Выпуск WDTT Plus v12

This commit is contained in:
Ivan4537 committed 2026-07-29 15:26:22 +03:00
1 parent b3aad32990
commit cd441e604e
108 files changed
+22105 -1969

No files matched your search

+16
View File
@@ -3,6 +3,7 @@
.kotlin/
build/
local.properties
/release-audit
.env
.env.*
!.env.example
@@ -44,13 +45,26 @@ server
*.p12
*.pfx
*.mobileprovision
*.db
*.sqlite
*.sqlite3
*.kdbx
id_rsa
id_rsa.pub
id_ed25519
id_ed25519.pub
known_hosts
known_hosts.*
google-services.json
service-account*.json
firebase-service-account*.json
credentials*.json
secrets*.json
.codex-local
.codex-local/
AGENTS.md
docs/*.md
docs/**/*.md
# ===== IDE =====
.idea/
@@ -73,3 +87,5 @@ Desktop.ini
*.rej
msg.txt
*.bat
cmd/wdtt-load
cmd/wdtt-load/
+41 -1
View File
@@ -2,6 +2,46 @@
Здесь фиксируются заметные пользовательские изменения WDTT Plus.
## v12 — 29.07.2026
### Туннель и профили
- Настройки подключения разделены на способы «Ссылка WDTT» и «Вручную».
- Уведомление, плитка и виджеты показывают профиль, с которого действительно запущен VPN. Исправлены повторные подключения и быстрое переключение между профилями.
### VK и перенос подключения
- Подключение через VK сначала использует быстрый способ без капчи, а при необходимости автоматически переходит к совместимым резервным вариантам.
- Для отдельного профиля можно добавить собственные резервные `Client ID` и `Client secret`; приложение проверяет их, а секрет хранит в защищённом хранилище устройства. Изменение этих настроек во время работающего VPN блокируется. Этот вариант нужен только старым приложениям с прежними TURN-цепочками VK.
- Окно VK-хешей умеет вставлять сразу несколько ссылок или хешей, заполнять свободные поля, заменять весь набор и очищать отдельные значения.
- Добавлена пошаговая справка по получению VK-хешей через ссылки `vk.ru` и `vk.com`.
- Подключение клиента можно передать ссылкой, QR-кодом или файлом без VK-хеша: получатель добавит собственный перед первым запуском.
- Файлы `.wdtt` можно открыть через Android или выбрать в настройках профилей.
### Сеть и исключения
- Подключение стало устойчивее: приложение перебирает доступные TURN-адреса и при необходимости использует резервные TCP/TLS-пути.
- DNS автоматически подстраивается под сеть устройства, в том числе при проблемах подключения в мобильной сети Ростелекома.
- Улучшено восстановление VPN после выхода из доверенной Wi-Fi, пробуждения телефона и смены сети.
- «Быстрые исключения» дополнены приложениями из актуальных белых списков мобильного интернета, а навигация по длинному списку стала удобнее.
### Сервер, диагностика и обновления
- После обновления владельцу настроенного сервера предлагается обновить серверную часть с сохранением клиентов и настроек. «Деплой» показывает установленную версию сервера.
- Сервер точнее соблюдает сроки клиентских доступов и ограничения отдельных профилей, а также лучше защищён от всплесков подключений.
- В карточке «Клиенты и сервер» считаются только устройства клиентов. Устройства владельца вынесены отдельно в обзор сервера.
- «Перенос сервера» сохраняет настройки, сроки доступа, статистику и устройства владельца, адаптирует профили к адресу и портам нового сервера и проверяет целостность новых файлов экспорта. Старые файлы остаются совместимыми.
- Переработан раздел «Выходной IP и прокси»: для локального и внешнего прокси, WARP, WireGuard и дополнительного VPS доступны корректные проверка, отключение и удаление. Настройки сохраняются после перезагрузки, а при ошибке восстанавливается прежний рабочий выход.
- Диагностика точнее проверяет сеть телефона, DNS, доступность VK и фактический выход сервера в интернет. Сообщения о неполадках прокси стали понятнее и выводятся по-русски.
- Перед установкой встроенное обновление проверяет, что APK получен из официального выпуска, не повреждён и подписан тем же ключом, что установленное приложение.
### Готовые профили и поддержка проекта
- Появилась возможность автоматически получить и добавить готовый профиль через Telegram-бота.
- Для таких профилей доступно автоматическое получение VK-хешей.
- Приложение следит за сроком доступа готового профиля и обновляет его состояние после продления.
- Реализовано получение резервного профиля через сообщество VK.
## v11 — 07.07.2026
### Туннель
@@ -139,7 +179,7 @@
### Передача и перенос данных
- Приём и передача подключения находятся в плавающей кнопке «Настройки» → «Передать или получить»: раздел «Получение VPN» принимает QR, изображение из галереи или файл, а раздел «Передача VPN» создаёт QR, ссылку или файл текущего VPN-профиля.
- Приём и передача подключения находятся в плавающей кнопке «Настройки» → «Передать или получить»: раздел «Получить профиль» принимает QR, изображение из галереи или файл, а раздел «Передать профиль» создаёт QR, ссылку или файл текущего VPN-профиля.
- VPN-профиль можно передать ссылкой, файлом или QR-кодом, а принять — через Android share, выбор файла, камеру или изображение из галереи.
- QR-коды передачи создаются единообразно во всех местах приложения, с подписью WDTT Plus и иконкой приложения рядом с кодом или под ним.
- Добавлен выбор профиля для замены при импорте подключения.
+24 -22
View File
@@ -44,28 +44,30 @@
### Что изменено в модификации
- **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Клиента можно перенести отдельно через QR, камеру, изображение, файл, Android Share или код передачи; создать с автоматическим или заданным вручную паролем и безопасно сменить пароль без перезапуска сервера. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями.
- **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Клиента можно перенести отдельно через QR, камеру, изображение, файл, Android Share или код передачи; создать с автоматическим или заданным вручную паролем и безопасно сменить пароль без перезапуска сервера. Сервер защищён от всплесков подключений и поддерживает пределы мощности и скорости для отдельного доступа. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями.
- **Обновление, восстановление и перенос сервера:** повторный деплой предлагает безопасное обновление с сохранением данных или чистую установку. Перед обновлением и прямым импортом создаётся страховочная копия; служба и целостность доступов проверяются, а при ошибке выполняется откат. Частичный экспорт переносит базу WDTT Plus, полный дополнительно сохраняет WireGuard-ключи сервера.
- **Ссылки, роли и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Импорт проверяется и занимает свободный VPN-профиль; при трёх занятых приложение запрашивает выбор профиля для замены. Переименованный профиль передаёт своё название вместе с подключением. Для администратора доступен защищённый паролем перенос локальных настроек.
- **Проверка VK-хешей:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Хеши можно копировать по одному или все заполненные сразу в порядке слотов. Настройка мощности сопровождается пояснением о потоках, нагрузке и частоте проверок VK.
- **Режимы пользователя и администратора:** режим «Юзер» оставляет подключение по ссылке или вручную, управление VPN, исключения и логи без серверных полей. Режим «Админ» открывает деплой и полное управление собственным сервером.
- **Ссылки и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Администратор может отправить клиентский доступ ещё до добавления VK-хеша — получатель заполнит его у себя перед запуском. Защищённая короткая ссылка может сразу добавить выданный доступ и предложить автоматическое либо ручное заполнение VK-хешей. Импорт занимает свободный VPN-профиль или предлагает выбрать заменяемый, сохраняет название и при наличии показывает установленный владельцем предел мощности. Полученный профиль показывает срок и доступное действие, а после окончания доступа не запускает VPN. Для администратора доступен защищённый паролем перенос локальных настроек.
- **VK-хеши и независимые провайдеры:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Несколько ссылок или хешей можно вставить из буфера сразу, не затирая заполненные поля без подтверждения. TURN-данные запрашиваются по порядку: быстрый VKCalls без капчи, собственные legacy-реквизиты (если включены), затем выбранные встроенные legacy Client ID; пользовательский secret хранится защищённо.
- **Настраиваемый выходной IP:** из Android и Telegram-бота управляются прямой выход, прокси VPS, внешний TCP-прокси, бесплатный WARP, готовый VPN/WireGuard-файл и WireGuard-выход через другой сервер. Приложение показывает состояние режимов на сервере, проверяет конфликтные маршруты перед включением и откатывается при ошибке.
- **Маршрутизация приложений:** ЧС и БС являются отдельными списками: в ЧС отмеченные приложения обходят VPN, в БС только отмеченные идут через VPN. Есть быстрый подбор приложений, чувствительных к VPN; смена режима перезапускает только WireGuard-слой.
- **Доверенные сети Wi-Fi:** VPN может автоматически переходить в ожидание в выбранных домашних или рабочих сетях и восстанавливать прежнее подключение после выхода из них. Ручное отключение отменяет автовосстановление, а неопределённая сеть никогда не отключает VPN.
- **Captcha и устойчивость транспорта:** перед captcha-цепочкой можно использовать VKCalls preflight; временный flood не создаёт повторный шквал запросов. Авто-режим начинает с Auto WebView и переходит к Go v2 и ручному WebView только при необходимости. Расширены восстановление после смены сети и пробуждения, контроль зависшего трафика и fail-open отключение неработающего VPN.
- **Доверенные сети Wi-Fi:** VPN может автоматически переходить в ожидание в выбранных домашних или рабочих сетях и восстанавливать прежнее подключение после выхода из них. Восстановление устойчивее работает в фоне и после пробуждения телефона; ручное отключение отменяет его, а неопределённая сеть никогда не отключает VPN.
- **Captcha и устойчивость транспорта:** современный VKCalls используется первым и обычно не требует капчи; временный flood не создаёт повторный шквал запросов. Если нужен legacy-резерв, авто-режим начинает с Auto WebView и переходит к Go v2 и ручному WebView только при необходимости. Клиент использует актуальные адреса `vk.ru`, выбирает рабочий DNS-путь и перебирает резервные TURN-соединения по UDP, TCP и TLS.
- **Диагностика телефона и VPS:** проверка устройства отдельно тестирует системный DNS, DNS-путь клиента, основной VKCalls и резервные VK/OK-узлы из сети телефона. Серверная диагностика сосредоточена на службе, UDP-портах, маршрутизации и выходном интернете; доступ к VK/OK с самого VPS показывается только справочно и не создаёт ложную ошибку.
- **Самостоятельная сборка WDTT Plus:** приложение использует пакет `com.wdtt.plus`, собственный канал обновлений и отдельное оформление. Gradle пересобирает Android `libclient.so` и сервер для деплоя из исходников, а release APK получает понятные имена для каждой ABI.
## Возможности Android-версии
- **Ориентир совместимости:** WDTT Plus смотрит вперёд и ориентируется на Android 10+ с современными требованиями Android SDK. `targetSdk` 35 — это целевой API сборки, а не верхний предел Android: новые версии Android должны поддерживаться по мере тестирования, включая отдельную проверку нативной части на устройствах с 16 KB page size. Android 9 и ниже не являются основной целью поддержки.
- **Проверка устройства:** при первом запуске приложение в фоне проверяет только архитектурные условия — Android, ABI, нативный клиент, память и размер страницы памяти — и предупреждает, если есть риск несовместимости. В **«Инфо»** доступна ручная расширенная проверка версии WDTT Plus, WebView, сети, разрешений Android, текущего состояния VPN и подсказок для настроек.
- **Проверка устройства:** при первом запуске приложение в фоне проверяет только архитектурные условия — Android, ABI, нативный клиент, память и размер страницы памяти — и предупреждает, если есть риск несовместимости. В **«Инфо»** доступна ручная расширенная проверка версии WDTT Plus, WebView, разрешений Android, системного и клиентского DNS, доступа к VK/OK и текущего состояния VPN.
- **Полноценный VPN-режим:** приложение использует `VpnService` и WireGuard GoBackend, поэтому трафик выбранных приложений проходит через системный VPN-интерфейс без ручного импорта конфигов.
- **Три профиля подключения:** VPN 1, VPN 2 и VPN 3 хранят отдельные настройки туннеля и деплоя; профиль можно переименовать долгим нажатием в боковых настройках. Название активного профиля видно в заголовках вкладок, передаче подключения, плитке быстрых настроек и активном уведомлении туннеля.
- **Три профиля подключения:** VPN 1, VPN 2 и VPN 3 хранят отдельные настройки туннеля и деплоя; профиль можно переименовать долгим нажатием в боковых настройках. Название активного профиля видно в заголовках вкладок, передаче подключения, плитке быстрых настроек и активном уведомлении туннеля. Полученный профиль может иметь собственный предел мощности, который показывается рядом с регулятором и не влияет на остальные профили.
- **Корректная передача VPN-слота:** если Android отключает WDTT Plus VPN или другой VPN забирает системный VPN-слот, WDTT Plus останавливает транспорт и переводит плитку/виджет в неактивное состояние. Плитка запускает VPN как с обычными настройками, так и в режиме ссылки, а при активном подключении показывает выбранный профиль вместе с уведомлением туннеля.
- **Доверенные сети Wi-Fi:** в боковых настройках можно добавить текущую сеть или точный SSID вручную. В доверенной сети системный VPN-интерфейс снимается и интернет работает напрямую, а тихое уведомление сохраняет режим ожидания. После перехода на мобильную или другую Wi-Fi сеть прежний VPN-профиль восстанавливается. Android запрашивает доступ к местоположению только потому, что относит имя Wi-Fi к чувствительным данным; координаты приложение не получает.
- **TURN/DTLS-транспорт:** нативный Go-клиент получает временные TURN-учётные данные VK-звонка и поднимает DTLS-соединения к relay-серверу, через который передаётся трафик до вашего сервера.
- **TURN/DTLS-транспорт:** нативный Go-клиент получает временные TURN-учётные данные VK-звонка и поднимает DTLS-соединения к relay-серверу, через который передаётся трафик до вашего сервера. Если основной TURN-путь не отвечает, клиент пробует другие выданные адреса и доступные варианты UDP, TCP или TLS.
- **Импорт VK-ссылок через «Поделиться»:** ссылку VK-звонка можно отправить прямо в WDTT Plus. Приложение извлечёт хеш после `/call/join/`, заполнит следующий слот VK-хеша и покажет, какой номер был обновлён.
- **Передача между устройствами:** текущий VPN-профиль отправляется как `wdtt://`-ссылка, файл или QR-код. Приложение принимает эти данные через Android, камеру, галерею и выбор файла, сохраняя совместимость со старыми ссылками.
- **Проверка VK-хешей:** окно VK-хешей умеет проверить, жив ли групповой звонок, решить VK Captcha в процессе проверки, показать понятный статус по каждому полю и скопировать один или все заполненные хеши.
- **Передача и получение подключения:** текущий VPN-профиль отправляется как `wdtt://`-ссылка, файл или QR-код. Приложение принимает эти данные через Android, камеру, галерею и выбор файла, сохраняя совместимость со старыми ссылками. Клиентский доступ можно передать без VK-хеша, чтобы получатель добавил собственный перед запуском. Защищённая короткая ссылка также может добавить выданный профиль без VK-хешей, после чего приложение предложит получить их автоматически или ввести вручную.
- **Проверка VK-хешей:** окно VK-хешей умеет проверить, жив ли групповой звонок, решить VK Captcha в процессе проверки, показать понятный статус по каждому полю, очистить отдельный слот и скопировать один или все заполненные хеши. Из буфера можно вставить до четырёх ссылок или хешей сразу с выбором: заполнить свободные поля или заменить набор.
- **TLS/HTTP-отпечаток:** по умолчанию используется Firefox fingerprint, при необходимости его можно переключить в настройках приложения.
- **WRAP без захардкоженного ключа:** внешний RTP AEAD/ChaCha20-Poly1305 слой выводится из пароля подключения через HKDF. Один пароль — один WRAP-ключ, ключ не хранится в APK.
- **RTP AEAD обфускация:** транспорт маскируется под RTP/WebRTC аудиотрафик с OPUS payload type, а полезная нагрузка шифруется AEAD-слоем поверх DTLS/WireGuard.
@@ -75,11 +77,11 @@
- **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит пользовательских паролей, 16-символьную генерацию, ручное задание пароля с проверками, привязку к устройству и срок действия. Клиентов можно создавать, импортировать, экспортировать, отключать, продлевать, отвязывать, удалять и менять им пароль из приложения или Telegram-бота.
- **Горячее обновление WRAP-ключей:** создание, удаление и истечение паролей обновляют набор WRAP-ключей на сервере без перезапуска ядра.
- **Исключения приложений:** ЧС и БС хранят независимые наборы. В ЧС отмеченные приложения работают напрямую, в БС только отмеченные направляются в VPN; изменения применяются быстрой перезагрузкой WireGuard.
- **Рабочая captcha-цепочка:** сначала приложение пробует получить TURN credentials через отключаемый VKCalls preflight. Если анонимный вход недоступен, Auto WebView решает обычную проверку, Go v2 используется как следующий автоматический этап, а ручной WebView остаётся fallback для slider/puzzle и других строгих проверок.
- **Живой лог-вьюер:** события Go-клиента, DTLS, WireGuard, WRAP, капчи, деплоя и статистики отображаются с группировкой повторов. Временные сбои показываются как предупреждения, а красным выделяются критические ошибки. После отключения итоговый трафик и доступная причина сохраняются, а завершённая сессия отображается неактивной.
- **Фоновая устойчивость:** `Foreground Service`, `WakeLock`, `WifiLock`, мягкий reconnect по валидированной сети и проверка после пробуждения помогают переживать Doze, смену Wi-Fi/LTE, DNS-сбои до VK и падение нативного процесса без агрессивных перезапусков.
- **VK Auth fallback:** клиент использует 2 проверенных VK `client_id` и переключается между ними при ошибках авторизации.
- **DNS fallback:** сначала используются Yandex DNS `77.88.8.8` / `77.88.8.1`, а при отказе или таймаутах выполняется fallback на системный провайдерский DNS устройства.
- **Рабочая цепочка VK:** сначала приложение пробует современный отключаемый VKCalls без капчи, затем собственный legacy Client ID и выбранные встроенные legacy ID. Для legacy-провайдеров Auto WebView решает обычную проверку, Go v2 используется как следующий автоматический этап, а ручной WebView остаётся fallback для slider/puzzle и других строгих проверок.
- **Живой лог-вьюер:** события Go-клиента, выбранного VK-провайдера, переходов между резервами, DTLS, WireGuard, WRAP, капчи, деплоя и статистики отображаются с группировкой повторов. Временные сбои показываются как предупреждения, а красным выделяются критические ошибки. После отключения итоговый трафик и доступная причина сохраняются, а завершённая сессия отображается неактивной.
- **Фоновая устойчивость:** `Foreground Service`, `WakeLock`, `WifiLock`, мягкий reconnect по валидированной сети и проверка после пробуждения помогают переживать Doze, смену Wi-Fi/LTE, DNS-сбои до VK и падение нативного процесса без агрессивных перезапусков. Выход из доверенной Wi-Fi дополнительно контролируется до фактического восстановления VPN.
- **VK Auth fallback:** собственные legacy-реквизиты не заменяют быстрый VKCalls и встроенную цепочку, а добавляются между ними как отдельный резерв. Ошибка собственного Client ID явно отображается в журнале, после чего клиент пробует выбранные встроенные ID.
- **DNS fallback:** клиент проверяет основной и резервный Yandex DNS по UDP, затем по TCP, а при их недоступности использует системный DNS устройства.
- **Темы и оформление:** Material 3, Jetpack Compose, Inter, светлая/тёмная тема, Dynamic Colors на Android 12+ и встроенные палитры.
- **Автообновления:** приложение проверяет релизы WDTT Plus при запуске, при возврате из фона не чаще одного раза в 5 минут и каждые 30 минут, если остаётся открытым. Подходящий APK скачивается внутри приложения и передаётся системному установщику Android. Если APK текущей версии был заменён в релизе, WDTT Plus сверяет SHA-256 установленного APK со всеми APK релиза и предлагает исправление текущей версии.
@@ -103,7 +105,7 @@ Android-приложение → VpnService / WireGuard GoBackend → локал
1. Соберите APK по разделу [«Для разработки»](#для-разработки) или скачайте готовую сборку со [страницы релизов WDTT Plus](https://github.com/Ivan4537/WDTT-Plus/releases), когда она опубликована.
2. Установите приложение на Android-смартфон. Основной ориентир совместимости — Android 10+.
3. Подготовьте домен или IP сервера, SSH-логин и SSH-пароль.
4. В VK создайте или откройте групповой звонок и отправьте ссылку вида `vk.com/call/join/xxxxxxxxxxx` в WDTT Plus через **«Поделиться»** либо скопируйте её вручную.
4. В VK создайте или откройте групповой звонок и отправьте ссылку вида `vk.ru/call/join/xxxxxxxxxxx` в WDTT Plus через **«Поделиться»** либо скопируйте её вручную. Старые ссылки `vk.com/call/join/...` также поддерживаются.
5. Откройте **WDTT Plus** и перейдите во вкладку **«Деплой»**.
6. Введите IP/домен сервера, SSH-логин, пароль и SSH-порт.
7. В **«Секретах»** задайте главный пароль туннеля. При необходимости добавьте Telegram `admin_id` / `bot_token` для управления доступом.
@@ -124,7 +126,7 @@ VK → группа → звонок → ссылка приглашения →
1. Откройте VK и создайте пустую группу или используйте существующую.
2. Начните групповой звонок.
3. Отправьте ссылку приглашения в WDTT Plus через системное меню **«Поделиться»** или скопируйте её вручную.
4. Приложение само разбирает полную ссылку `vk.com/call/join/...`, убирает лишние параметры и заполняет первое свободное поле VK-хеша в активном VPN-профиле.
4. Приложение само разбирает полную ссылку `vk.ru/call/join/...` (и старый вариант `vk.com/call/join/...`), убирает лишние параметры и заполняет первое свободное поле VK-хеша в активном VPN-профиле.
5. Если такой хеш уже добавлен, WDTT Plus покажет ошибку и не создаст дубль. Если все 4 поля заняты, будет обновлён следующий слот по кругу с предупреждением о перезаписи.
6. Можно использовать до **4 хешей** одновременно для распределения нагрузки и увеличения доступного числа потоков.
@@ -158,7 +160,7 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se
В блоке **«Клиенты и сервер»** вкладки **«Деплой»** можно искать и фильтровать клиентов, создавать доступы с автоматическим или ручным паролем, редактировать параметры, срок и привязку устройства, менять пароль, а также передавать подключение ссылкой, файлом или QR-кодом. Там же доступны экспорт и импорт отдельного клиента для ручного переноса на другой сервер, история, трафик, настройки сервера, очистка устаревших записей и сервисные действия. После импорта приложение перечитывает список сервера и выбирает добавленного клиента.
Экспорт отдельного клиента переносит только данные доступа: пароль, название, VK-хеши, срок и состояние. Устройство, WireGuard-ключи, статистика, история, адрес, порты и серверные параметры не копируются; после импорта клиент использует настройки нового сервера и привязывается к устройству при первом подключении.
Экспорт отдельного клиента переносит только данные доступа: пароль, название, имеющиеся VK-хеши, срок и состояние. Устройство, WireGuard-ключи, статистика, история, адрес, порты и серверные параметры не копируются; после импорта клиент использует настройки нового сервера и привязывается к устройству при первом подключении.
Обычные изменения применяются работающим сервером сразу и не прерывают остальных клиентов: Android вызывает admin-команды по SSH, а они обращаются к закрытому локальному сокету `wdtt-server`, не открывая отдельный управляющий порт в сеть. Явный перезапуск сервиса оставлен отдельным подтверждаемым действием. При удалении или истечении пароля соответствующий WRAP-ключ удаляется из памяти сервера.
@@ -166,12 +168,12 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se
#### Передача между устройствами
Раздел **«Передать или получить»** находится в боковых настройках. Пользователь может отправить активный VPN-профиль ссылкой, файлом или QR-кодом; на другом устройстве данные можно открыть напрямую, выбрать как файл, отсканировать камерой либо распознать на изображении из галереи. Приложение использует первый пустой профиль VPN, а если заняты все три — предлагает выбрать профиль и подтвердить замену. Названия профилей помогают отличать подключения в заголовках вкладок «Туннель» и «Деплой».
Раздел **«Передать или получить»** находится в боковых настройках. Пользователь может отправить активный VPN-профиль ссылкой, файлом или QR-кодом; на другом устройстве данные можно открыть напрямую, выбрать как файл, отсканировать камерой либо распознать на изображении из галереи. Доступ без VK-хеша тоже распознаётся и сохраняется, но перед запуском получатель должен добавить собственный. Приложение использует первый пустой профиль VPN, а если заняты все три — предлагает выбрать профиль и подтвердить замену. Названия профилей помогают отличать подключения в заголовках вкладок «Туннель» и «Деплой».
В режиме администратора там же можно передать все локальные VPN-профили, параметры деплоя, исключения и настройки выхода. Такой экспорт шифруется отдельным паролем; пароль не сохраняется и должен передаваться получателю отдельно. Резервная копия состояния самого сервера по-прежнему импортируется через **«Деплой» → «Перенос сервера»**.
> [!WARNING]
> Ссылка и пользовательский QR содержат пароль подключения и VK-хеши. Не публикуйте их и передавайте только доверенному получателю.
> Ссылка и пользовательский QR всегда содержат пароль подключения и могут содержать VK-хеши. Не публикуйте их и передавайте только доверенному получателю.
#### Исключения приложений
@@ -179,11 +181,11 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se
#### Капча
По умолчанию включён режим **«Авто капча»**: приложение пробует VKCalls, затем Auto WebView, Go v2 и при необходимости ручной WebView. Slider/puzzle считается строгой проверкой VK и передаётся пользователю. Вместо автоматической цепочки можно выбрать **«Всегда вручную»**. Ошибки мёртвой ссылки, запрета анонимного входа и переполненного звонка выводятся отдельно и не маскируются под бесконечное решение капчи.
По умолчанию включены быстрый **VKCalls** и режим **«Авто капча»**. Сначала TURN-данные запрашиваются через VKCalls без капчи. Если он недоступен, приложение пробует собственный legacy Client ID (если включён), затем встроенные legacy ID; только в этой резервной ветке используются Auto WebView, Go v2 и при необходимости ручной WebView. Slider/puzzle считается строгой проверкой VK и передаётся пользователю. Вместо автоматического решения можно выбрать **«Всегда вручную»**. Ошибки мёртвой ссылки, запрета анонимного входа и переполненного звонка выводятся отдельно.
#### Логирование
Вкладка **«Логи»** показывает статус получения VK-учётных данных, решение капчи, DTLS-handshake, WRAP-состояние, готовность WireGuard, статистику активных воркеров и ошибки. Повторяющиеся строки схлопываются в одну запись со счётчиком.
Вкладка **«Логи»** показывает старт быстрого VKCalls, переходы на собственный и встроенный legacy-провайдеры, использование кэша TURN, решение капчи, DTLS-handshake, WRAP-состояние, готовность WireGuard, статистику активных воркеров и ошибки. Ожидаемый переход на резерв не помечается как критическая ошибка; повторяющиеся строки схлопываются в одну запись со счётчиком.
> [!NOTE]
> Если видны DTLS handshake, но `Активных: 0`, чаще всего указан неправильный пароль подключения или используется сервер без актуального WRAP-протокола. Если часть потоков уже активна, одиночные DTLS timeout больше не считаются неверным паролем и не останавливают туннель.
+549 -35
View File
@@ -2,6 +2,8 @@ package main
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"flag"
@@ -14,18 +16,30 @@ import (
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"golang.zx2c4.com/wireguard/device"
)
type adminResponse struct {
OK bool `json:"ok"`
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
RestartRequired bool `json:"restart_required,omitempty"`
Server *adminServerInfo `json:"server,omitempty"`
Password *adminPasswordInfo `json:"password,omitempty"`
Passwords []adminPasswordInfo `json:"passwords,omitempty"`
ClientState *adminClientState `json:"client_state,omitempty"`
}
type adminClientState struct {
Version int `json:"version"`
Password string `json:"password"`
DownBytes int64 `json:"down_bytes"`
UpBytes int64 `json:"up_bytes"`
Traffic []TrafficBucket `json:"traffic,omitempty"`
TrafficImports map[string]TrafficImport `json:"traffic_imports,omitempty"`
BindHistory []BindHistoryEntry `json:"bind_history,omitempty"`
}
type adminRequest struct {
@@ -33,28 +47,101 @@ type adminRequest struct {
Args []string `json:"args"`
}
type adminCommandError struct {
code string
message string
}
func (e *adminCommandError) Error() string {
if e == nil {
return ""
}
return e.message
}
func newAdminCommandError(code, message string) error {
return &adminCommandError{code: code, message: message}
}
func adminErrorResponse(err error) adminResponse {
response := adminResponse{OK: false}
if err == nil {
return response
}
response.Message = err.Error()
var coded *adminCommandError
if errors.As(err, &coded) {
response.Code = coded.code
}
return response
}
type adminLiveSnapshot struct {
password string
device *ClientDevice
}
type adminServerInfo struct {
WDTTPlusVersion string `json:"wdtt_plus_version"`
BinarySHA256 string `json:"binary_sha256,omitempty"`
WGBackend string `json:"wg_backend,omitempty"`
ConfigDir string `json:"config_dir"`
PublicIP string `json:"public_ip,omitempty"`
EffectivePublic string `json:"effective_public_ip,omitempty"`
DNS string `json:"dns,omitempty"`
DefaultPorts string `json:"default_ports"`
MaxPasswords int `json:"max_passwords"`
MaxWorkersPerAccess int `json:"max_workers_per_access"`
MaxClientMbps float64 `json:"max_client_mbps"`
PasswordCount int `json:"password_count"`
ActivePasswordCount int `json:"active_password_count"`
RetainedExpiredCount int `json:"retained_expired_count"`
AvailablePasswordCount int `json:"available_password_count"`
DeviceCount int `json:"device_count"`
OwnerDeviceCount int `json:"owner_device_count"`
ExpiredCount int `json:"expired_count"`
OrphanDeviceCount int `json:"orphan_device_count"`
ActiveConnections int32 `json:"active_connections"`
CPUPercent float64 `json:"cpu_percent"`
MemoryPercent float64 `json:"memory_percent"`
NetworkRxMbps float64 `json:"network_rx_mbps"`
NetworkTxMbps float64 `json:"network_tx_mbps"`
PacketDrops int64 `json:"packet_drops"`
Reconnects int64 `json:"reconnects"`
HandshakeFailures int64 `json:"handshake_failures"`
HandshakeThrottles int64 `json:"handshake_throttles"`
WorkerLimitRejects int64 `json:"worker_limit_rejections"`
OrphanDevices []adminDeviceInfo `json:"orphan_devices,omitempty"`
Traffic adminTrafficPeriod `json:"traffic"`
AdminTraffic adminTrafficPeriod `json:"admin_traffic"`
AdminProfile AdminProfileEntry `json:"admin_profile,omitempty"`
}
var (
runningBinarySHA256Once sync.Once
runningBinarySHA256Sum string
)
func runningBinarySHA256() string {
runningBinarySHA256Once.Do(func() {
executable, err := os.Executable()
if err != nil {
return
}
source, err := os.Open(executable)
if err != nil {
return
}
defer source.Close()
digest := sha256.New()
if _, err := io.Copy(digest, source); err != nil {
return
}
runningBinarySHA256Sum = fmt.Sprintf("%x", digest.Sum(nil))
})
return runningBinarySHA256Sum
}
type adminTrafficValue struct {
Down int64 `json:"down"`
Up int64 `json:"up"`
@@ -92,6 +179,7 @@ type adminPasswordInfo struct {
Ports string `json:"ports"`
Status string `json:"status"`
ExpiresAt int64 `json:"expires_at,omitempty"`
PurgeAfter int64 `json:"purge_after,omitempty"`
DownBytes int64 `json:"down_bytes,omitempty"`
UpBytes int64 `json:"up_bytes,omitempty"`
DeviceID string `json:"device_id,omitempty"`
@@ -154,7 +242,7 @@ func runAdminCLI(args []string) int {
return 0
}
func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDev *device.Device, live bool) (adminResponse, error) {
func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDev wgDevice, live bool) (adminResponse, error) {
var response adminResponse
var err error
snapshot := captureAdminLiveSnapshot(loaded, rest)
@@ -170,8 +258,12 @@ func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDe
}
case "details":
response, err = adminPasswordDetails(configDir, loaded, rest[1:])
case "export-client-state":
response, err = adminExportClientState(configDir, loaded, rest[1:])
case "create":
response, err = adminCreatePassword(configDir, loaded, rest[1:])
case "import-client-state":
response, err = adminImportClientState(configDir, loaded, rest[1:])
case "delete":
response, err = adminDeletePassword(configDir, loaded, rest[1:])
case "unbind":
@@ -186,6 +278,8 @@ func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDe
response, err = adminSetPasswordHash(configDir, loaded, rest[1:])
case "set-expiry":
response, err = adminSetPasswordExpiry(configDir, loaded, rest[1:])
case "set-retention":
response, err = adminSetPasswordRetention(configDir, loaded, rest[1:])
case "set-ports":
response, err = adminSetPasswordPorts(configDir, loaded, rest[1:])
case "set-password":
@@ -212,6 +306,8 @@ func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDe
response, err = adminCleanupOrphans(configDir, loaded, wgDev, live)
case "reset-traffic":
response, err = adminResetTraffic(configDir, loaded)
case "merge-client-traffic":
response, err = adminMergeClientTraffic(configDir, loaded, rest[1:])
case "restart":
response = adminResponse{OK: true, Message: "Перезапуск сервиса", RestartRequired: true}
default:
@@ -268,7 +364,7 @@ func captureAdminLiveSnapshot(loaded *Database, args []string) adminLiveSnapshot
}
}
func applyLiveAdminEffects(configDir string, loaded *Database, args []string, response adminResponse, snapshot adminLiveSnapshot, wgDev *device.Device) error {
func applyLiveAdminEffects(configDir string, loaded *Database, args []string, response adminResponse, snapshot adminLiveSnapshot, wgDev wgDevice) error {
if len(args) == 0 {
return nil
}
@@ -287,16 +383,16 @@ func applyLiveAdminEffects(configDir string, loaded *Database, args []string, re
return fmt.Errorf("не удалось добавить WRAP-ключ: %w", err)
}
case "delete":
if !isAdminSnapshotDevice(loaded, snapshot) {
if shouldRemoveAdminSnapshotPeer(loaded, snapshot) {
removePeerFromWG(wgDev, snapshot.device)
}
serverWrapKeys.RemovePassword(snapshot.password)
case "unbind":
if !isAdminSnapshotDevice(loaded, snapshot) {
if shouldRemoveAdminSnapshotPeer(loaded, snapshot) {
removePeerFromWG(wgDev, snapshot.device)
}
case "deactivate":
if !isAdminSnapshotDevice(loaded, snapshot) {
if shouldRemoveAdminSnapshotPeer(loaded, snapshot) {
removePeerFromWG(wgDev, snapshot.device)
}
serverWrapKeys.RemovePassword(snapshot.password)
@@ -314,9 +410,10 @@ func applyLiveAdminEffects(configDir string, loaded *Database, args []string, re
return errors.New("сервер изменил пароль клиента без нового значения")
}
newPassword := response.Password.Password
if response.Password.Status == "active" {
entry := loaded.Passwords[newPassword]
if entry != nil && !entry.IsDeactivated && !isPasswordPurgeable(entry) {
if err := serverWrapKeys.AddPassword(newPassword); err != nil {
if entry := loaded.Passwords[newPassword]; entry != nil {
if entry != nil {
delete(loaded.Passwords, newPassword)
loaded.Passwords[snapshot.password] = entry
_ = saveAdminDB(configDir, loaded)
@@ -325,9 +422,21 @@ func applyLiveAdminEffects(configDir string, loaded *Database, args []string, re
}
}
serverWrapKeys.RemovePassword(snapshot.password)
if !isAdminSnapshotDevice(loaded, snapshot) {
if shouldRemoveAdminSnapshotPeer(loaded, snapshot) {
removePeerFromWG(wgDev, snapshot.device)
}
case "set-expiry":
if response.Password == nil {
return errors.New("сервер обновил срок клиента без состояния доступа")
}
password := response.Password.Password
if response.Password.Status == "active" {
if err := serverWrapKeys.AddPassword(password); err != nil {
return fmt.Errorf("не удалось вернуть WRAP-ключ после продления: %w", err)
}
} else if response.Password.Status == "deactivated" {
serverWrapKeys.RemovePassword(password)
}
case "set-dns", "update-settings":
setServerDNS(loaded.DNS)
setServerDefaultPorts(loaded.DefaultPorts)
@@ -357,6 +466,13 @@ func isAdminSnapshotDevice(loaded *Database, snapshot adminLiveSnapshot) bool {
return ok
}
func shouldRemoveAdminSnapshotPeer(loaded *Database, snapshot adminLiveSnapshot) bool {
if snapshot.device == nil || isAdminSnapshotDevice(loaded, snapshot) {
return false
}
return !databaseUsesDeviceIDExcept(loaded, snapshot.device.DeviceID, snapshot.password)
}
func adminSocketPath(configDir string) string {
if filepath.Clean(configDir) == "/etc/wdtt" {
return "/run/wdtt/admin.sock"
@@ -381,7 +497,7 @@ func callAdminSocket(configDir string, request adminRequest) (adminResponse, err
return response, nil
}
func startAdminSocket(ctx context.Context, configDir string, wgDev *device.Device) error {
func startAdminSocket(ctx context.Context, configDir string, wgDev wgDevice) error {
path := adminSocketPath(configDir)
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
@@ -419,7 +535,7 @@ func startAdminSocket(ctx context.Context, configDir string, wgDev *device.Devic
return nil
}
func handleAdminSocketConn(conn net.Conn, configDir string, wgDev *device.Device) {
func handleAdminSocketConn(conn net.Conn, configDir string, wgDev wgDevice) {
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(15 * time.Second))
var request adminRequest
@@ -439,7 +555,7 @@ func handleAdminSocketConn(conn net.Conn, configDir string, wgDev *device.Device
}
response, err := executeAdminCommand(configDir, db, request.Args, wgDev, true)
if err != nil {
response = adminResponse{OK: false, Message: err.Error()}
response = adminErrorResponse(err)
}
_ = json.NewEncoder(conn).Encode(response)
}
@@ -620,19 +736,43 @@ func saveAdminDB(configDir string, loaded *Database) error {
func buildAdminServerInfo(configDir string, loaded *Database) *adminServerInfo {
expired := 0
active := 0
retainedExpired := 0
occupied := 0
nowUnix := time.Now().Unix()
usedDevices := make(map[string]struct{})
clientDevices := make(map[string]struct{})
for _, entry := range loaded.Passwords {
if entry == nil {
continue
}
if isPasswordExpired(entry) {
if !isPasswordPurgeableAt(entry, nowUnix) {
occupied++
}
if isPasswordExpiredAt(entry, nowUnix) {
expired++
if isPasswordRetainedExpiredAt(entry, nowUnix) {
retainedExpired++
}
} else if !entry.IsDeactivated {
active++
}
if entry.DeviceID != "" {
usedDevices[entry.DeviceID] = struct{}{}
clientDevices[entry.DeviceID] = struct{}{}
}
for _, event := range entry.BindHistory {
deviceID := strings.TrimSpace(event.DeviceID)
if deviceID == "" || event.Status == "denied_mismatch" {
continue
}
if event.BoundAt > 0 || event.Status == "active" || event.Status == "unbound" {
clientDevices[deviceID] = struct{}{}
}
}
for deviceID := range adminDeviceIDSet(loaded) {
}
ownerDevices := adminDeviceIDSet(loaded)
for deviceID := range ownerDevices {
usedDevices[deviceID] = struct{}{}
}
orphans := 0
@@ -652,17 +792,41 @@ func buildAdminServerInfo(configDir string, loaded *Database) *adminServerInfo {
if effectivePublic == "" {
effectivePublic = publicIP
}
available := loaded.MaxPasswords - occupied
if available < 0 {
available = 0
}
maxWorkersPerAccess, maxClientMbps := configuredAccessRuntimeLimits()
return &adminServerInfo{
WDTTPlusVersion: wdttServerVersion,
BinarySHA256: runningBinarySHA256(),
WGBackend: activeWGBackend.Load(),
ConfigDir: configDir,
PublicIP: loaded.PublicIP,
EffectivePublic: effectivePublic,
DNS: loaded.DNS,
DefaultPorts: loaded.DefaultPorts,
MaxPasswords: loaded.MaxPasswords,
MaxWorkersPerAccess: maxWorkersPerAccess,
MaxClientMbps: maxClientMbps,
PasswordCount: len(loaded.Passwords),
DeviceCount: len(loaded.Devices),
ActivePasswordCount: active,
RetainedExpiredCount: retainedExpired,
AvailablePasswordCount: available,
DeviceCount: len(clientDevices),
OwnerDeviceCount: len(ownerDevices),
ExpiredCount: expired,
OrphanDeviceCount: orphans,
ActiveConnections: atomic.LoadInt32(&activeConns),
CPUPercent: runtimeCPUPercent(),
MemoryPercent: runtimeMemoryPercent(),
NetworkRxMbps: runtimeNetworkRxMbps(),
NetworkTxMbps: runtimeNetworkTxMbps(),
PacketDrops: atomic.LoadInt64(&runtimePacketDrops),
Reconnects: atomic.LoadInt64(&reconnectCount),
HandshakeFailures: atomic.LoadInt64(&handshakeFailures),
HandshakeThrottles: atomic.LoadInt64(&handshakeThrottles),
WorkerLimitRejects: atomic.LoadInt64(&workerLimitRejections),
OrphanDevices: orphanDevices,
Traffic: buildAdminDatabaseTraffic(loaded),
AdminTraffic: buildAdminTrafficPeriod(loaded.AdminTraffic, loaded.AdminDownBytes, loaded.AdminUpBytes),
@@ -711,6 +875,148 @@ func adminPasswordDetails(configDir string, loaded *Database, args []string) (ad
}, nil
}
func adminExportClientState(configDir string, loaded *Database, args []string) (adminResponse, error) {
password, err := adminPasswordArg("export-client-state", args)
if err != nil {
return adminResponse{}, err
}
entry, err := requireAdminPassword(loaded, password)
if err != nil {
return adminResponse{}, err
}
state := &adminClientState{
Version: 1,
Password: password,
DownBytes: entry.DownBytes,
UpBytes: entry.UpBytes,
Traffic: append([]TrafficBucket(nil), entry.Traffic...),
TrafficImports: cloneTrafficImports(entry.TrafficImports),
BindHistory: append([]BindHistoryEntry(nil), entry.BindHistory...),
}
return adminResponse{
OK: true,
Message: "Состояние клиента подготовлено",
Server: buildAdminServerInfo(configDir, loaded),
Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, password, entry)),
ClientState: state,
}, nil
}
func adminImportClientState(configDir string, loaded *Database, args []string) (adminResponse, error) {
fs := flag.NewFlagSet("import-client-state", flag.ContinueOnError)
fs.SetOutput(io.Discard)
password := fs.String("password", "", "пароль клиента")
operationID := fs.String("operation-id", "", "уникальный идентификатор переноса")
encoded := fs.String("state", "", "base64url-состояние клиента")
if err := fs.Parse(args); err != nil {
return adminResponse{}, err
}
key := strings.TrimSpace(*operationID)
if key == "" || len(key) > 160 {
return adminResponse{}, errors.New("operation-id должен содержать 1..160 символов")
}
entry, err := requireAdminPassword(loaded, strings.TrimSpace(*password))
if err != nil {
return adminResponse{}, err
}
if entry.TrafficImports != nil {
if _, applied := entry.TrafficImports[key]; applied {
return adminResponse{
OK: true,
Message: "Состояние клиента уже было перенесено",
Server: buildAdminServerInfo(configDir, loaded),
Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, strings.TrimSpace(*password), entry)),
}, nil
}
}
raw, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(*encoded))
if err != nil || len(raw) == 0 || len(raw) > 128<<10 {
return adminResponse{}, errors.New("состояние клиента повреждено или слишком велико")
}
var state adminClientState
if err := json.Unmarshal(raw, &state); err != nil {
return adminResponse{}, errors.New("состояние клиента имеет неверный формат")
}
if err := validateAdminClientState(&state, strings.TrimSpace(*password)); err != nil {
return adminResponse{}, err
}
if entry.DeviceID != "" || entry.DownBytes != 0 || entry.UpBytes != 0 ||
len(entry.Traffic) != 0 || len(entry.BindHistory) != 0 {
return adminResponse{}, newAdminCommandError(
"target_not_empty",
"целевой клиент уже содержит устройство или статистику",
)
}
previousDown := entry.DownBytes
previousUp := entry.UpBytes
previousTraffic := append([]TrafficBucket(nil), entry.Traffic...)
previousImports := cloneTrafficImports(entry.TrafficImports)
previousHistory := append([]BindHistoryEntry(nil), entry.BindHistory...)
entry.DownBytes = state.DownBytes
entry.UpBytes = state.UpBytes
entry.Traffic = append([]TrafficBucket(nil), state.Traffic...)
entry.TrafficImports = cloneTrafficImports(state.TrafficImports)
if entry.TrafficImports == nil {
entry.TrafficImports = make(map[string]TrafficImport)
}
entry.TrafficImports[key] = TrafficImport{AppliedAt: time.Now().Unix()}
entry.BindHistory = append([]BindHistoryEntry(nil), state.BindHistory...)
if err := saveAdminDB(configDir, loaded); err != nil {
entry.DownBytes = previousDown
entry.UpBytes = previousUp
entry.Traffic = previousTraffic
entry.TrafficImports = previousImports
entry.BindHistory = previousHistory
return adminResponse{}, err
}
return adminResponse{
OK: true,
Message: "Статистика и история клиента перенесены",
Server: buildAdminServerInfo(configDir, loaded),
Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, strings.TrimSpace(*password), entry)),
}, nil
}
func validateAdminClientState(state *adminClientState, password string) error {
if state == nil || state.Version != 1 || state.Password != password {
return errors.New("состояние клиента относится к другому паролю или версии")
}
if state.DownBytes < 0 || state.UpBytes < 0 {
return errors.New("счётчики состояния клиента не могут быть отрицательными")
}
if len(state.Traffic) > trafficHistoryDays || len(state.BindHistory) > 50 ||
len(state.TrafficImports) > 1024 {
return errors.New("история состояния клиента превышает допустимый размер")
}
for _, bucket := range state.Traffic {
if len(bucket.Date) != 10 || bucket.DownBytes < 0 || bucket.UpBytes < 0 {
return errors.New("история трафика клиента повреждена")
}
if _, err := time.Parse("2006-01-02", bucket.Date); err != nil {
return errors.New("история трафика клиента содержит неверную дату")
}
}
for key, imported := range state.TrafficImports {
if strings.TrimSpace(key) == "" || len(key) > 160 ||
imported.DownBytes < 0 || imported.UpBytes < 0 || imported.AppliedAt < 0 {
return errors.New("история учёта перенесённого трафика повреждена")
}
}
return nil
}
func cloneTrafficImports(source map[string]TrafficImport) map[string]TrafficImport {
if len(source) == 0 {
return nil
}
result := make(map[string]TrafficImport, len(source))
for key, value := range source {
result[key] = value
}
return result
}
func buildAdminPasswordInfo(loaded *Database, password string, entry *PasswordEntry) adminPasswordInfo {
info := adminPasswordInfo{
Password: password,
@@ -727,16 +1033,20 @@ func buildAdminPasswordInfo(loaded *Database, password string, entry *PasswordEn
info.Label = entry.Label
info.VkHash = entry.VkHash
info.ExpiresAt = entry.ExpiresAt
info.PurgeAfter = entry.PurgeAfter
info.DownBytes = entry.DownBytes
info.UpBytes = entry.UpBytes
info.DeviceID = entry.DeviceID
info.BindEventsCount = len(entry.BindHistory)
info.Traffic = buildAdminTrafficPeriod(entry.Traffic, entry.DownBytes, entry.UpBytes)
info.BindHistory = append([]BindHistoryEntry(nil), entry.BindHistory...)
if entry.IsDeactivated {
info.Status = "deactivated"
} else if isPasswordExpired(entry) {
nowUnix := time.Now().Unix()
if isPasswordRetainedExpiredAt(entry, nowUnix) {
info.Status = "expired_retained"
} else if isPasswordExpiredAt(entry, nowUnix) {
info.Status = "expired"
} else if entry.IsDeactivated {
info.Status = "deactivated"
}
if entry.DeviceID != "" {
if dev := loaded.Devices[entry.DeviceID]; dev != nil {
@@ -810,6 +1120,11 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm
ports := fs.String("ports", "", "DTLS,WG,TUN")
clientPassword := fs.String("client-password", "", "заданный пароль клиента")
expiresAt := fs.Int64("expires-at", -1, "точная дата окончания unix, 0 = бессрочно")
purgeAfter := fs.Int64(
"purge-after",
0,
"не удалять истёкшую запись до unix timestamp",
)
deactivated := fs.Bool("deactivated", false, "создать клиента отключённым")
if err := fs.Parse(args); err != nil {
return adminResponse{}, err
@@ -819,7 +1134,7 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm
}
cleanupExpiredPasswordsAdmin(loaded)
if len(loaded.Passwords) >= loaded.MaxPasswords {
return adminResponse{}, fmt.Errorf("лимит клиентов: максимум %d", loaded.MaxPasswords)
return adminResponse{}, newAdminCommandError("capacity_full", fmt.Sprintf("лимит клиентов: максимум %d", loaded.MaxPasswords))
}
normalizedPorts := loaded.DefaultPorts
if strings.TrimSpace(*ports) != "" {
@@ -879,6 +1194,10 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm
} else if *days > 0 {
entry.ExpiresAt = time.Now().Add(time.Duration(*days) * 24 * time.Hour).Unix()
}
if err := validatePasswordRetention(entry.ExpiresAt, *purgeAfter); err != nil {
return adminResponse{}, err
}
entry.PurgeAfter = *purgeAfter
loaded.Passwords[password] = entry
if err := saveAdminDB(configDir, loaded); err != nil {
return adminResponse{}, err
@@ -1071,21 +1390,67 @@ func adminSetPasswordExpiry(configDir string, loaded *Database, args []string) (
fs.SetOutput(io.Discard)
password := fs.String("password", "", "пароль клиента")
days := fs.Int("days", 30, "новый срок от текущего момента, 0 = бессрочно")
expiresAt := fs.Int64("expires-at", -1, "точная дата окончания unix, 0 = бессрочно")
purgeAfter := fs.Int64(
"purge-after",
-1,
"не удалять истёкшую запись до unix timestamp; по умолчанию сохраняется прежний интервал",
)
if err := fs.Parse(args); err != nil {
return adminResponse{}, err
}
if *days < 0 || *days > 365 {
provided := make(map[string]bool)
fs.Visit(func(value *flag.Flag) {
provided[value.Name] = true
})
if provided["days"] && provided["expires-at"] {
return adminResponse{}, errors.New("укажите только один из параметров: days или expires-at")
}
if !provided["expires-at"] && (*days < 0 || *days > 365) {
return adminResponse{}, errors.New("days должен быть 0..365")
}
entry, err := requireAdminPassword(loaded, *password)
if err != nil {
return adminResponse{}, err
}
if *days == 0 {
entry.ExpiresAt = 0
} else {
entry.ExpiresAt = time.Now().Add(time.Duration(*days) * 24 * time.Hour).Unix()
nowUnix := time.Now().Unix()
if isPasswordPurgeableAt(entry, nowUnix) {
return adminResponse{}, newAdminCommandError(
"retention_expired",
"запись уже подлежит удалению; создайте доступ заново",
)
}
newExpiresAt := int64(0)
if provided["expires-at"] {
if *expiresAt < 0 {
return adminResponse{}, errors.New("expires-at должен быть 0 или будущим unix timestamp")
}
newExpiresAt = *expiresAt
if newExpiresAt > 0 && newExpiresAt <= nowUnix {
return adminResponse{}, errors.New("новый срок действия уже истёк")
}
} else if *days > 0 {
newExpiresAt = time.Now().Add(time.Duration(*days) * 24 * time.Hour).Unix()
}
newPurgeAfter := int64(0)
if provided["purge-after"] {
newPurgeAfter = *purgeAfter
} else {
oldRetentionDuration := entry.PurgeAfter - entry.ExpiresAt
if newExpiresAt > 0 && entry.ExpiresAt > 0 && oldRetentionDuration > 0 {
newPurgeAfter = newExpiresAt + oldRetentionDuration
if newPurgeAfter < newExpiresAt {
return adminResponse{}, errors.New("срок хранения выходит за допустимый диапазон")
}
}
}
if err := validatePasswordRetention(newExpiresAt, newPurgeAfter); err != nil {
return adminResponse{}, err
}
entry.ExpiresAt = newExpiresAt
entry.PurgeAfter = newPurgeAfter
if err := saveAdminDB(configDir, loaded); err != nil {
return adminResponse{}, err
}
@@ -1097,6 +1462,80 @@ func adminSetPasswordExpiry(configDir string, loaded *Database, args []string) (
}, nil
}
func validatePasswordRetention(expiresAt, purgeAfter int64) error {
if purgeAfter < 0 {
return errors.New("purge-after должен быть неотрицательным unix timestamp")
}
if expiresAt == 0 {
if purgeAfter != 0 {
return errors.New("для бессрочного доступа purge-after должен быть 0")
}
return nil
}
if purgeAfter > 0 && purgeAfter < expiresAt {
return errors.New("purge-after не может быть раньше expires-at")
}
return nil
}
func adminSetPasswordRetention(configDir string, loaded *Database, args []string) (adminResponse, error) {
fs := flag.NewFlagSet("set-retention", flag.ContinueOnError)
fs.SetOutput(io.Discard)
password := fs.String("password", "", "пароль клиента")
expectedExpiresAt := fs.Int64("expected-expires-at", -1, "ожидаемая дата окончания unix")
purgeAfter := fs.Int64("purge-after", -1, "новая дата удаления истёкшей записи unix")
if err := fs.Parse(args); err != nil {
return adminResponse{}, newAdminCommandError("invalid", err.Error())
}
if fs.NArg() != 0 {
return adminResponse{}, newAdminCommandError("invalid", "лишние аргументы set-retention")
}
passwordValue := strings.TrimSpace(*password)
if passwordValue == "" {
return adminResponse{}, newAdminCommandError("invalid", "укажите --password")
}
if *expectedExpiresAt <= 0 {
return adminResponse{}, newAdminCommandError("invalid", "expected-expires-at должен быть положительным unix timestamp")
}
if *purgeAfter <= 0 {
return adminResponse{}, newAdminCommandError("invalid", "purge-after должен быть положительным unix timestamp")
}
entry, err := requireAdminPassword(loaded, passwordValue)
if err != nil {
return adminResponse{}, err
}
nowUnix := time.Now().Unix()
if isPasswordPurgeableAt(entry, nowUnix) {
return adminResponse{}, newAdminCommandError("retention_expired", "истёкшая запись уже подлежит удалению")
}
if entry.ExpiresAt != *expectedExpiresAt {
return adminResponse{}, newAdminCommandError("retention_conflict", "срок доступа изменился; обновите состояние перед повтором")
}
if entry.ExpiresAt <= 0 || entry.PurgeAfter <= 0 {
return adminResponse{}, newAdminCommandError("invalid", "изменить можно только существующий конечный срок хранения")
}
if *purgeAfter < entry.ExpiresAt {
return adminResponse{}, newAdminCommandError("invalid", "purge-after не может быть раньше expires-at")
}
if *purgeAfter <= entry.PurgeAfter {
return adminResponse{}, newAdminCommandError("retention_conflict", "запись уже хранится до такого же или более позднего срока")
}
previousPurgeAfter := entry.PurgeAfter
entry.PurgeAfter = *purgeAfter
if err := saveAdminDB(configDir, loaded); err != nil {
entry.PurgeAfter = previousPurgeAfter
return adminResponse{}, err
}
return adminResponse{
OK: true,
Message: "Срок хранения обновлён",
Server: buildAdminServerInfo(configDir, loaded),
Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, passwordValue, entry)),
}, nil
}
func adminSetPasswordPorts(configDir string, loaded *Database, args []string) (adminResponse, error) {
fs := flag.NewFlagSet("set-ports", flag.ContinueOnError)
fs.SetOutput(io.Discard)
@@ -1365,7 +1804,7 @@ func adminRefreshPublicIP(configDir string, loaded *Database, live bool) (adminR
return adminResponse{OK: true, Message: "Публичный IP сервера определён: " + value, Server: buildAdminServerInfo(configDir, loaded)}, nil
}
func adminCleanupExpired(configDir string, loaded *Database, wgDev *device.Device, live bool) (adminResponse, error) {
func adminCleanupExpired(configDir string, loaded *Database, wgDev wgDevice, live bool) (adminResponse, error) {
removed := 0
if live {
removed = cleanupExpiredPasswordsLocked(wgDev)
@@ -1380,7 +1819,7 @@ func adminCleanupExpired(configDir string, loaded *Database, wgDev *device.Devic
return adminResponse{OK: true, Message: fmt.Sprintf("Удалено истёкших клиентов: %d", removed), Server: buildAdminServerInfo(configDir, loaded)}, nil
}
func adminCleanupOrphans(configDir string, loaded *Database, wgDev *device.Device, live bool) (adminResponse, error) {
func adminCleanupOrphans(configDir string, loaded *Database, wgDev wgDevice, live bool) (adminResponse, error) {
used := make(map[string]struct{})
for _, entry := range loaded.Passwords {
if entry != nil && entry.DeviceID != "" {
@@ -1427,6 +1866,69 @@ func adminResetTraffic(configDir string, loaded *Database) (adminResponse, error
return adminResponse{OK: true, Message: "Счётчики трафика сброшены", Server: buildAdminServerInfo(configDir, loaded)}, nil
}
func adminMergeClientTraffic(configDir string, loaded *Database, args []string) (adminResponse, error) {
fs := flag.NewFlagSet("merge-client-traffic", flag.ContinueOnError)
fs.SetOutput(io.Discard)
password := fs.String("password", "", "пароль клиента")
operationID := fs.String("operation-id", "", "уникальный идентификатор переноса")
downBytes := fs.Int64("down-bytes", 0, "скачано на другом сервере")
upBytes := fs.Int64("up-bytes", 0, "отдано на другом сервере")
if err := fs.Parse(args); err != nil {
return adminResponse{}, err
}
key := strings.TrimSpace(*operationID)
if key == "" || len(key) > 160 {
return adminResponse{}, errors.New("operation-id должен содержать 1..160 символов")
}
if *downBytes < 0 || *upBytes < 0 {
return adminResponse{}, errors.New("счётчики трафика не могут быть отрицательными")
}
entry, err := requireAdminPassword(loaded, strings.TrimSpace(*password))
if err != nil {
return adminResponse{}, err
}
if entry.TrafficImports == nil {
entry.TrafficImports = make(map[string]TrafficImport)
}
if previous, exists := entry.TrafficImports[key]; exists {
if previous.DownBytes != *downBytes || previous.UpBytes != *upBytes {
return adminResponse{}, errors.New("этот operation-id уже применён с другими значениями")
}
return adminResponse{
OK: true,
Message: "Трафик уже был учтён",
Server: buildAdminServerInfo(configDir, loaded),
Password: ptrAdminPasswordInfo(
buildAdminPasswordInfo(loaded, strings.TrimSpace(*password), entry),
),
}, nil
}
entry.DownBytes += *downBytes
entry.UpBytes += *upBytes
entry.Traffic = addTrafficBucket(
entry.Traffic,
trafficDayKey(time.Now()),
*downBytes,
*upBytes,
)
entry.TrafficImports[key] = TrafficImport{
DownBytes: *downBytes,
UpBytes: *upBytes,
AppliedAt: time.Now().Unix(),
}
if err := saveAdminDB(configDir, loaded); err != nil {
return adminResponse{}, err
}
return adminResponse{
OK: true,
Message: "Трафик клиента учтён",
Server: buildAdminServerInfo(configDir, loaded),
Password: ptrAdminPasswordInfo(
buildAdminPasswordInfo(loaded, strings.TrimSpace(*password), entry),
),
}, nil
}
func adminPasswordArg(command string, args []string) (string, error) {
fs := flag.NewFlagSet(command, flag.ContinueOnError)
fs.SetOutput(io.Discard)
@@ -1448,23 +1950,35 @@ func requireAdminPassword(loaded *Database, password string) (*PasswordEntry, er
}
entry, exists := loaded.Passwords[password]
if !exists || entry == nil {
return nil, errors.New("пароль не найден")
return nil, newAdminCommandError("not_found", "пароль не найден")
}
return entry, nil
}
func cleanupExpiredPasswordsAdmin(loaded *Database) int {
return cleanupExpiredPasswordsAdminAt(loaded, time.Now().Unix())
}
func cleanupExpiredPasswordsAdminAt(loaded *Database, nowUnix int64) int {
removed := 0
nowUnix := time.Now().Unix()
deviceCandidates := make(map[string]struct{})
for password, entry := range loaded.Passwords {
if isPasswordExpired(entry) {
if entry != nil {
unbindPasswordDeviceAdminAt(loaded, entry, nowUnix)
if isPasswordPurgeableAt(entry, nowUnix) {
if entry != nil && entry.DeviceID != "" {
markActiveBindUnbound(entry, entry.DeviceID, nowUnix)
deviceCandidates[entry.DeviceID] = struct{}{}
}
delete(loaded.Passwords, password)
removed++
}
}
adminDevices := adminDeviceIDSet(loaded)
for deviceID := range deviceCandidates {
if _, isAdminDevice := adminDevices[deviceID]; isAdminDevice || databaseUsesDeviceID(loaded, deviceID) {
continue
}
delete(loaded.Devices, deviceID)
}
return removed
}
@@ -1478,10 +1992,10 @@ func unbindPasswordDeviceAdminAt(loaded *Database, entry *PasswordEntry, ts int6
}
oldDeviceID := entry.DeviceID
markActiveBindUnbound(entry, oldDeviceID, ts)
if _, isAdminDevice := adminDeviceIDSet(loaded)[oldDeviceID]; !isAdminDevice {
entry.DeviceID = ""
if _, isAdminDevice := adminDeviceIDSet(loaded)[oldDeviceID]; !isAdminDevice && !databaseUsesDeviceID(loaded, oldDeviceID) {
delete(loaded.Devices, oldDeviceID)
}
entry.DeviceID = ""
}
func ptrAdminPasswordInfo(value adminPasswordInfo) *adminPasswordInfo {
@@ -1497,7 +2011,7 @@ func writeAdminJSON(response adminResponse) {
func writeAdminError(err error) {
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
_ = enc.Encode(adminResponse{OK: false, Message: err.Error()})
_ = enc.Encode(adminErrorResponse(err))
}
func adminAtoi(value string) (int, error) {
+149
View File
@@ -2,10 +2,142 @@ package main
import (
"context"
"encoding/base64"
"encoding/json"
"reflect"
"regexp"
"testing"
"time"
)
func TestAdminServerInfoReportsRunningBinarySHA256(t *testing.T) {
sum := runningBinarySHA256()
if !regexp.MustCompile(`^[0-9a-f]{64}$`).MatchString(sum) {
t.Fatalf("unexpected running binary SHA-256: %q", sum)
}
info := buildAdminServerInfo(t.TempDir(), &Database{
DefaultPorts: "56000,56001,9000",
MaxPasswords: 10,
Passwords: make(map[string]*PasswordEntry),
Devices: make(map[string]*ClientDevice),
})
if info.BinarySHA256 != sum {
t.Fatalf("admin server SHA-256 = %q, want %q", info.BinarySHA256, sum)
}
}
func TestAdminServerInfoSeparatesClientAndOwnerDevices(t *testing.T) {
loaded := &Database{
DefaultPorts: "56000,56001,9000",
MaxPasswords: 10,
AdminProfile: AdminProfileEntry{
DeviceIDs: []string{"owner-phone", "shared-phone", "owner-phone"},
},
Passwords: map[string]*PasswordEntry{
"client-one": {
DeviceID: "shared-phone",
BindHistory: []BindHistoryEntry{
{DeviceID: "shared-phone", BoundAt: 10, Status: "active"},
{DeviceID: "old-client-phone", BoundAt: 5, UnboundAt: 9, Status: "unbound"},
{DeviceID: "rejected-phone", EventAt: 11, Status: "denied_mismatch"},
},
},
"client-two": {},
},
Devices: map[string]*ClientDevice{
"shared-phone": {DeviceID: "shared-phone"},
"owner-phone": {DeviceID: "owner-phone"},
"orphan": {DeviceID: "orphan"},
},
}
info := buildAdminServerInfo(t.TempDir(), loaded)
if info.DeviceCount != 2 {
t.Fatalf("client device count = %d, want current plus successful history = 2", info.DeviceCount)
}
if info.OwnerDeviceCount != 2 {
t.Fatalf("owner device count = %d, want 2 unique owner devices", info.OwnerDeviceCount)
}
if info.OrphanDeviceCount != 1 {
t.Fatalf("orphan device count = %d, want 1", info.OrphanDeviceCount)
}
}
func TestAdminClientStateMovesTrafficAndBindingHistoryExactlyOnce(t *testing.T) {
sourceDir := t.TempDir()
targetDir := t.TempDir()
password := "ABCDEFGHJKLMNPQR"
today := time.Now().Format("2006-01-02")
source := &Database{
DefaultPorts: "56000,56001,9000",
MaxPasswords: 10,
Passwords: map[string]*PasswordEntry{
password: {
DownBytes: 8192,
UpBytes: 4096,
Traffic: []TrafficBucket{
{Date: today, DownBytes: 8192, UpBytes: 4096},
},
TrafficImports: map[string]TrafficImport{
"older-transfer": {DownBytes: 128, UpBytes: 64, AppliedAt: 100},
},
BindHistory: []BindHistoryEntry{
{DeviceID: "old-phone", BoundAt: 10, UnboundAt: 20, Status: "unbound"},
{DeviceID: "current-phone", BoundAt: 30, Status: "active"},
},
},
},
Devices: make(map[string]*ClientDevice),
}
exported, err := adminExportClientState(
sourceDir,
source,
[]string{"--password", password},
)
if err != nil || exported.ClientState == nil {
t.Fatalf("export-client-state failed: response=%#v error=%v", exported, err)
}
raw, err := json.Marshal(exported.ClientState)
if err != nil {
t.Fatal(err)
}
encoded := base64.RawURLEncoding.EncodeToString(raw)
target := &Database{
DefaultPorts: "56000,56001,9000",
MaxPasswords: 10,
Passwords: map[string]*PasswordEntry{
password: {},
},
Devices: make(map[string]*ClientDevice),
}
args := []string{
"--password", password,
"--operation-id", "client-transfer-row",
"--state", encoded,
}
for attempt := 0; attempt < 2; attempt++ {
if _, err := adminImportClientState(targetDir, target, args); err != nil {
t.Fatalf("import-client-state attempt %d failed: %v", attempt+1, err)
}
}
entry := target.Passwords[password]
if entry.DownBytes != 8192 || entry.UpBytes != 4096 {
t.Fatalf("traffic totals changed during import: %#v", entry)
}
if !reflect.DeepEqual(entry.Traffic, source.Passwords[password].Traffic) {
t.Fatalf("daily traffic history was not preserved: %#v", entry.Traffic)
}
if !reflect.DeepEqual(entry.BindHistory, source.Passwords[password].BindHistory) {
t.Fatalf("binding history was not preserved: %#v", entry.BindHistory)
}
if _, ok := entry.TrafficImports["client-transfer-row"]; !ok {
t.Fatal("idempotency marker was not recorded")
}
if entry.DeviceID != "" || len(target.Devices) != 0 {
t.Fatal("live device keys must be rebound on the destination, not copied")
}
}
func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) {
configDir := t.TempDir()
loaded := &Database{
@@ -165,6 +297,23 @@ func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) {
if db.Passwords[password].DownBytes != 0 || db.Passwords[password].UpBytes != 0 {
t.Fatal("traffic counters were not reset")
}
request(
"merge-client-traffic",
"--password", password,
"--operation-id", "incident-row-return",
"--down-bytes", "3072",
"--up-bytes", "4096",
)
request(
"merge-client-traffic",
"--password", password,
"--operation-id", "incident-row-return",
"--down-bytes", "3072",
"--up-bytes", "4096",
)
if db.Passwords[password].DownBytes != 3072 || db.Passwords[password].UpBytes != 4096 {
t.Fatal("traffic import must be applied exactly once")
}
request("deactivate", "--password", password)
dbMutex.Lock()
+141 -37
View File
@@ -1,11 +1,52 @@
import java.io.File
import java.util.Properties
import org.gradle.api.DefaultTask
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
abstract class VerifyReleaseConfiguration : DefaultTask() {
@get:Input
abstract val keystorePath: Property<String>
@get:Input
abstract val credentialsComplete: Property<Boolean>
@get:Input
abstract val productionDomain: Property<Boolean>
@get:Input
abstract val releaseAuditRequired: Property<Boolean>
@get:Input
abstract val releaseAuditPath: Property<String>
@TaskAction
fun verify() {
require(File(keystorePath.get()).isFile) {
"Release signing keystore is required."
}
require(credentialsComplete.get()) {
"Complete release signing credentials are required."
}
require(productionDomain.get()) {
"Release builds must use the production WDTT Plus domain."
}
require(
!releaseAuditRequired.get() ||
File(releaseAuditPath.get()).let { it.isFile && it.canExecute() }
) {
"The local release audit is required but unavailable."
}
}
}
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.plugin.compose")
}
val appVersionName = "11"
val appVersionName = "12"
val releaseApkBaseName = "WDTT-Plus"
val localProperties = Properties()
@@ -14,17 +55,47 @@ if (localPropertiesFile.exists()) {
localProperties.load(localPropertiesFile.inputStream())
}
fun buildConfigString(value: String): String =
"\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
val wdttPlusDomain = localProperties.getProperty("WDTT_PLUS_DOMAIN")
?.trim()
?.trimEnd('/')
?.takeIf { it.isNotBlank() }
?: "wdttplus.ru"
val remoteActionPreview = providers.gradleProperty("REMOTE_ACTION_PREVIEW")
.orNull
?.toBooleanStrictOrNull()
?: false
val releaseKeystoreProperty = localProperties.getProperty("KEYSTORE_FILE")
?.trim()
.orEmpty()
val releaseKeystoreFile = when {
releaseKeystoreProperty.startsWith("..") ->
rootDir.resolve(releaseKeystoreProperty.removePrefix("../"))
releaseKeystoreProperty.isNotBlank() -> file(releaseKeystoreProperty)
else -> null
}
val releaseCredentialsComplete =
listOf("KEYSTORE_PASSWORD", "KEY_ALIAS", "KEY_PASSWORD")
.all { !localProperties.getProperty(it).isNullOrBlank() }
val localReleaseAuditRequired = rootProject.file("release.keystore").exists()
val localReleaseAudit = rootProject.file("release-audit")
android {
namespace = "com.wdtt.plus"
compileSdk = 35
compileSdk = 36
defaultConfig {
applicationId = "com.wdtt.plus"
minSdk = 28
targetSdk = 35
versionCode = 11
versionCode = 12
versionName = appVersionName
buildConfigField("String", "MOD_RELEASE_DATE", "\"07.07.2026\"")
buildConfigField("String", "MOD_RELEASE_DATE", "\"29.07.2026\"")
buildConfigField("String", "WDTT_PLUS_DOMAIN", buildConfigString(wdttPlusDomain))
manifestPlaceholders["wdttPlusDomain"] = wdttPlusDomain
manifestPlaceholders["appLabel"] = "WDTT Plus"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
@@ -47,23 +118,11 @@ android {
signingConfigs {
create("release") {
val keyFile = localProperties.getProperty("KEYSTORE_FILE")
if (keyFile != null) {
// Резолвим путь: если начинается с "..", берём от корня проекта
val resolvedFile = if (keyFile.startsWith("..")) {
// ../release.keystore -> корень проекта / release.keystore
file(rootDir.resolve(keyFile.substring(3)))
} else {
file(keyFile)
}
if (resolvedFile.exists()) {
storeFile = resolvedFile
if (releaseKeystoreFile?.isFile == true) {
storeFile = releaseKeystoreFile
storePassword = localProperties.getProperty("KEYSTORE_PASSWORD")
keyAlias = localProperties.getProperty("KEY_ALIAS")
keyPassword = localProperties.getProperty("KEY_PASSWORD")
} else {
println("WARNING: Keystore file not found: $keyFile (resolved: ${resolvedFile.absolutePath})")
}
}
enableV1Signing = true
enableV2Signing = true
@@ -72,28 +131,31 @@ android {
}
buildTypes {
getByName("debug") {
applicationIdSuffix = ".preview"
versionNameSuffix = "-preview"
manifestPlaceholders["appLabel"] = "WDTT Plus Preview"
buildConfigField("boolean", "REMOTE_ACTION_PREVIEW", remoteActionPreview.toString())
}
getByName("release") {
buildConfigField("boolean", "REMOTE_ACTION_PREVIEW", "false")
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
val keyFile = localProperties.getProperty("KEYSTORE_FILE")
val resolvedFile = if (keyFile != null && keyFile.startsWith("..")) {
file(rootDir.resolve(keyFile.substring(3)))
} else if (keyFile != null) {
file(keyFile)
} else null
if (resolvedFile != null && resolvedFile.exists()) {
if (releaseKeystoreFile?.isFile == true) {
signingConfig = signingConfigs.getByName("release")
println("✅ Signing config applied: ${resolvedFile.absolutePath}")
} else {
println("⚠️ WARNING: Keystore not found, using debug signing")
println(" Looked for: ${resolvedFile?.absolutePath ?: keyFile}")
}
}
create("preview") {
initWith(getByName("release"))
versionNameSuffix = "-preview-ui2"
manifestPlaceholders["appLabel"] = "WDTT Plus Preview"
buildConfigField("boolean", "REMOTE_ACTION_PREVIEW", "true")
signingConfig = signingConfigs.getByName("release")
}
}
packaging {
@@ -113,8 +175,8 @@ android {
}
lint {
checkReleaseBuilds = false
abortOnError = false
checkReleaseBuilds = true
abortOnError = true
}
compileOptions {
@@ -129,6 +191,19 @@ android {
}
}
val verifyReleaseConfiguration =
tasks.register<VerifyReleaseConfiguration>("verifyReleaseConfiguration") {
keystorePath.set(releaseKeystoreFile?.absolutePath.orEmpty())
credentialsComplete.set(releaseCredentialsComplete)
productionDomain.set(wdttPlusDomain == "wdttplus.ru")
releaseAuditRequired.set(localReleaseAuditRequired)
releaseAuditPath.set(localReleaseAudit.absolutePath)
}
tasks.matching { it.name == "preReleaseBuild" }.configureEach {
dependsOn(verifyReleaseConfiguration)
}
val goClientDir = rootProject.layout.projectDirectory.dir("go_client")
val jniLibsDir = layout.projectDirectory.dir("src/main/jniLibs")
val serverAssetFile = layout.projectDirectory.file("src/main/assets/server")
@@ -174,11 +249,11 @@ tasks.register<Exec>("buildNativeClient") {
mkdir -p "${'$'}jni_dir/${'$'}abi"
if [ -n "${'$'}goarm" ]; then
env GOOS=android GOARCH="${'$'}goarch" GOARM="${'$'}goarm" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \
go build -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \
go build -buildvcs=false -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \
-o "${'$'}jni_dir/${'$'}abi/libclient.so" .
else
env GOOS=android GOARCH="${'$'}goarch" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \
go build -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \
go build -buildvcs=false -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \
-o "${'$'}jni_dir/${'$'}abi/libclient.so" .
fi
}
@@ -220,7 +295,7 @@ tasks.register<Exec>("buildServerAsset") {
out="${'$'}1"
mkdir -p "$(dirname "${'$'}out")"
env GOOS=linux GOARCH=amd64 CGO_ENABLED=0 \
go build -trimpath -ldflags="-s -w" -o "${'$'}out" .
go build -buildvcs=false -trimpath -ldflags="-s -w" -o "${'$'}out" .
""".trimIndent(),
"bash",
serverAssetFile.asFile.absolutePath
@@ -233,9 +308,17 @@ tasks.matching {
dependsOn("buildServerAsset")
}
tasks.register<Exec>("nameReleaseApks") {
// Lint reads the source asset/native folders directly. During assembleRelease
// the generators are in the same task graph, so make their order explicit
// without forcing public source-only lint runs to build private local artifacts.
tasks.matching { it.name.contains("Lint", ignoreCase = true) }.configureEach {
mustRunAfter("buildServerAsset", "buildNativeClient")
}
val nameReleaseApks = tasks.register<Exec>("nameReleaseApks") {
group = "build"
description = "Copies release APKs to filenames with app name and version."
dependsOn("packageRelease")
val releaseDir = layout.buildDirectory.dir("outputs/apk/release")
val namedReleaseDir = layout.buildDirectory.dir("outputs/apk/release/named")
@@ -266,8 +349,28 @@ tasks.register<Exec>("nameReleaseApks") {
)
}
val auditReleaseApks = tasks.register<Exec>("auditReleaseApks") {
group = "verification"
description = "Runs the configured local source and APK publication audit."
dependsOn(nameReleaseApks)
enabled = localReleaseAuditRequired
val namedReleaseDir = layout.buildDirectory.dir("outputs/apk/release/named").get().asFile
val variants = listOf("universal", "arm64-v8a", "armeabi-v7a", "x86_64")
val releaseApks = variants.map { abi ->
namedReleaseDir.resolve("$releaseApkBaseName-v$appVersionName-$abi-release.apk")
}
inputs.files(releaseApks)
commandLine(
listOf(
localReleaseAudit.absolutePath,
rootDir.absolutePath,
) + releaseApks.map(File::getAbsolutePath)
)
}
tasks.matching { it.name == "assembleRelease" }.configureEach {
finalizedBy("nameReleaseApks")
finalizedBy(auditReleaseApks)
}
dependencies {
@@ -281,6 +384,7 @@ dependencies {
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.material:material-icons-extended")
implementation("androidx.activity:activity-compose:1.9.3")
implementation("androidx.browser:browser:1.9.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
@@ -6,7 +6,9 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.wdtt.plus.ui.DeployTab
@@ -62,8 +64,10 @@ private fun InfoTabPreview() {
)
@Composable
private fun TunnelTabPreview() {
val context = LocalContext.current
val settingsStore = remember { SettingsStore(context) }
PreviewScreen {
SettingsTab()
SettingsTab(settingsStore = settingsStore)
}
}
+24 -2
View File
@@ -28,7 +28,7 @@
android:name=".WdttApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="WDTT Plus"
android:label="${appLabel}"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WDTTClient">
@@ -54,8 +54,10 @@
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="application/vnd.wdtt.plus" />
<data android:mimeType="application/json" />
<data android:mimeType="application/vnd.wdtt.plus.transfer" />
<data android:mimeType="application/vnd.wdtt.plus.client" />
<data android:mimeType="application/octet-stream" />
</intent-filter>
<intent-filter>
@@ -64,13 +66,33 @@
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="wdtt" />
</intent-filter>
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="${wdttPlusDomain}"
android:pathPrefix="/c/" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/vnd.wdtt.plus" />
<data android:mimeType="application/json" />
<data android:mimeType="application/vnd.wdtt.plus.transfer" />
<data android:mimeType="application/vnd.wdtt.plus.client" />
<data android:mimeType="application/octet-stream" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="content" />
<data android:scheme="file" />
<data android:host="*" />
<data android:pathPattern=".*\\.wdtt" />
</intent-filter>
</activity>
<provider
@@ -103,7 +125,7 @@
android:name=".QuickToggleTileService"
android:exported="true"
android:icon="@drawable/ic_tile_logo"
android:label="WDTT Plus"
android:label="${appLabel}"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
+56 -3
View File
@@ -2,19 +2,24 @@
# ==============================================================================
# WDTT Plus Server — Универсальный установщик для VPS
# Поддержка: Debian 11+, Ubuntu 20.04+, CentOS/RHEL/Fedora/AlmaLinux/Rocky
# Версия: 3.3 | Дата: 2026-07-02
# Версия: 3.4 | Дата: 2026-07-13
# NAT: MASQUERADE через iptables
# WG: порт 56001 (не конфликтует с существующим WG на 51820)
# DTLS: порт 56000
# ==============================================================================
set -uo pipefail
readonly SCRIPT_VERSION="3.3"
readonly SCRIPT_VERSION="3.4"
readonly LOG_FILE="/var/log/wdtt-install.log"
readonly WG_PORT="${WDTT_WG_PORT:-56001}"
readonly DTLS_PORT="${WDTT_DTLS_PORT:-56000}"
readonly SSH_PORT="${WDTT_SSH_PORT:-22}"
readonly MAX_PASSWORDS="${WDTT_MAX_PASSWORDS:-50}"
readonly MAX_WORKERS_PER_ACCESS="${WDTT_MAX_WORKERS_PER_ACCESS:-0}"
readonly MAX_HANDSHAKES="${WDTT_MAX_HANDSHAKES:-32}"
readonly HANDSHAKE_RATE="${WDTT_HANDSHAKE_RATE:-24}"
readonly MAX_CLIENT_MBPS="${WDTT_MAX_CLIENT_MBPS:-0}"
readonly WG_BACKEND="${WDTT_WG_BACKEND:-auto}"
readonly WDTT_ARGS="${WDTT_ARGS:-}"
readonly WDTT_PRESERVE_DATA="${WDTT_PRESERVE_DATA:-0}"
readonly WDTT_IFACE="wdtt0"
@@ -34,6 +39,33 @@ validate_port() {
fi
}
validate_runtime_limits() {
for item in \
"WDTT_MAX_PASSWORDS:$MAX_PASSWORDS" \
"WDTT_MAX_HANDSHAKES:$MAX_HANDSHAKES"; do
local name="${item%%:*}" value="${item#*:}"
case "$value" in
''|*[!0-9]*) die "$name должен быть положительным целым числом" ;;
esac
[ "$value" -ge 1 ] || die "$name должен быть не меньше 1"
done
case "$MAX_WORKERS_PER_ACCESS" in
''|*[!0-9]*) die "WDTT_MAX_WORKERS_PER_ACCESS должен быть целым числом" ;;
esac
for item in \
"WDTT_HANDSHAKE_RATE:$HANDSHAKE_RATE" \
"WDTT_MAX_CLIENT_MBPS:$MAX_CLIENT_MBPS"; do
local name="${item%%:*}" value="${item#*:}"
case "$value" in
''|*[!0-9.]*) die "$name должен быть неотрицательным числом" ;;
esac
done
case "$WG_BACKEND" in
auto|kernel|userspace) ;;
*) die "WDTT_WG_BACKEND должен быть auto, kernel или userspace" ;;
esac
}
# ─── Цвета ───────────────────────────────────────────────────────────────────
C_GREEN=''; C_YELLOW=''; C_RED=''
C_CYAN=''; C_BOLD=''; C_NC=''
@@ -115,14 +147,20 @@ install_prerequisites() {
apt)
pkg_install ca-certificates iproute2 iptables nftables procps psmisc || \
log_warn "Часть apt-пакетов не установилась, продолжаю с доступными утилитами"
pkg_install wireguard-tools || \
log_warn "wireguard-tools не установлен; будет использован userspace WireGuard"
;;
dnf|yum)
pkg_install ca-certificates iproute iptables nftables procps-ng psmisc || \
log_warn "Часть rpm-пакетов не установилась, продолжаю с доступными утилитами"
pkg_install wireguard-tools || \
log_warn "wireguard-tools не установлен; будет использован userspace WireGuard"
;;
pacman)
pkg_install ca-certificates iproute2 iptables nftables procps-ng psmisc || \
log_warn "Часть pacman-пакетов не установилась, продолжаю с доступными утилитами"
pkg_install wireguard-tools || \
log_warn "wireguard-tools не установлен; будет использован userspace WireGuard"
;;
esac
}
@@ -378,8 +416,22 @@ setup_sysctl() {
mkdir -p /etc/sysctl.d
cat > /etc/sysctl.d/99-wdtt.conf << 'SYSEOF'
net.ipv4.ip_forward = 1
net.core.default_qdisc = fq
net.core.rmem_max = 25165824
net.core.wmem_max = 25165824
net.core.rmem_default = 4194304
net.core.wmem_default = 4194304
net.core.netdev_max_backlog = 16384
net.ipv4.udp_rmem_min = 262144
net.ipv4.udp_wmem_min = 262144
net.ipv4.tcp_rmem = 4096 87380 25165824
net.ipv4.tcp_wmem = 4096 65536 25165824
SYSEOF
if sysctl -n net.ipv4.tcp_available_congestion_control 2>/dev/null | grep -qw bbr; then
echo 'net.ipv4.tcp_congestion_control = bbr' >> /etc/sysctl.d/99-wdtt.conf
fi
sysctl -p /etc/sysctl.d/99-wdtt.conf >/dev/null 2>&1 || true
echo "✓ Sysctl настроен"
@@ -461,7 +513,7 @@ Wants=network-online.target
Type=simple
ExecStartPre=-/usr/bin/env bash -c "ip link show ${WDTT_IFACE} >/dev/null 2>&1 && ip link del ${WDTT_IFACE} 2>/dev/null || true"
ExecStartPre=-/usr/bin/env bash -c "if command -v iptables >/dev/null 2>&1; then iptables -C INPUT -p udp --dport ${DTLS_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${DTLS_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; iptables -C INPUT -p udp --dport ${WG_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${WG_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; iptables -C INPUT -p tcp --dport ${SSH_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport ${SSH_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; fi"
ExecStart=/usr/local/bin/wdtt-server -listen 0.0.0.0:${DTLS_PORT} -wg-port ${WG_PORT} -config-dir ${WDTT_CONFIG_DIR} -max-passwords ${MAX_PASSWORDS} ${WDTT_ARGS}
ExecStart=/usr/local/bin/wdtt-server -listen 0.0.0.0:${DTLS_PORT} -wg-port ${WG_PORT} -config-dir ${WDTT_CONFIG_DIR} -max-passwords ${MAX_PASSWORDS} -max-workers-per-access ${MAX_WORKERS_PER_ACCESS} -max-handshakes ${MAX_HANDSHAKES} -handshake-rate ${HANDSHAKE_RATE} -max-client-mbps ${MAX_CLIENT_MBPS} -wg-backend ${WG_BACKEND} ${WDTT_ARGS}
Restart=always
RestartSec=5
LimitNOFILE=65535
@@ -572,6 +624,7 @@ main() {
validate_port "WDTT_DTLS_PORT" "$DTLS_PORT"
validate_port "WDTT_WG_PORT" "$WG_PORT"
validate_port "WDTT_SSH_PORT" "$SSH_PORT"
validate_runtime_limits
mkdir -p "$(dirname "$LOG_FILE")"
echo "=== WDTT Plus Installer v${SCRIPT_VERSION} — $(date) ===" >> "$LOG_FILE"
@@ -0,0 +1,216 @@
package com.wdtt.plus
enum class AccessLifecycleSeverity {
NORMAL,
WARNING,
ERROR;
companion object {
fun parse(value: String, allowConnect: Boolean): AccessLifecycleSeverity =
when (value.trim().lowercase()) {
"normal", "info" -> NORMAL
"warning", "warn" -> WARNING
"error", "danger" -> ERROR
else -> if (allowConnect) NORMAL else ERROR
}
}
}
/**
* Opaque provider-neutral capability attached to a remotely managed profile.
*
* Android does not interpret the provider policy behind this capability. It
* submits the protected key to the exact HTTPS service URL, then applies only
* the generic connection decision and optional document/action returned by it.
*/
data class RemoteAccessCapability(
val available: Boolean,
val key: String = "",
val url: String = "",
val binding: String = "",
val initialStatus: AccessLifecycleStatus? = null,
val cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable,
val exchange: RemoteProfileExchange = RemoteProfileExchange.Unavailable,
) {
companion object {
val Unavailable = RemoteAccessCapability(available = false)
}
}
/**
* Provider-neutral exchange attached to one remotely managed profile.
*
* Tokens are opaque and device-bound. Android can submit the profile's normal
* auxiliary values or invoke the remotely presented action, but it does not
* know why the provider stores them or how the returned update is produced.
*/
data class RemoteProfileExchange(
val submitAvailable: Boolean,
val submitToken: String = "",
val actionAvailable: Boolean = false,
val actionToken: String = "",
val label: String = "",
val message: String = "",
) {
companion object {
val Unavailable = RemoteProfileExchange(submitAvailable = false)
}
}
/**
* A provider-neutral action cached with a remotely managed profile.
*
* Android treats [payload] as an opaque clipboard value and opens [target]
* exactly as supplied. Presentation is also remote-provided, so the APK does
* not know which external channel fulfills the action.
*/
data class CachedRemoteAction(
val available: Boolean,
val payload: String = "",
val target: RemoteLaunchTarget = RemoteLaunchTarget(primaryUrl = ""),
val title: String = "",
val message: String = "",
val label: String = "",
val clipboardLabel: String = "",
val copiedMessage: String = "",
val failedMessage: String = "",
val helpTitle: String = "",
val helpIntro: String = "",
val helpSteps: String = "",
) {
companion object {
val Unavailable = CachedRemoteAction(available = false)
}
}
data class AccessProfileUpdate(
val revision: Long,
val link: RemoteDocumentLink,
)
data class AccessLifecycleStatus(
val allowConnect: Boolean,
val actionAvailable: Boolean,
val actionLabel: String = "",
val actionMessage: String = "",
val title: String = "",
val message: String = "",
val detailLabel: String = "",
val detailValue: String = "",
val actionIcon: String = "",
val severity: AccessLifecycleSeverity = AccessLifecycleSeverity.NORMAL,
val checkedAtMillis: Long = System.currentTimeMillis(),
val profileRevision: Long = 0,
val profileUpdate: AccessProfileUpdate? = null,
val cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable,
val exchange: RemoteProfileExchange? = null,
)
data class StoredAccessLifecycle(
val managed: Boolean,
val capability: RemoteAccessCapability,
val status: AccessLifecycleStatus?,
val appliedProfileRevision: Long,
val lastAttemptAtMillis: Long,
)
data class AccessLifecycleUiState(
val managed: Boolean,
val allowConnect: Boolean,
val actionAvailable: Boolean,
val actionLabel: String,
val actionMessage: String,
val title: String,
val message: String,
val detailLabel: String = "",
val detailValue: String = "",
val actionIcon: String = "",
val severity: AccessLifecycleSeverity,
val checkedAtMillis: Long,
) {
companion object {
val Unmanaged = AccessLifecycleUiState(
managed = false,
allowConnect = true,
actionAvailable = false,
actionLabel = "",
actionMessage = "",
title = "",
message = "",
detailLabel = "",
detailValue = "",
actionIcon = "",
severity = AccessLifecycleSeverity.NORMAL,
checkedAtMillis = 0,
)
}
}
internal fun accessLifecycleDismissalSignature(
lifecycle: AccessLifecycleUiState,
): String {
if (!lifecycle.managed) return ""
return listOf(
lifecycle.allowConnect,
lifecycle.actionAvailable,
lifecycle.title,
lifecycle.message,
lifecycle.detailLabel,
lifecycle.detailValue,
).joinToString("|")
}
internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState {
val current = status
return AccessLifecycleUiState(
managed = managed,
allowConnect = current?.allowConnect ?: true,
actionAvailable = current?.actionAvailable == true,
actionLabel = current?.actionLabel.orEmpty(),
actionMessage = current?.actionMessage.orEmpty(),
title = current?.title.orEmpty(),
message = current?.message.orEmpty(),
detailLabel = current?.detailLabel.orEmpty(),
detailValue = current?.detailValue.orEmpty(),
actionIcon = current?.actionIcon.orEmpty(),
severity = current?.severity ?: AccessLifecycleSeverity.NORMAL,
checkedAtMillis = current?.checkedAtMillis ?: 0,
)
}
internal sealed interface AccessStartDecision {
data object Allowed : AccessStartDecision
data class Denied(val status: AccessLifecycleStatus) : AccessStartDecision
}
internal fun accessStartDecision(
lifecycle: StoredAccessLifecycle,
): AccessStartDecision {
val status = lifecycle.status
val pendingProfileUpdate = status?.profileUpdate
?.revision
?.let { it > lifecycle.appliedProfileRevision } == true
return if (
!lifecycle.capability.available ||
status == null ||
(status.allowConnect && !pendingProfileUpdate)
) {
AccessStartDecision.Allowed
} else {
AccessStartDecision.Denied(
if (pendingProfileUpdate) {
status.copy(
allowConnect = false,
title = "Нужно обновить профиль",
message = "Не удалось применить новые параметры. Повторите подключение.",
severity = AccessLifecycleSeverity.WARNING,
)
} else {
status
}
)
}
}
internal fun AccessLifecycleUiState.fallbackTitle(): String =
if (allowConnect) "Профиль доступен" else "Профиль временно недоступен"
@@ -0,0 +1,567 @@
package com.wdtt.plus
import android.content.Context
import android.os.Build
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.TimeZone
sealed interface AccessLifecycleRefreshResult {
data object Unmanaged : AccessLifecycleRefreshResult
data class Success(val status: AccessLifecycleStatus) : AccessLifecycleRefreshResult
data class Cached(val status: AccessLifecycleStatus?) : AccessLifecycleRefreshResult
data class Throttled(
val status: AccessLifecycleStatus?,
val retryAfterMillis: Long,
) : AccessLifecycleRefreshResult
data class Failed(val message: String, val cached: AccessLifecycleStatus?) :
AccessLifecycleRefreshResult
}
object AccessLifecycleCoordinator {
private const val STATUS_CACHE_TTL_MS = 10 * 60 * 1000L
private const val MIN_ATTEMPT_INTERVAL_MS = 10_000L
private val profileLocks = Array(3) { Mutex() }
private val _refreshingProfiles = MutableStateFlow<Set<Int>>(emptySet())
val refreshingProfiles: StateFlow<Set<Int>> = _refreshingProfiles.asStateFlow()
private val pendingExternalRefresh = mutableSetOf<Int>()
suspend fun refreshProfile(
context: Context,
profileIndex: Int,
force: Boolean = false,
): AccessLifecycleRefreshResult {
val appContext = context.applicationContext
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(appContext)
val before = store.accessLifecycleForProfile(profile)
if (!before.capability.available) return AccessLifecycleRefreshResult.Unmanaged
val now = System.currentTimeMillis()
if (
!force &&
before.status != null &&
now - before.status.checkedAtMillis in 0 until STATUS_CACHE_TTL_MS
) {
return AccessLifecycleRefreshResult.Cached(before.status)
}
val attemptAge = now - before.lastAttemptAtMillis
if (attemptAge in 0 until MIN_ATTEMPT_INTERVAL_MS) {
return AccessLifecycleRefreshResult.Throttled(
status = before.status,
retryAfterMillis = MIN_ATTEMPT_INTERVAL_MS - attemptAge,
)
}
return profileLocks[profile].withLock {
val current = store.accessLifecycleForProfile(profile)
val currentNow = System.currentTimeMillis()
if (!current.capability.available) return@withLock AccessLifecycleRefreshResult.Unmanaged
syncPendingProfileValues(store, profile, current.capability)
if (
!force &&
current.status != null &&
currentNow - current.status.checkedAtMillis in 0 until STATUS_CACHE_TTL_MS
) {
return@withLock AccessLifecycleRefreshResult.Cached(current.status)
}
val currentAttemptAge = currentNow - current.lastAttemptAtMillis
if (currentAttemptAge in 0 until MIN_ATTEMPT_INTERVAL_MS) {
return@withLock AccessLifecycleRefreshResult.Throttled(
status = current.status,
retryAfterMillis = MIN_ATTEMPT_INTERVAL_MS - currentAttemptAge,
)
}
store.saveAccessLifecycleAttempt(profile, currentNow)
setRefreshing(profile, true)
try {
val received = AccessLifecycleGateway.fetch(
capability = current.capability,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
profileRevision = current.appliedProfileRevision,
)
val effectiveCapability = current.capability.copy(
exchange = received.exchange ?: current.capability.exchange,
)
if (effectiveCapability != current.capability) {
store.saveRemoteAccessCapability(effectiveCapability, profile)
}
val effectiveCurrent = current.copy(capability = effectiveCapability)
// Статус доступа самодостаточен: сохраняем его даже если отдельное
// обновление параметров профиля временно не удалось скачать или применить.
if (
!store.saveAccessLifecycleStatus(
profile,
received,
expectedCapability = effectiveCapability,
)
) {
return@withLock AccessLifecycleRefreshResult.Unmanaged
}
val profileUpdated = applyProfileUpdateIfNeeded(
appContext = appContext,
store = store,
profile = profile,
current = effectiveCurrent,
status = received,
)
// Новая capability может очистить прежний статус при ротации ключа.
if (profileUpdated) {
store.saveAccessLifecycleStatus(
profile,
received,
expectedCapability = effectiveCapability,
)
}
// Состояние управляемого доступа показывается своей профильной карточкой.
// Общая ошибка подключения не должна дублировать её и переноситься на
// другой, в том числе ручной, профиль.
TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS)
if (
current.status?.allowConnect != received.allowConnect ||
current.status?.title != received.title
) {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profile}_decision",
message = received.title.ifBlank { "Состояние профиля обновлено" },
warning = received.severity != AccessLifecycleSeverity.NORMAL,
)
}
updateExternalSurfaces(appContext)
AccessLifecycleRefreshResult.Success(received)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: AccessLifecycleRequestException) {
if (!error.kind.authoritative) {
return@withLock accessRefreshFailure(profile, current, error)
}
val denied = authoritativeAccessDenialStatus(
failure = error,
cached = current.status,
)
if (
!store.saveAccessLifecycleStatus(
profile,
denied,
expectedCapability = current.capability,
)
) {
return@withLock AccessLifecycleRefreshResult.Unmanaged
}
TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS)
if (
current.status?.allowConnect != denied.allowConnect ||
current.status?.title != denied.title
) {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profile}_${error.code}",
message = denied.title,
warning = true,
)
}
updateExternalSurfaces(appContext)
AccessLifecycleRefreshResult.Success(denied)
} catch (error: Exception) {
accessRefreshFailure(profile, current, error)
} finally {
setRefreshing(profile, false)
}
}
}
private fun accessRefreshFailure(
profile: Int,
current: StoredAccessLifecycle,
error: Exception,
): AccessLifecycleRefreshResult.Failed {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profile}_check_failed",
message = error.message ?: "Не удалось обновить сведения о доступе",
warning = true,
)
return AccessLifecycleRefreshResult.Failed(
message = error.message ?: "Не удалось проверить профиль.",
cached = current.status,
)
}
internal suspend fun prepareStart(
context: Context,
profileIndex: Int,
): AccessStartDecision {
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(context.applicationContext)
val current = store.accessLifecycleForProfile(profile)
if (!current.capability.available) return AccessStartDecision.Allowed
val now = System.currentTimeMillis()
val cachedDecision = accessStartDecision(current)
val fresh = current.status?.checkedAtMillis?.let {
now - it in 0 until STATUS_CACHE_TTL_MS
} == true
if (fresh && cachedDecision == AccessStartDecision.Allowed) {
return AccessStartDecision.Allowed
}
return when (val refreshed = refreshProfile(context, profile, force = true)) {
is AccessLifecycleRefreshResult.Success ->
if (refreshed.status.allowConnect) {
AccessStartDecision.Allowed
} else {
AccessStartDecision.Denied(refreshed.status)
}
is AccessLifecycleRefreshResult.Cached -> {
accessStartDecision(store.accessLifecycleForProfile(profile))
}
is AccessLifecycleRefreshResult.Throttled -> {
accessStartDecision(store.accessLifecycleForProfile(profile))
}
is AccessLifecycleRefreshResult.Failed ->
accessStartDecision(store.accessLifecycleForProfile(profile))
AccessLifecycleRefreshResult.Unmanaged -> AccessStartDecision.Allowed
}
}
suspend fun beginAction(
context: Context,
profileIndex: Int,
): RemoteLaunchTarget {
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(context.applicationContext)
val current = store.accessLifecycleForProfile(profile)
require(current.capability.available && current.status?.actionAvailable == true) {
current.status?.actionMessage?.ifBlank {
"Действие сейчас недоступно."
} ?: "Действие сейчас недоступно."
}
val target = AccessLifecycleGateway.begin(
capability = current.capability,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
profileRevision = current.appliedProfileRevision,
)
store.markAccessLifecycleActionLaunched(profile)
synchronized(pendingExternalRefresh) {
pendingExternalRefresh += profile
}
return target
}
suspend fun noteServerDenied(context: Context, profileIndex: Int) {
val appContext = context.applicationContext
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(appContext)
store.markAccessLifecycleDenied(profile)
updateExternalSurfaces(appContext)
refreshProfile(appContext, profile, force = true)
}
suspend fun refreshAllIfStale(context: Context) {
val store = SettingsStore(context.applicationContext)
store.accessLifecycleProfiles().forEach { profile ->
refreshProfile(context, profile, force = false)
}
}
suspend fun refreshAllOnForeground(
context: Context,
alreadyScheduledProfiles: Set<Int> = emptySet(),
) {
val store = SettingsStore(context.applicationContext)
accessProfilesForForegroundRefresh(
managedProfiles = store.accessLifecycleProfiles(),
alreadyScheduledProfiles = alreadyScheduledProfiles,
).forEach { profile ->
refreshAfterAttemptWindow(context, profile)
}
}
suspend fun refreshAfterSuccessfulConnect(context: Context, profileIndex: Int) {
refreshAfterAttemptWindow(context, profileIndex)
}
suspend fun refreshAfterExternalAction(
context: Context,
profileIndex: Int,
): AccessLifecycleRefreshResult =
refreshAfterAttemptWindow(context, profileIndex)
private suspend fun refreshAfterAttemptWindow(
context: Context,
profileIndex: Int,
): AccessLifecycleRefreshResult {
val first = refreshProfile(
context.applicationContext,
profileIndex,
force = true,
)
if (first !is AccessLifecycleRefreshResult.Throttled) return first
delay(first.retryAfterMillis)
return refreshProfile(
context.applicationContext,
profileIndex,
force = true,
)
}
fun takePendingExternalRefreshProfiles(): Set<Int> = synchronized(pendingExternalRefresh) {
pendingExternalRefresh.toSet().also { pendingExternalRefresh.clear() }
}
suspend fun syncProfileValues(
context: Context,
profileIndex: Int,
values: List<String>,
): Boolean {
val profile = profileIndex.coerceIn(0, 2)
val cleaned = values
.map(VkJoinLink::extractHash)
.filter(VkJoinLink::isValidHash)
.distinct()
.take(4)
val store = SettingsStore(context.applicationContext)
val current = store.accessLifecycleForProfile(profile)
val exchange = current.capability.exchange
if (
!current.capability.available ||
!exchange.submitAvailable ||
exchange.submitToken.isBlank()
) {
return false
}
store.markProfileValuesSyncPending(profile)
val updatedExchange = AccessLifecycleGateway.submitProfileValues(
capability = current.capability,
token = exchange.submitToken,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
values = cleaned,
)
store.saveRemoteAccessCapability(
current.capability.copy(exchange = updatedExchange),
profile,
)
store.clearProfileValuesSyncPending(profile)
return true
}
suspend fun restoreProfileValues(
context: Context,
profileIndex: Int,
expectedCapability: RemoteAccessCapability,
): WdttDeepLinkApplyResult {
val appContext = context.applicationContext
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(appContext)
return profileLocks[profile].withLock {
val current = store.accessLifecycleForProfile(profile)
require(
current.capability.available &&
expectedCapability.available &&
current.capability.key == expectedCapability.key &&
current.capability.url == expectedCapability.url &&
current.capability.binding == expectedCapability.binding
) {
"Сохранённые данные относятся к другому профилю."
}
val exchange = current.capability.exchange
require(
exchange.actionAvailable && exchange.actionToken.isNotBlank()
) {
"Действие для этого профиля больше недоступно."
}
val link = AccessLifecycleGateway.invokeProfileAction(
capability = current.capability,
token = exchange.actionToken,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
profileRevision = current.appliedProfileRevision,
)
val delivery = RemoteDocumentGateway.receive(
link = link,
device = store.getOrCreateConnectDeviceId(),
label = androidDeviceLabel(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
localBindings = store.remoteDocumentBindings(),
)
require(delivery.kind == RemoteDocumentKind.UPDATE) {
"WDTT Plus вернул неподходящее обновление профиля."
}
require(
current.capability.binding.isNotBlank() &&
delivery.binding == current.capability.binding
) {
"Обновление относится к другому профилю."
}
val applied = store.applyRemoteDocumentDelivery(
plan = WdttDeepLinkApplyPlan(
link = delivery.document,
targetProfile = profile,
requiresConfirmation = false,
storeAsLink = false,
),
delivery = delivery,
isBoundUpdate = true,
) ?: throw IllegalStateException("Не удалось применить обновление профиля.")
store.clearProfileValuesSyncPending(profile)
requestTunnelProfileRuntimeUpdate(profile)
applied
}
}
private suspend fun syncPendingProfileValues(
store: SettingsStore,
profile: Int,
capability: RemoteAccessCapability,
) {
if (!store.profileValuesSyncPending(profile)) return
val exchange = capability.exchange
if (!exchange.submitAvailable || exchange.submitToken.isBlank()) return
val values = store.tunnelProfileSnapshot(profile).vkHashes
.split(",")
.map(VkJoinLink::extractHash)
.filter(VkJoinLink::isValidHash)
.distinct()
.take(4)
runCatching {
val updatedExchange = AccessLifecycleGateway.submitProfileValues(
capability = capability,
token = exchange.submitToken,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
values = values,
)
store.saveRemoteAccessCapability(
capability.copy(exchange = updatedExchange),
profile,
)
}.onSuccess {
store.clearProfileValuesSyncPending(profile)
}
}
private suspend fun applyProfileUpdateIfNeeded(
appContext: Context,
store: SettingsStore,
profile: Int,
current: StoredAccessLifecycle,
status: AccessLifecycleStatus,
): Boolean {
val update = status.profileUpdate ?: return false
if (update.revision <= current.appliedProfileRevision) return false
val delivery = RemoteDocumentGateway.receive(
link = update.link,
device = store.getOrCreateConnectDeviceId(),
label = androidDeviceLabel(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
localBindings = store.remoteDocumentBindings(),
)
require(delivery.kind == RemoteDocumentKind.UPDATE) {
"WDTT Plus вернул неподходящее обновление профиля."
}
val binding = store.remoteAccessBindingForProfile(profile)
require(binding.isNotBlank() && delivery.binding == binding) {
"Обновление относится к другому профилю."
}
val applied = store.applyWdttDeepLink(
plan = WdttDeepLinkApplyPlan(
link = delivery.document,
targetProfile = profile,
requiresConfirmation = false,
storeAsLink = false,
),
resetRemoteContinuation = false,
profileMaxWorkers = delivery.profileMaxWorkers,
remoteManaged = null,
preserveVkHashes = true,
)
require(applied != null) { "Не удалось применить обновление профиля." }
if (delivery.access.available) {
store.saveRemoteAccessCapability(delivery.access, profile)
}
store.saveAppliedAccessProfileRevision(profile, update.revision)
requestTunnelProfileRuntimeUpdate(profile)
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profile}_updated",
message = "Параметры профиля обновлены",
warning = false,
)
return true
}
private fun androidDeviceLabel(): String {
val values = listOf(Build.MANUFACTURER, Build.MODEL)
.map(String::trim)
.filter(String::isNotBlank)
.distinctBy(String::lowercase)
return values.joinToString(" ").ifBlank { "Android-устройство" }
}
private fun setRefreshing(profile: Int, refreshing: Boolean) {
_refreshingProfiles.value = _refreshingProfiles.value.toMutableSet().apply {
if (refreshing) add(profile) else remove(profile)
}
}
private fun updateExternalSurfaces(context: Context) {
VpnWidgetProvider.updateAllWidgets(context)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
android.service.quicksettings.TileService.requestListeningState(
context,
android.content.ComponentName(context, QuickToggleTileService::class.java),
)
}
}
}
internal fun accessProfilesForForegroundRefresh(
managedProfiles: Collection<Int>,
alreadyScheduledProfiles: Set<Int>,
): List<Int> = managedProfiles
.filter { it in 0..2 && it !in alreadyScheduledProfiles }
.distinct()
.sorted()
internal fun authoritativeAccessDenialStatus(
failure: AccessLifecycleRequestException,
cached: AccessLifecycleStatus?,
checkedAtMillis: Long = System.currentTimeMillis(),
): AccessLifecycleStatus {
require(failure.kind.authoritative)
val (title, fallbackMessage) = when (failure.kind) {
AccessLifecycleFailureKind.REJECTED ->
"Профиль недоступен" to
"Поставщик отклонил использование этого профиля."
AccessLifecycleFailureKind.UNBOUND ->
"Профиль отвязан" to
"Запросите новую ссылку на профиль у поставщика."
AccessLifecycleFailureKind.UNAVAILABLE ->
"Профиль больше недоступен" to
"Проверьте профиль и привязку устройства у поставщика."
AccessLifecycleFailureKind.TEMPORARY -> error("temporary failure is not authoritative")
}
return AccessLifecycleStatus(
allowConnect = false,
actionAvailable = false,
title = title,
message = failure.message?.takeIf { it.isNotBlank() } ?: fallbackMessage,
severity = AccessLifecycleSeverity.ERROR,
checkedAtMillis = checkedAtMillis,
profileRevision = cached?.profileRevision ?: 0,
)
}
@@ -0,0 +1,384 @@
package com.wdtt.plus
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
enum class AccessLifecycleFailureKind {
REJECTED,
UNBOUND,
UNAVAILABLE,
TEMPORARY;
val authoritative: Boolean
get() = this != TEMPORARY
}
class AccessLifecycleRequestException(
val kind: AccessLifecycleFailureKind,
val code: String,
message: String,
) : IllegalStateException(message)
object AccessLifecycleGateway {
private const val MAX_RESPONSE_CHARS = 32 * 1024
suspend fun fetch(
capability: RemoteAccessCapability,
device: String,
client: String,
system: String,
timezone: String,
profileRevision: Long,
): AccessLifecycleStatus = request(
capability = capability,
device = device,
client = client,
system = system,
timezone = timezone,
profileRevision = profileRevision,
operation = "status",
).let(::parseStatus)
suspend fun begin(
capability: RemoteAccessCapability,
device: String,
client: String,
system: String,
timezone: String,
profileRevision: Long,
): RemoteLaunchTarget = request(
capability = capability,
device = device,
client = client,
system = system,
timezone = timezone,
profileRevision = profileRevision,
operation = "continue",
).let(::parseLaunchTarget)
suspend fun submitProfileValues(
capability: RemoteAccessCapability,
token: String,
device: String,
client: String,
system: String,
timezone: String,
values: List<String>,
): RemoteProfileExchange =
parseExchangeResult(
request(
capability = capability,
device = device,
client = client,
system = system,
timezone = timezone,
profileRevision = 0,
action = token,
values = values,
)
)
suspend fun invokeProfileAction(
capability: RemoteAccessCapability,
token: String,
device: String,
client: String,
system: String,
timezone: String,
profileRevision: Long,
): RemoteDocumentLink = request(
capability = capability,
device = device,
client = client,
system = system,
timezone = timezone,
profileRevision = profileRevision,
action = token,
).let(::parseActionDocument)
private suspend fun request(
capability: RemoteAccessCapability,
device: String,
client: String,
system: String,
timezone: String,
profileRevision: Long,
operation: String = "",
action: String = "",
values: List<String> = emptyList(),
): String {
require(capability.available && opaqueValue(capability.key)) {
"Управление доступом недоступно для этого профиля."
}
require(safeServiceUrl(capability.url)) {
"Не удалось проверить доступ для этого профиля."
}
require(validDevice(device)) { "Не удалось определить текущее устройство." }
require(
(
operation in setOf("status", "continue") &&
action.isBlank()
) ||
(
operation.isBlank() &&
opaqueValue(action)
)
)
require(values.size <= 16)
return withContext(Dispatchers.IO) {
val payload = JSONObject()
.put("key", capability.key.trim())
.put("device", device.trim())
.put("client", client.trim().take(64))
.put("system", system.trim().take(64))
.put("timezone", timezone.trim().take(64))
.put("profile_revision", profileRevision.coerceAtLeast(0))
.put("values", org.json.JSONArray(values))
.apply {
if (operation.isNotBlank()) put("operation", operation)
if (action.isNotBlank()) put("action", action)
}
.toString()
.toByteArray(Charsets.UTF_8)
var connection: HttpURLConnection? = null
try {
connection = URL(capability.url).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.instanceFollowRedirects = false
connection.connectTimeout = 7_000
connection.readTimeout = 9_000
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val body = readBody(connection, status)
if (status !in 200..299) {
throw parseHttpFailure(
status = status,
body = body,
operation = operation,
codeHint = connection.getHeaderField("X-WDTT-Access-Code").orEmpty(),
)
}
body
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
if (error is IllegalStateException) throw error
throw IllegalStateException(
if (operation == "continue") {
"Не удалось открыть страницу. Проверьте интернет и повторите попытку."
} else if (action.isNotBlank()) {
"Не удалось обновить сохранённые данные профиля."
} else {
"Не удалось проверить профиль. Проверьте интернет."
}
)
} finally {
connection?.disconnect()
}
}
}
internal fun parseHttpFailure(
status: Int,
body: String,
operation: String,
codeHint: String = "",
): AccessLifecycleRequestException {
val root = runCatching { JSONObject(body) }.getOrNull()
val detail = root?.opt("detail")
val structured = detail as? JSONObject
val code = structured?.optString("code").orEmpty()
.ifBlank { root?.optString("code").orEmpty() }
.ifBlank { codeHint }
.trim()
.lowercase()
val message = (
structured?.optString("message")
?: (detail as? String)
?: ""
).trim().take(300)
val kind = when {
status == 410 || code == "expired" -> AccessLifecycleFailureKind.REJECTED
code in setOf("unbound", "device_mismatch") -> AccessLifecycleFailureKind.UNBOUND
status in setOf(401, 403, 404) ||
code in setOf("removed", "revoked", "not_found", "forbidden") ->
AccessLifecycleFailureKind.UNAVAILABLE
else -> AccessLifecycleFailureKind.TEMPORARY
}
val fallback = when {
operation == "continue" -> "Действие сейчас недоступно. Попробуйте позже."
kind == AccessLifecycleFailureKind.REJECTED ->
"Поставщик отклонил использование этого профиля."
kind == AccessLifecycleFailureKind.UNBOUND ->
"Профиль отвязан от этого устройства."
kind == AccessLifecycleFailureKind.UNAVAILABLE ->
"Профиль больше недоступен для этого устройства."
else -> "Не удалось проверить профиль."
}
return AccessLifecycleRequestException(
kind = kind,
code = code.ifBlank { "http_$status" },
message = message.ifBlank { fallback },
)
}
internal fun parseStatus(body: String): AccessLifecycleStatus {
val root = parseRoot(body)
require(root.optInt("version", 0) == 1) {
"Для проверки доступа нужна более новая версия WDTT Plus."
}
require(root.has("allow_connect")) {
"WDTT Plus вернул неполное решение по профилю."
}
val allowConnect = root.optBoolean("allow_connect", false)
val action = root.optJSONObject("action")
val actionAvailable = action?.optBoolean("available", false) == true
val actionLabel = action?.optString("label").orEmpty().trim().take(80)
val actionMessage = action?.optString("message").orEmpty().trim().take(240)
val actionIcon = action?.optString("icon").orEmpty().trim().take(32)
.takeIf { it == "update" }
.orEmpty()
val title = root.optString("title").trim().take(120)
val message = root.optString("message").trim().take(400)
val detail = root.optJSONObject("detail")
val detailLabel = detail?.optString("label").orEmpty().trim().take(80)
val detailValue = detail?.optString("value").orEmpty().trim().take(120)
val severity = AccessLifecycleSeverity.parse(
root.optString("severity"),
allowConnect,
)
val profile = root.optJSONObject("profile")
val revision = profile?.optLong("revision", 0)?.coerceAtLeast(0) ?: 0
val update = if (profile?.optBoolean("update_available", false) == true) {
val link = RemoteDocumentGateway.extractLink(profile.optString("document"))
?: throw IllegalStateException("WDTT Plus вернул повреждённое обновление профиля.")
require(revision > 0) { "WDTT Plus вернул неполное обновление профиля." }
AccessProfileUpdate(revision = revision, link = link)
} else {
null
}
val cachedAction = root.optJSONObject("cached_action")
?.let(RemoteDocumentGateway::parseCachedAction)
?: CachedRemoteAction.Unavailable
val exchange = root.optJSONObject("exchange")
?.let(RemoteDocumentGateway::parseProfileExchange)
return AccessLifecycleStatus(
allowConnect = allowConnect,
actionAvailable = actionAvailable,
actionLabel = actionLabel,
actionMessage = actionMessage,
title = title,
message = message,
detailLabel = detailLabel,
detailValue = detailValue,
actionIcon = actionIcon,
severity = severity,
profileRevision = revision,
profileUpdate = update,
cachedAction = cachedAction,
exchange = exchange,
)
}
internal fun parseLaunchTarget(body: String): RemoteLaunchTarget {
val root = parseRoot(body)
val primary = root.optString("url").trim()
val fallback = root.optString("fallback").trim()
val handler = root.optString("handler").trim()
val alternateHandlers = root.optJSONArray("alternate_handlers")?.let { source ->
if (source.length() > 7) null else {
(0 until source.length())
.map { index -> source.optString(index).trim() }
.takeIf { values ->
values.all { it.isNotBlank() && safePackageName(it) } &&
values.distinct().size == values.size
}
}
} ?: if (root.has("alternate_handlers")) null else emptyList()
require(safeExternalUrl(primary)) {
"WDTT Plus вернул повреждённый адрес продолжения."
}
require(fallback.isBlank() || safeExternalUrl(fallback)) {
"WDTT Plus вернул повреждённый резервный адрес."
}
require(handler.isBlank() || safePackageName(handler)) {
"WDTT Plus вернул повреждённый обработчик продолжения."
}
require(alternateHandlers != null) {
"WDTT Plus вернул повреждённые резервные обработчики."
}
return RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternateHandlers,
)
}
internal fun parseActionDocument(body: String): RemoteDocumentLink {
val root = parseRoot(body)
require(root.optInt("version", 0) == 1) {
"Для действия нужна более новая версия WDTT Plus."
}
return RemoteDocumentGateway.extractLink(root.optString("document"))
?: throw IllegalStateException("WDTT Plus вернул повреждённое обновление профиля.")
}
internal fun parseExchangeResult(body: String): RemoteProfileExchange {
val root = parseRoot(body)
require(root.optInt("version", 0) == 1) {
"WDTT Plus не подтвердил обновление данных профиля."
}
val source = root.optJSONObject("exchange")
?: throw IllegalStateException("WDTT Plus вернул неполный ответ.")
return RemoteDocumentGateway.parseProfileExchange(source)
}
private fun parseRoot(body: String): JSONObject {
require(body.length <= MAX_RESPONSE_CHARS) { "Ответ WDTT Plus слишком большой." }
return runCatching { JSONObject(body) }
.getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") }
}
private fun safeServiceUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) &&
uri.rawUserInfo.isNullOrBlank() &&
uri.rawQuery.isNullOrBlank() &&
uri.rawFragment.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safeExternalUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safePackageName(value: String): Boolean =
value.length in 3..255 &&
Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value)
private fun opaqueValue(value: String): Boolean =
value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value)
private fun validDevice(value: String): Boolean =
Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim())
private fun readBody(connection: HttpURLConnection, status: Int): String {
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty()
}
}
+164 -20
View File
@@ -2,6 +2,8 @@ package com.wdtt.plus
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.content.FileProvider
@@ -33,8 +35,16 @@ private const val UPDATE_CHECK_TOTAL_TIMEOUT_MS = 25_000L
private const val UPDATE_CHECK_REQUEST_TIMEOUT_MS = 6_000L
private const val UPDATE_CHECK_MIN_REQUEST_TIMEOUT_MS = 1_000L
private const val UPDATE_APK_HASH_TIMEOUT_MS = 4_000L
private const val MAX_UPDATE_APK_BYTES = 200L * 1024L * 1024L
private const val MAX_UPDATE_METADATA_BYTES = 1024 * 1024
private const val MAX_UPDATE_WEB_BYTES = 512 * 1024
private const val MAX_UPDATE_REDIRECTS = 5
private const val GITHUB_API_RATE_LIMIT_FALLBACK_MS = 30L * 60L * 1000L
private val SIMPLE_VERSION_TAG_REGEX = Regex("^v?(\\d+)$", RegexOption.IGNORE_CASE)
private val TRUSTED_UPDATE_ASSET_HOSTS = setOf(
"objects.githubusercontent.com",
"release-assets.githubusercontent.com",
)
@Volatile
private var githubApiCooldownUntilMs = 0L
@@ -185,7 +195,12 @@ suspend fun resolveAppUpdateCandidate(
fun selectUpdateApkAsset(release: AppReleaseInfo): AppReleaseAsset? {
val apkAssets = release.assets
.filter { it.name.endsWith(".apk", ignoreCase = true) && it.downloadUrl.isNotBlank() }
.filter {
it.name.endsWith(".apk", ignoreCase = true) &&
it.sha256 != null &&
it.sizeBytes in 1..MAX_UPDATE_APK_BYTES &&
isTrustedUpdateDownloadUrl(it.downloadUrl, initialRequest = true)
}
if (apkAssets.isEmpty()) return null
Build.SUPPORTED_ABIS.orEmpty().forEach { abi ->
@@ -201,6 +216,14 @@ suspend fun downloadUpdateApk(
asset: AppReleaseAsset,
onProgress: suspend (AppUpdateDownloadProgress) -> Unit = {}
): File = withContext(Dispatchers.IO) {
val expectedSha256 = asset.sha256
?: throw SecurityException("Для APK отсутствует обязательный SHA-256.")
require(asset.sizeBytes in 1..MAX_UPDATE_APK_BYTES) {
"Размер APK отсутствует или превышает безопасный лимит."
}
require(isTrustedUpdateDownloadUrl(asset.downloadUrl, initialRequest = true)) {
"Адрес APK не принадлежит официальному выпуску WDTT Plus."
}
val appContext = context.applicationContext
val updatesDir = File(appContext.cacheDir, "updates").apply { mkdirs() }
updatesDir.listFiles()?.forEach { file ->
@@ -217,28 +240,58 @@ suspend fun downloadUpdateApk(
}
try {
conn = URL(asset.downloadUrl).openConnection() as HttpURLConnection
applyNoCacheHeaders(conn)
conn.instanceFollowRedirects = true
conn.requestMethod = "GET"
conn.setRequestProperty("Accept", "application/vnd.android.package-archive,application/octet-stream,*/*")
conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}")
conn.connectTimeout = 15_000
conn.readTimeout = 30_000
val responseCode = conn.responseCode
var currentUrl = URL(asset.downloadUrl)
var responseCode = 0
for (redirect in 0..MAX_UPDATE_REDIRECTS) {
val currentConnection = currentUrl.openConnection() as HttpURLConnection
conn = currentConnection
applyNoCacheHeaders(currentConnection)
currentConnection.instanceFollowRedirects = false
currentConnection.requestMethod = "GET"
currentConnection.setRequestProperty(
"Accept",
"application/vnd.android.package-archive,application/octet-stream",
)
currentConnection.setRequestProperty(
"User-Agent",
"WDTTAndroid/${BuildConfig.VERSION_NAME}",
)
currentConnection.connectTimeout = 15_000
currentConnection.readTimeout = 30_000
responseCode = currentConnection.responseCode
if (responseCode !in 300..399) break
val location = currentConnection.getHeaderField("Location")
?.takeIf { it.isNotBlank() }
?: throw IOException("GitHub вернул перенаправление без адреса.")
if (redirect >= MAX_UPDATE_REDIRECTS) {
throw IOException("GitHub вернул слишком много перенаправлений.")
}
val nextUrl = URL(currentUrl, location)
require(isTrustedUpdateDownloadUrl(nextUrl.toString(), initialRequest = false)) {
"GitHub перенаправил загрузку на недоверенный адрес."
}
currentConnection.disconnect()
conn = null
currentUrl = nextUrl
}
val activeConnection = conn ?: throw IOException("Не удалось открыть загрузку APK.")
if (responseCode !in 200..299) {
throw IOException("GitHub вернул HTTP $responseCode при скачивании APK")
}
val total = asset.sizeBytes.takeIf { it > 0L }
?: conn.contentLengthLong.takeIf { it > 0L }
?: 0L
val responseLength = activeConnection.contentLengthLong
if (responseLength > MAX_UPDATE_APK_BYTES) {
throw IOException("APK превышает безопасный лимит размера.")
}
if (responseLength > 0L && responseLength != asset.sizeBytes) {
throw IOException("Размер APK не совпал с данными выпуска.")
}
val total = asset.sizeBytes
var downloaded = 0L
var lastEmitAt = 0L
emit(0L, total)
conn.inputStream.use { input ->
activeConnection.inputStream.use { input ->
outputFile.outputStream().use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
@@ -246,6 +299,9 @@ suspend fun downloadUpdateApk(
if (read < 0) break
output.write(buffer, 0, read)
downloaded += read
if (downloaded > MAX_UPDATE_APK_BYTES || downloaded > asset.sizeBytes) {
throw IOException("APK превышает заявленный размер.")
}
val now = System.currentTimeMillis()
if (now - lastEmitAt >= 250L || downloaded == total) {
lastEmitAt = now
@@ -260,13 +316,12 @@ suspend fun downloadUpdateApk(
throw IOException("Размер APK не совпал с GitHub asset")
}
asset.sha256?.let { expected ->
val actual = outputFile.sha256Hex()
if (!actual.equals(expected, ignoreCase = true)) {
if (!actual.equals(expectedSha256, ignoreCase = true)) {
outputFile.delete()
throw SecurityException("SHA-256 скачанного APK не совпал с GitHub digest")
}
}
validateUpdatePackage(appContext, outputFile)
emit(outputFile.length(), total.takeIf { it > 0L } ?: outputFile.length())
outputFile
@@ -285,6 +340,7 @@ fun canRequestApkInstall(context: Context): Boolean {
fun installUpdateApk(context: Context, apkFile: File) {
val appContext = context.applicationContext
validateUpdatePackage(appContext, apkFile)
val uri = FileProvider.getUriForFile(appContext, "${appContext.packageName}.files", apkFile)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
@@ -294,6 +350,90 @@ fun installUpdateApk(context: Context, apkFile: File) {
appContext.startActivity(intent)
}
internal fun isTrustedUpdateDownloadUrl(
value: String,
initialRequest: Boolean,
): Boolean {
val uri = runCatching { java.net.URI(value) }.getOrNull() ?: return false
val host = uri.host?.lowercase(Locale.US)?.trimEnd('.') ?: return false
if (
!uri.scheme.equals("https", ignoreCase = true) ||
!uri.rawUserInfo.isNullOrBlank() ||
(uri.port != -1 && uri.port != 443) ||
!uri.rawFragment.isNullOrBlank()
) {
return false
}
if (initialRequest) {
return host == "github.com" &&
uri.path.orEmpty().startsWith(
"/Ivan4537/WDTT-Plus/releases/download/",
ignoreCase = true,
)
}
return host in TRUSTED_UPDATE_ASSET_HOSTS ||
host.endsWith(".release-assets.githubusercontent.com")
}
private fun validateUpdatePackage(context: Context, apkFile: File) {
require(apkFile.isFile && apkFile.length() in 1..MAX_UPDATE_APK_BYTES) {
"Файл обновления отсутствует или имеет недопустимый размер."
}
val packageManager = context.packageManager
val archive = packageManager.updateArchiveInfo(apkFile)
?: throw SecurityException("Не удалось проверить пакет обновления.")
val installed = packageManager.installedUpdateTargetInfo(context.packageName)
if (archive.packageName != context.packageName) {
throw SecurityException("APK предназначен для другого приложения.")
}
val archiveSigners = archive.currentSignerDigests()
val installedSigners = installed.currentSignerDigests()
if (
archiveSigners.isEmpty() ||
installedSigners.isEmpty() ||
archiveSigners != installedSigners
) {
throw SecurityException("Подпись APK не совпадает с установленным WDTT Plus.")
}
}
@Suppress("DEPRECATION")
private fun PackageManager.updateArchiveInfo(apkFile: File): PackageInfo? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
getPackageArchiveInfo(
apkFile.absolutePath,
PackageManager.PackageInfoFlags.of(
PackageManager.GET_SIGNING_CERTIFICATES.toLong(),
),
)
} else {
getPackageArchiveInfo(apkFile.absolutePath, PackageManager.GET_SIGNING_CERTIFICATES)
}
}
@Suppress("DEPRECATION")
private fun PackageManager.installedUpdateTargetInfo(packageName: String): PackageInfo {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
getPackageInfo(
packageName,
PackageManager.PackageInfoFlags.of(
PackageManager.GET_SIGNING_CERTIFICATES.toLong(),
),
)
} else {
getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES)
}
}
private fun PackageInfo.currentSignerDigests(): Set<String> {
val signers = signingInfo?.apkContentsSigners.orEmpty()
return signers.mapTo(linkedSetOf()) { signature ->
MessageDigest.getInstance("SHA-256")
.digest(signature.toByteArray())
.joinToString("") { "%02x".format(it) }
}
}
fun isNewerVersion(local: String, remote: String): Boolean {
val localParts = versionParts(local)
val remoteParts = versionParts(remote)
@@ -442,7 +582,9 @@ private fun fetchReleaseFromLatestWebRedirect(budget: UpdateCheckBudget): AppRel
}
if (responseCode in 200..299) {
val response = conn.inputStream.bufferedReader().use { it.readText() }
val response = conn.inputStream.use {
it.readUtf8TextLimited(MAX_UPDATE_WEB_BYTES)
}
val versionTag = Regex("/releases/tag/([^\"?#<]+)").find(response)?.groupValues?.getOrNull(1)
if (!versionTag.isNullOrBlank()) {
return AppReleaseInfo(versionTag, "$GITHUB_RELEASE_TAG_URL_PREFIX$versionTag", RemoteVersionSource.Release)
@@ -494,7 +636,9 @@ private fun fetchHttpText(
val responseCode = conn.responseCode
val stream = if (responseCode in 200..299) conn.inputStream else conn.errorStream
val response = stream?.bufferedReader()?.use { it.readText() }.orEmpty()
val response = stream?.use {
it.readUtf8TextLimited(MAX_UPDATE_METADATA_BYTES)
}.orEmpty()
if (responseCode in 200..299) {
if (isGitHubApi) githubApiCooldownUntilMs = 0L
@@ -0,0 +1,19 @@
package com.wdtt.plus
import java.io.ByteArrayOutputStream
import java.io.InputStream
internal fun InputStream.readUtf8TextLimited(maxBytes: Int): String {
require(maxBytes > 0) { "Лимит ответа должен быть положительным." }
val output = ByteArrayOutputStream(minOf(maxBytes, DEFAULT_BUFFER_SIZE))
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var total = 0
while (true) {
val read = read(buffer)
if (read < 0) break
total += read
require(total <= maxBytes) { "Ответ сервиса слишком большой." }
output.write(buffer, 0, read)
}
return output.toString(Charsets.UTF_8.name())
}
@@ -384,14 +384,8 @@ object CaptchaWebViewManager {
handler: android.webkit.SslErrorHandler,
error: android.net.http.SslError
) {
// Разрешаем только для доверенных доменов VK/OK
val url = error.url ?: ""
if (url.contains("vk.ru") || url.contains("vk.com") || url.contains("okcdn.ru")) {
handler.proceed()
} else {
handler.cancel()
Log.w(TAG, "SSL error rejected for: $url")
}
Log.w(TAG, "Отклонена страница с ошибкой TLS")
}
}
@@ -0,0 +1,562 @@
package com.wdtt.plus
import android.content.Context
import android.net.ConnectivityManager
import android.net.DnsResolver
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import android.os.CancellationSignal
import android.os.SystemClock
import android.telephony.TelephonyManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.io.DataInputStream
import java.io.DataOutputStream
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketTimeoutException
import java.net.URL
import java.net.UnknownHostException
import java.util.concurrent.Executor
import javax.net.ssl.HttpsURLConnection
import kotlin.coroutines.resume
data class ClientNetworkDiagnosticsReport(
val summaryLines: List<String>,
val items: List<DeviceCheckItem>
)
private data class DiagnosticNetwork(
val network: Network,
val capabilities: NetworkCapabilities,
val linkProperties: LinkProperties?,
val activeNetworkIsVpn: Boolean,
val mobileOperator: String
)
private data class NetworkProbeResult(
val label: String,
val success: Boolean,
val result: String,
val elapsedMs: Long
) {
fun display(): String = "$label: $result (${elapsedMs} мс)"
}
internal data class DnsResponseStatus(
val responseCode: Int,
val answerCount: Int,
val truncated: Boolean
)
internal data class ClientDnsPathAssessment(
val status: String,
val recommendation: String,
val severity: DeviceCheckSeverity,
val action: DeviceCheckAction?
)
private const val NETWORK_PROBE_TIMEOUT_MS = 4_500L
private const val SOCKET_TIMEOUT_MS = 3_500
private val directExecutor = Executor { command -> command.run() }
private val clientDnsServers = listOf("77.88.8.8", "77.88.8.1")
private val clientDnsRouteOrder = listOf(
"77.88.8.8 UDP",
"77.88.8.1 UDP",
"77.88.8.8 TCP",
"77.88.8.1 TCP"
)
internal const val clientDnsProbeHost = "api.vk.me"
internal val primaryVkDiagnosticHosts = linkedSetOf(
"api.vk.me",
"calls.okcdn.ru"
)
internal val reserveVkDiagnosticHosts = linkedSetOf(
"vk.ru",
"login.vk.ru",
"api.vk.ru",
"id.vk.ru",
"static.vk.ru",
"vk.com",
"id.vk.com",
"static.vk.com"
)
private val vkDnsHosts = (primaryVkDiagnosticHosts + reserveVkDiagnosticHosts).toList()
private val vkHttpsTargets = listOf(
"api.vk.me" to "https://api.vk.me/method/users.get?v=5.276",
"calls.okcdn.ru" to "https://calls.okcdn.ru/fb.do",
"vk.ru" to "https://vk.ru/",
"login.vk.ru" to "https://login.vk.ru/",
"api.vk.ru" to "https://api.vk.ru/method/users.get?v=5.275",
"id.vk.ru" to "https://id.vk.ru/",
"static.vk.ru" to "https://static.vk.ru/",
"vk.com" to "https://vk.com/",
"id.vk.com" to "https://id.vk.com/",
"static.vk.com" to "https://static.vk.com/"
)
suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiagnosticsReport =
withContext(Dispatchers.IO) {
val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
val diagnosticNetwork = connectivityManager?.let { selectDiagnosticNetwork(context, it) }
if (diagnosticNetwork == null) {
return@withContext ClientNetworkDiagnosticsReport(
summaryLines = listOf("Активная физическая сеть для проверки DNS/VK не найдена"),
items = listOf(
DeviceCheckItem(
title = "Сетевой путь телефона",
status = "физическая сеть не найдена",
details = "Не удалось выбрать сеть без VPN для безопасной проверки DNS и узлов VK/OK.",
recommendation = "Отключите режим полёта, включите Wi‑Fi или мобильную сеть и повторите диагностику.",
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.NetworkSettings
)
)
)
}
val networkItem = buildNetworkPathItem(diagnosticNetwork)
val (dnsResults, clientDnsResults, httpsResults) = coroutineScope {
val systemDns = async { probeSystemDns(diagnosticNetwork.network) }
val clientDns = async { probeClientDns(diagnosticNetwork.network) }
val vkHttps = async { probeVkHttps(diagnosticNetwork.network) }
Triple(systemDns.await(), clientDns.await(), vkHttps.await())
}
val primaryDnsResults = dnsResults.filter { it.label in primaryVkDiagnosticHosts }
val reserveDnsResults = dnsResults.filter { it.label in reserveVkDiagnosticHosts }
val primaryDnsOk = primaryDnsResults.count { it.success }
val clientUdp = clientDnsResults.filter { it.label.endsWith("UDP") }
val clientTcp = clientDnsResults.filter { it.label.endsWith("TCP") }
val clientUdpOk = clientUdp.count { it.success }
val clientTcpOk = clientTcp.count { it.success }
val primaryHttpsResults = httpsResults.filter { it.label in primaryVkDiagnosticHosts }
val reserveHttpsResults = httpsResults.filter { it.label in reserveVkDiagnosticHosts }
val primaryHttpsOk = primaryHttpsResults.count { it.success }
val systemPrimaryApiWorks = dnsResults.firstOrNull { it.label == clientDnsProbeHost }?.success == true
val successfulClientDnsRoutes = clientDnsResults
.filter { it.success }
.mapTo(linkedSetOf()) { it.label }
val clientDnsAssessment = assessClientDnsPath(successfulClientDnsRoutes, systemPrimaryApiWorks)
val dnsItem = DeviceCheckItem(
title = "DNS основного VKCalls на телефоне",
status = "$primaryDnsOk из ${primaryDnsResults.size} основных узлов разрешаются",
details = primaryDnsResults.joinToString(". ") { it.display() } + ". " +
"Резервные legacy- и совместимые узлы: " +
reserveDnsResults.joinToString(". ") { it.display() } + ".",
recommendation = if (primaryDnsOk == primaryDnsResults.size) "" else
"Быстрый VKCalls может быть недоступен. Проверьте системный или Private DNS и сеть оператора; приложение также попробует legacy-резерв.",
severity = if (primaryDnsOk == primaryDnsResults.size) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning,
action = if (primaryDnsOk == primaryDnsResults.size) null else DeviceCheckAction.NetworkSettings
)
val clientDnsItem = DeviceCheckItem(
title = "DNS-путь нативного клиента",
status = clientDnsAssessment.status,
details = clientDnsResults.joinToString(". ") { it.display() } +
". Нативный клиент проверяет эти прямые DNS-пути, а при их недоступности автоматически использует системный DNS Android.",
recommendation = clientDnsAssessment.recommendation,
severity = clientDnsAssessment.severity,
action = clientDnsAssessment.action
)
val httpsItem = DeviceCheckItem(
title = "Основной VKCalls HTTPS с телефона",
status = "$primaryHttpsOk из ${primaryHttpsResults.size} основных узлов отвечают",
details = primaryHttpsResults.joinToString(". ") { it.display() } + ". " +
"Резервные legacy- и совместимые узлы: " +
reserveHttpsResults.joinToString(". ") { it.display() } +
". Любой HTTP-код означает, что DNS, TCP и TLS до узла отработали; авторизация и VK-хеш не используются.",
recommendation = if (primaryHttpsOk == primaryHttpsResults.size) "" else
"Для быстрого VKCalls сеть должна пропускать api.vk.me и calls.okcdn.ru. При их недоступности приложение попробует legacy-резерв.",
severity = if (primaryHttpsOk == primaryHttpsResults.size) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning,
action = if (primaryHttpsOk == primaryHttpsResults.size) null else DeviceCheckAction.NetworkSettings
)
val recentNetworkEvents = buildRecentNetworkEventsItem()
ClientNetworkDiagnosticsReport(
summaryLines = listOf(
"Физическая сеть диагностики: ${networkPathSummary(diagnosticNetwork)}",
"DNS основного VKCalls: $primaryDnsOk/${primaryDnsResults.size}",
"DNS клиента: ${clientDnsAssessment.status}; UDP $clientUdpOk/${clientUdp.size}, TCP $clientTcpOk/${clientTcp.size}",
"HTTPS основного VKCalls: $primaryHttpsOk/${primaryHttpsResults.size}"
),
items = buildList {
add(networkItem)
add(dnsItem)
add(clientDnsItem)
add(httpsItem)
recentNetworkEvents?.let(::add)
}
)
}
internal fun assessClientDnsPath(
successfulDirectRoutes: Set<String>,
systemPrimaryApiWorks: Boolean
): ClientDnsPathAssessment {
val selectedDirectRoute = clientDnsRouteOrder.firstOrNull(successfulDirectRoutes::contains)
return when {
selectedDirectRoute == "77.88.8.8 UDP" -> ClientDnsPathAssessment(
status = "основной UDP DNS доступен",
recommendation = "",
severity = DeviceCheckSeverity.Ok,
action = null
)
selectedDirectRoute == "77.88.8.1 UDP" -> ClientDnsPathAssessment(
status = "резервный UDP DNS доступен",
recommendation = "Основной прямой DNS ограничен, но нативный клиент автоматически выберет рабочий резервный адрес.",
severity = DeviceCheckSeverity.Info,
action = null
)
selectedDirectRoute?.endsWith(" TCP") == true -> ClientDnsPathAssessment(
status = "UDP DNS недоступен, TCP отвечает",
recommendation = "Оператор ограничивает прямой UDP DNS, но нативный клиент автоматически использует рабочий TCP-путь.",
severity = DeviceCheckSeverity.Info,
action = null
)
systemPrimaryApiWorks -> ClientDnsPathAssessment(
status = "прямой DNS недоступен, используется системный DNS",
recommendation = "Это штатный автоматический fallback: менять DNS вручную не требуется.",
severity = DeviceCheckSeverity.Info,
action = null
)
else -> ClientDnsPathAssessment(
status = "DNS до VK недоступен",
recommendation = "Не ответили ни прямые DNS-пути клиента, ни системный DNS Android. Проверьте Private DNS или повторите проверку в другой сети.",
severity = DeviceCheckSeverity.Error,
action = DeviceCheckAction.NetworkSettings
)
}
}
private fun selectDiagnosticNetwork(context: Context, connectivityManager: ConnectivityManager): DiagnosticNetwork? {
val activeNetwork = runCatching { connectivityManager.activeNetwork }.getOrNull()
val activeCapabilities = activeNetwork?.let {
runCatching { connectivityManager.getNetworkCapabilities(it) }.getOrNull()
}
val activeNetworkIsVpn = activeCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
val candidates = runCatching { connectivityManager.allNetworks.toList() }.getOrDefault(emptyList())
.mapNotNull { network ->
val capabilities = runCatching { connectivityManager.getNetworkCapabilities(network) }.getOrNull()
?: return@mapNotNull null
if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) ||
!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
) {
return@mapNotNull null
}
Triple(network, capabilities, runCatching { connectivityManager.getLinkProperties(network) }.getOrNull())
}
val selected = candidates.maxByOrNull { (network, capabilities, _) ->
var score = 0
if (network == activeNetwork) score += 100
if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) score += 50
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) score += 10
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) score += 5
score
} ?: return null
return DiagnosticNetwork(
network = selected.first,
capabilities = selected.second,
linkProperties = selected.third,
activeNetworkIsVpn = activeNetworkIsVpn,
mobileOperator = mobileOperatorSummary(context, selected.second)
)
}
private fun mobileOperatorSummary(context: Context, capabilities: NetworkCapabilities): String {
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return "не применяется"
return runCatching {
val telephonyManager = context.getSystemService(TelephonyManager::class.java)
val network = telephonyManager?.networkOperatorName.orEmpty().trim()
val sim = telephonyManager?.simOperatorName.orEmpty().trim()
val names = listOf(network, sim).filter(String::isNotBlank).distinct()
buildString {
append(names.joinToString(" / ").ifBlank { "не определён" })
append(", roaming=")
append(telephonyManager?.isNetworkRoaming ?: false)
}
}.getOrDefault("недоступен")
}
private fun buildNetworkPathItem(network: DiagnosticNetwork): DeviceCheckItem {
val capabilities = network.capabilities
val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
val details = networkPathSummary(network)
return DeviceCheckItem(
title = "Сетевой путь телефона",
status = if (validated) "физическая сеть подтверждена" else "интернет не подтверждён Android",
details = details,
recommendation = if (validated) "" else
"Проверьте ограничения оператора, captive portal или доступность интернета без VPN.",
severity = if (validated) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning,
action = if (validated) null else DeviceCheckAction.NetworkSettings
)
}
private fun networkPathSummary(network: DiagnosticNetwork): String {
val capabilities = network.capabilities
val properties = network.linkProperties
val transports = buildList {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) add("мобильная")
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) add("Wi‑Fi")
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) add("Ethernet")
}.joinToString().ifBlank { "не определена" }
val hasIpv4 = properties?.linkAddresses?.any { it.address is Inet4Address } == true
val hasIpv6 = properties?.linkAddresses?.any { it.address is Inet6Address } == true
val dnsServers = properties?.dnsServers
?.joinToString { it.hostAddress.orEmpty() }
?.ifBlank { "не указаны" }
?: "недоступны"
val privateDns = if (properties?.isPrivateDnsActive == true) {
properties.privateDnsServerName?.takeIf(String::isNotBlank)?.let { "включён ($it)" } ?: "включён"
} else {
"выключен"
}
val nat64 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
properties?.nat64Prefix?.toString() ?: "нет"
} else {
"не поддерживается Android"
}
val mtu = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
properties?.mtu?.toString() ?: "недоступно"
} else {
"не поддерживается Android"
}
return "Сеть: $transports; validated=${capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)}; " +
"metered=${!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)}; " +
"активный VPN=${network.activeNetworkIsVpn}; оператор=${network.mobileOperator}; " +
"IPv4=$hasIpv4; IPv6=$hasIpv6; NAT64=$nat64; " +
"MTU=$mtu; системные DNS: $dnsServers; Private DNS: $privateDns. " +
"Локальные IP-адреса телефона в отчёт не включаются."
}
private suspend fun probeSystemDns(network: Network): List<NetworkProbeResult> = coroutineScope {
vkDnsHosts.map { host ->
async(Dispatchers.IO) {
timedProbe(host) {
val addresses = resolveWithSystemDns(network, host)
val ipv4 = addresses.count { it is Inet4Address }
val ipv6 = addresses.count { it is Inet6Address }
if (addresses.isEmpty()) error("пустой DNS-ответ")
"OK, IPv4=$ipv4, IPv6=$ipv6"
}
}
}.awaitAll()
}
private suspend fun resolveWithSystemDns(network: Network, host: String): List<InetAddress> =
withTimeout(NETWORK_PROBE_TIMEOUT_MS) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
suspendCancellableCoroutine { continuation ->
val cancellationSignal = CancellationSignal()
continuation.invokeOnCancellation { cancellationSignal.cancel() }
DnsResolver.getInstance().query(
network,
host,
DnsResolver.FLAG_EMPTY,
directExecutor,
cancellationSignal,
object : DnsResolver.Callback<List<InetAddress>> {
override fun onAnswer(answer: List<InetAddress>, rcode: Int) {
if (!continuation.isActive) return
if (rcode == 0 && answer.isNotEmpty()) continuation.resume(answer)
else continuation.resumeWith(Result.failure(UnknownHostException("DNS rcode=$rcode")))
}
override fun onError(error: DnsResolver.DnsException) {
if (continuation.isActive) continuation.resumeWith(Result.failure(error))
}
}
)
}
} else {
runInterruptible(Dispatchers.IO) { network.getAllByName(host).toList() }
}
}
private suspend fun probeClientDns(network: Network): List<NetworkProbeResult> = coroutineScope {
clientDnsServers.flatMap { server ->
listOf(
async(Dispatchers.IO) {
timedProbe("$server UDP") { directDnsQuery(network, server, useTcp = false) }
},
async(Dispatchers.IO) {
timedProbe("$server TCP") { directDnsQuery(network, server, useTcp = true) }
}
)
}.awaitAll()
}
private fun directDnsQuery(network: Network, server: String, useTcp: Boolean): String {
val queryId = (SystemClock.elapsedRealtimeNanos() and 0xffff).toInt()
val query = buildDnsQuery(clientDnsProbeHost, queryId)
val response = if (useTcp) {
Socket().use { socket ->
network.bindSocket(socket)
socket.connect(InetSocketAddress(server, 53), SOCKET_TIMEOUT_MS)
socket.soTimeout = SOCKET_TIMEOUT_MS
DataOutputStream(socket.getOutputStream()).use { output ->
output.writeShort(query.size)
output.write(query)
output.flush()
val input = DataInputStream(socket.getInputStream())
val responseLength = input.readUnsignedShort()
require(responseLength in 12..65_535) { "некорректная длина DNS-ответа" }
ByteArray(responseLength).also(input::readFully)
}
}
} else {
DatagramSocket(null).use { socket ->
network.bindSocket(socket)
socket.soTimeout = SOCKET_TIMEOUT_MS
socket.connect(InetSocketAddress(server, 53))
socket.send(DatagramPacket(query, query.size))
val buffer = ByteArray(2_048)
val packet = DatagramPacket(buffer, buffer.size)
socket.receive(packet)
packet.data.copyOfRange(packet.offset, packet.offset + packet.length)
}
}
val status = parseDnsResponse(response, queryId)
require(status.responseCode == 0) { "DNS rcode=${status.responseCode}" }
require(status.answerCount > 0) { "DNS-ответ без записей" }
return "OK, ответов=${status.answerCount}${if (status.truncated) ", truncated" else ""}"
}
internal fun buildDnsQuery(host: String, queryId: Int): ByteArray {
val labels = host.trim('.').split('.')
require(labels.isNotEmpty() && labels.all { it.isNotBlank() && it.toByteArray(Charsets.US_ASCII).size <= 63 }) {
"некорректное DNS-имя"
}
val bytes = ArrayList<Byte>(host.length + 18)
fun addShort(value: Int) {
bytes += ((value ushr 8) and 0xff).toByte()
bytes += (value and 0xff).toByte()
}
addShort(queryId)
addShort(0x0100)
addShort(1)
addShort(0)
addShort(0)
addShort(0)
labels.forEach { label ->
val encoded = label.toByteArray(Charsets.US_ASCII)
bytes += encoded.size.toByte()
encoded.forEach { bytes += it }
}
bytes += 0.toByte()
addShort(1)
addShort(1)
return bytes.toByteArray()
}
internal fun parseDnsResponse(response: ByteArray, expectedId: Int): DnsResponseStatus {
require(response.size >= 12) { "короткий DNS-ответ" }
fun unsignedShort(offset: Int): Int =
((response[offset].toInt() and 0xff) shl 8) or (response[offset + 1].toInt() and 0xff)
require(unsignedShort(0) == (expectedId and 0xffff)) { "чужой DNS-ответ" }
val flags = unsignedShort(2)
require(flags and 0x8000 != 0) { "DNS-пакет не является ответом" }
return DnsResponseStatus(
responseCode = flags and 0x000f,
answerCount = unsignedShort(6),
truncated = flags and 0x0200 != 0
)
}
private suspend fun probeVkHttps(network: Network): List<NetworkProbeResult> = coroutineScope {
vkHttpsTargets.map { (label, url) ->
async(Dispatchers.IO) {
timedProbe(label) { httpsProbe(network, url) }
}
}.awaitAll()
}
private fun httpsProbe(network: Network, target: String): String {
val connection = network.openConnection(URL(target)) as HttpsURLConnection
return try {
connection.connectTimeout = SOCKET_TIMEOUT_MS
connection.readTimeout = SOCKET_TIMEOUT_MS
connection.instanceFollowRedirects = false
connection.requestMethod = "GET"
connection.setRequestProperty("User-Agent", "WDTT-Plus-Diagnostics/${BuildConfig.VERSION_NAME}")
connection.setRequestProperty("Range", "bytes=0-0")
val responseCode = connection.responseCode
require(responseCode in 100..599) { "нет HTTP-ответа" }
"HTTP $responseCode"
} finally {
connection.disconnect()
}
}
private suspend inline fun timedProbe(label: String, crossinline block: suspend () -> String): NetworkProbeResult {
val started = SystemClock.elapsedRealtime()
return try {
val result = block()
NetworkProbeResult(label, true, result, SystemClock.elapsedRealtime() - started)
} catch (error: CancellationException) {
if (error !is TimeoutCancellationException) throw error
NetworkProbeResult(label, false, "тайм-аут", SystemClock.elapsedRealtime() - started)
} catch (_: SocketTimeoutException) {
NetworkProbeResult(label, false, "тайм-аут", SystemClock.elapsedRealtime() - started)
} catch (_: UnknownHostException) {
NetworkProbeResult(label, false, "DNS не разрешён", SystemClock.elapsedRealtime() - started)
} catch (error: Throwable) {
val reason = error.message
?.replace(Regex("[\\r\\n]+"), " ")
?.take(120)
?.takeIf(String::isNotBlank)
?: error.javaClass.simpleName
NetworkProbeResult(label, false, reason, SystemClock.elapsedRealtime() - started)
}
}
private fun buildRecentNetworkEventsItem(): DeviceCheckItem? {
val entries = TunnelManager.logs.value
.filter { entry ->
entry.severity != LogSeverity.Info ||
entry.key.startsWith("err_") ||
entry.key.startsWith("vkcalls_") ||
entry.key.startsWith("vk_provider_") ||
entry.key.startsWith("vk_credentials_") ||
entry.key.startsWith("vk_legacy_") ||
entry.key.startsWith("turn_") ||
entry.key.startsWith("worker_turn_")
}
.take(12)
if (entries.isEmpty()) return null
val details = entries.joinToString(" | ") { entry ->
val message = entry.message
.replace(Regex("(https?://[^?\\s]+)\\?[^\\s]+"), "\$1?<параметры скрыты>")
.replace(Regex("(?i)(token|password|credential|secret)=([^&\\s]+)"), "\$1=<скрыто>")
.take(220)
"${entry.key}: $message${if (entry.count > 1) " ×${entry.count}" else ""}"
}
return DeviceCheckItem(
title = "Последние сетевые события туннеля",
status = "собрано ${entries.size}",
details = details,
severity = DeviceCheckSeverity.Info
)
}
@@ -90,13 +90,11 @@ object ClientTransferCodec {
val clean = value.trim()
if (clean.isBlank()) return ""
require(clean.length <= 4096 && clean.none(Char::isISOControl)) { "Поле VK-хешей повреждено." }
val hashes = clean.split(Regex("[,\\s]+"))
.map { VkJoinLink.extractHash(it) }
.filter { it.isNotBlank() }
require(hashes.isNotEmpty() && hashes.all { it.length >= 16 } && hashes.none { it.contains('/') || it.contains('\\') }) {
val hashes = VkJoinLink.normalizeHashes(clean)
require(hashes != null) {
"VK-хеши в переносе имеют неверный формат."
}
return hashes.distinct().joinToString(",")
return hashes
}
}
@@ -17,6 +17,7 @@ object DeployManager {
val deployProgress = MutableStateFlow(0f)
val currentStep = MutableStateFlow("")
val lastResult = MutableStateFlow("") // "success", "error: ...", ""
val installedServerVersion = MutableStateFlow("")
@Volatile
var activeSession: com.jcraft.jsch.Session? = null
@@ -59,6 +60,7 @@ object DeployManager {
deployProgress.value = 0f
currentStep.value = "Инициализация..."
lastResult.value = ""
installedServerVersion.value = ""
}
fun stopDeploy(result: String = "") {
@@ -340,8 +340,8 @@ object DeviceCompatibility {
DeviceCheckItem(
title = "WebView",
status = "не найден",
details = "Автоматическая и ручная captcha через WebView могут не работать.",
recommendation = "Проверьте системный Android System WebView или браузер-провайдер WebView.",
details = "Быстрый VKCalls может работать без WebView, но автоматическая и ручная капча резервного способа будут недоступны.",
recommendation = "Обновите или включите Android System WebView либо браузер-провайдер WebView, чтобы резервное подключение могло пройти капчу.",
severity = DeviceCheckSeverity.Warning,
firstLaunchRelevant = false,
action = DeviceCheckAction.WebViewSettings
@@ -350,7 +350,7 @@ object DeviceCompatibility {
DeviceCheckItem(
title = "WebView",
status = webView.packageName,
details = "Версия: ${webView.versionName}. WebView доступен для captcha-сценариев.",
details = "Версия: ${webView.versionName}. WebView доступен для капчи резервного способа.",
severity = DeviceCheckSeverity.Ok,
firstLaunchRelevant = false
)
@@ -395,7 +395,7 @@ object DeviceCompatibility {
return DeviceCheckItem(
title = "Сеть Android",
status = "активная сеть не найдена",
details = "Приложение запустится, но для VKCalls, TURN и обновлений нужна сеть.",
details = "Приложение запустится, но для быстрого VKCalls, TURN и обновлений нужна сеть.",
recommendation = "Подключитесь к Wi‑Fi или мобильной сети.",
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.NetworkSettings
@@ -422,7 +422,7 @@ object DeviceCompatibility {
DeviceCheckItem(
title = "Сеть Android",
status = "$transports, интернет подтверждён",
details = "Активная сеть выглядит пригодной для проверки VK/TURN.",
details = "Android подтвердил общий доступ в интернет. Системный DNS, DNS-путь нативного клиента и служебные узлы VK/OK проверяются отдельными пунктами ниже.",
severity = DeviceCheckSeverity.Ok
)
}
@@ -0,0 +1,29 @@
package com.wdtt.plus
internal object DeviceIdentity {
private val validPattern = Regex("^[A-Za-z0-9_.:-]{8,128}$")
private val knownInvalidAndroidIds = setOf(
"9774d56d682e549c",
"unknown",
)
fun valid(value: String): Boolean =
value.trim().matches(validPattern) &&
value.trim().lowercase() !in knownInvalidAndroidIds
fun resolve(
existing: String?,
platformId: String?,
generatedId: String,
): String {
val stored = existing.orEmpty().trim()
if (valid(stored)) return stored
val platform = platformId.orEmpty().trim()
if (valid(platform)) return platform
val generated = generatedId.trim()
require(valid(generated)) { "Некорректный резервный идентификатор устройства." }
return generated
}
}
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,6 @@
package com.wdtt.plus
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Intent
import android.graphics.drawable.Icon
@@ -33,9 +34,19 @@ class QuickToggleTileService : TileService() {
TunnelManager.running,
TrustedWifiManager.state,
settingsStore.activeProfile,
settingsStore.profileNames
) { running, trustedWifi, activeProfile, profileNames ->
TileUiState(running, trustedWifi, activeProfile, profileNames)
TunnelManager.activeTunnelProfile,
settingsStore.profileNames,
) { running, trustedWifi, selectedProfile, activeTunnelProfile, profileNames ->
TileUiState(
running,
trustedWifi,
selectedProfile,
activeTunnelProfile,
profileNames,
AccessLifecycleUiState.Unmanaged,
)
}.combine(settingsStore.activeAccessLifecycle) { state, accessLifecycle ->
state.copy(accessLifecycle = accessLifecycle)
}.collect { uiState ->
updateTile(uiState)
}
@@ -53,27 +64,36 @@ class QuickToggleTileService : TileService() {
override fun onClick() {
super.onClick()
runCatching {
if (TunnelManager.running.value || TrustedWifiManager.state.value.waiting) {
// Если запущен — останавливаем. Состояние плитки изменится автоматически,
// когда TunnelManager остановит процессы и обновит статус running в false.
val stopIntent = Intent(this, TunnelService::class.java).apply { action = "STOP" }
startService(stopIntent)
return
when (
tunnelToggleAction(
running = TunnelManager.running.value,
trustedWifiWaiting = TrustedWifiManager.state.value.waiting,
vpnPermissionRequired = VpnService.prepare(this) != null,
)
) {
TunnelToggleAction.STOP -> {
// Состояние плитки изменится после фактической остановки службы.
startService(
Intent(this, TunnelService::class.java).apply { action = "STOP" }
)
}
// Проверяем наличие выданного разрешения VPN перед стартом
if (VpnService.prepare(this) != null) {
Toast.makeText(this, "Откройте WDTT Plus и выдайте VPN-разрешение", Toast.LENGTH_LONG).show()
TunnelToggleAction.REQUEST_VPN_PERMISSION -> {
Toast.makeText(
this,
"Откройте WDTT Plus и выдайте VPN-разрешение",
Toast.LENGTH_LONG
).show()
openMainActivity()
return
}
// Запускаем старт туннеля в фоне
scope.launch {
TunnelToggleAction.START -> scope.launch {
try {
val intent = buildTunnelStartIntentFromSettings(this@QuickToggleTileService)
if (intent == null) {
Toast.makeText(this@QuickToggleTileService, "Заполните настройки подключения в WDTT Plus", Toast.LENGTH_LONG).show()
Toast.makeText(
this@QuickToggleTileService,
"Заполните настройки подключения в WDTT Plus",
Toast.LENGTH_LONG
).show()
openMainActivity()
return@launch
}
@@ -85,7 +105,12 @@ class QuickToggleTileService : TileService() {
}
} catch (e: Exception) {
Log.e("QuickToggleTile", "Failed to start tunnel via QS tile", e)
Toast.makeText(this@QuickToggleTileService, "Ошибка запуска: ${e.localizedMessage}", Toast.LENGTH_SHORT).show()
Toast.makeText(
this@QuickToggleTileService,
"Ошибка запуска: ${e.localizedMessage}",
Toast.LENGTH_SHORT
).show()
}
}
}
}.onFailure { e ->
@@ -102,12 +127,21 @@ class QuickToggleTileService : TileService() {
runCatching {
val running = uiState.running
val waiting = uiState.trustedWifi.waiting
val activeProfile = uiState.activeProfile
val profileNames = uiState.profileNames
val profile = activeProfile.coerceIn(0, 2)
val profile = displayedTunnelProfile(
selectedProfile = uiState.selectedProfile,
activeTunnelProfile = uiState.activeTunnelProfile,
running = running,
trustedWifiWaiting = waiting,
)
val profileLabel = vpnProfileDisplayName(profile, profileNames)
val defaultProfileLabel = vpnProfileDefaultName(profile)
val profileIsDefault = profileLabel == defaultProfileLabel
val accessBlocked =
uiState.accessLifecycle.managed &&
!uiState.accessLifecycle.allowConnect &&
!running &&
!waiting
qsTile?.apply {
label = when {
waiting -> "Ожидание"
@@ -121,6 +155,8 @@ class QuickToggleTileService : TileService() {
subtitle = when {
waiting -> uiState.trustedWifi.ssid.ifBlank { "Wi-Fi" }
running -> ""
accessBlocked -> uiState.accessLifecycle.title
.ifBlank { uiState.accessLifecycle.fallbackTitle() }
else -> "Отключено"
}
}
@@ -134,10 +170,13 @@ class QuickToggleTileService : TileService() {
private data class TileUiState(
val running: Boolean,
val trustedWifi: TrustedWifiRuntimeState,
val activeProfile: Int,
val profileNames: List<String>
val selectedProfile: Int,
val activeTunnelProfile: Int?,
val profileNames: List<String>,
val accessLifecycle: AccessLifecycleUiState,
)
@SuppressLint("StartActivityAndCollapseDeprecated")
private fun openMainActivity() {
runCatching {
val intent = Intent(this, MainActivity::class.java).apply {
@@ -0,0 +1,407 @@
package com.wdtt.plus
import android.content.Context
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.util.UUID
/**
* Provider-neutral UI action prepared by a remote service.
*
* The application does not interpret the destination or reconstruct either
* URL. It only validates the generic HTTPS boundary and opens the exact
* backend-provided target.
*/
data class RemoteUiAction(
val title: String,
val message: String,
val label: String,
val target: RemoteLaunchTarget,
val confirmationTitle: String = "",
val confirmationMessage: String = "",
val confirmationLabel: String = "",
val progressLabel: String = "",
val preparingMessage: String = "",
val stoppingMessage: String = "",
val openingMessage: String = "",
val successMessage: String = "",
val cancelledMessage: String = "",
val failureMessage: String = "",
val compactMessage: String = "",
val compactLabel: String = "",
val compactLinkText: String = "",
val compactButtonVisible: Boolean = true,
val cancelLabel: String = "",
val form: RemoteActionForm? = null,
)
data class RemoteActionFormChoice(
val label: String,
val value: String,
)
data class RemoteActionForm(
val token: String,
val submitUrl: String,
val title: String,
val message: String,
val choices: List<RemoteActionFormChoice>,
val inputLabel: String,
val inputSuffix: String,
val initialValue: String,
val minimum: Long,
val maximum: Long,
val maxCharacters: Int,
val supportingText: String,
val invalidText: String,
val submitLabel: String,
val busyLabel: String,
val failureMessage: String,
val fallbackLabel: String,
)
class RemoteActionExecutionException(message: String) : IllegalStateException(message)
data class RemoteActionCatalog(
val actions: Map<String, RemoteUiAction> = emptyMap(),
) {
fun at(placement: String): RemoteUiAction? = actions[placement]
companion object {
val Empty = RemoteActionCatalog()
}
}
object RemoteActionCatalogGateway {
private const val CACHE_TTL_MS = 10 * 60 * 1000L
private const val MAX_RESPONSE_CHARS = 32 * 1024
private val placements = setOf("tunnel", "profile", "about")
@Volatile
private var cachedAt = 0L
@Volatile
private var cachedCatalog = RemoteActionCatalog.Empty
fun hasFreshCache(): Boolean =
System.currentTimeMillis() - cachedAt in 0 until CACHE_TTL_MS
fun cached(): RemoteActionCatalog =
if (hasFreshCache()) cachedCatalog else RemoteActionCatalog.Empty
suspend fun fetch(force: Boolean = false): RemoteActionCatalog {
val now = System.currentTimeMillis()
if (!force && now - cachedAt in 0 until CACHE_TTL_MS) return cachedCatalog
return withContext(Dispatchers.IO) {
val current = System.currentTimeMillis()
if (!force && current - cachedAt in 0 until CACHE_TTL_MS) {
return@withContext cachedCatalog
}
val received = runCatching { request() }.getOrDefault(RemoteActionCatalog.Empty)
cachedCatalog = received
cachedAt = current
received
}
}
suspend fun fetchQuestionAction(): RemoteUiAction? =
withContext(Dispatchers.IO) {
runCatching { request(context = "question").at("about") }.getOrNull()
}
suspend fun execute(
form: RemoteActionForm,
requestId: String,
value: String,
): RemoteLaunchTarget = withContext(Dispatchers.IO) {
require(validOpaqueToken(form.token)) { "Действие устарело. Обновите экран." }
require(safeExternalUrl(form.submitUrl)) { "Получен небезопасный адрес действия." }
require(runCatching { UUID.fromString(requestId) }.isSuccess) {
"Не удалось подготовить действие."
}
require(value.length in 1..32) { form.invalidText }
var connection: HttpURLConnection? = null
try {
connection = URL(form.submitUrl).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.instanceFollowRedirects = false
connection.connectTimeout = 7_000
connection.readTimeout = 12_000
connection.doOutput = true
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
val payload = JSONObject()
.put("token", form.token)
.put("request_id", requestId)
.put("value", value)
.put("client", BuildConfig.VERSION_NAME)
.put("system", android.os.Build.VERSION.RELEASE.orEmpty())
.toString()
.toByteArray(Charsets.UTF_8)
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val stream = if (status in 200..299) {
connection.inputStream
} else {
connection.errorStream
}
val body = stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty()
if (status !in 200..299) {
val detail = runCatching {
JSONObject(body).optString("detail").trim().take(240)
}.getOrDefault("")
throw RemoteActionExecutionException(
detail.ifBlank { form.failureMessage }
)
}
parseExecutionTarget(body)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: RemoteActionExecutionException) {
throw error
} catch (error: Exception) {
throw RemoteActionExecutionException(form.failureMessage)
} finally {
connection?.disconnect()
}
}
private fun request(context: String? = null): RemoteActionCatalog {
var connection: HttpURLConnection? = null
return try {
val query = buildList {
if (BuildConfig.REMOTE_ACTION_PREVIEW) add("preview=1")
if (context == "question") add("context=question")
}.joinToString("&").let { if (it.isBlank()) "" else "?$it" }
connection = URL(
"https://${BuildConfig.WDTT_PLUS_DOMAIN}/api/client/actions$query"
).openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.instanceFollowRedirects = false
connection.connectTimeout = 5_000
connection.readTimeout = 6_000
connection.setRequestProperty("Accept", "application/json")
val status = connection.responseCode
if (status !in 200..299) return RemoteActionCatalog.Empty
parse(connection.inputStream.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) })
} finally {
connection?.disconnect()
}
}
internal fun parse(body: String): RemoteActionCatalog {
if (body.length > MAX_RESPONSE_CHARS) return RemoteActionCatalog.Empty
val root = runCatching { JSONObject(body) }.getOrNull()
?: return RemoteActionCatalog.Empty
if (root.optInt("version", 0) != 1) return RemoteActionCatalog.Empty
val source = root.optJSONObject("actions") ?: return RemoteActionCatalog.Empty
val actions = placements.mapNotNull { placement ->
val item = source.optJSONObject(placement) ?: return@mapNotNull null
parseAction(item)?.let { placement to it }
}.toMap()
return RemoteActionCatalog(actions)
}
private fun parseAction(item: JSONObject): RemoteUiAction? {
val title = item.optString("title").trim().take(120)
val message = item.optString("message").trim().take(400)
val label = item.optString("label").trim().take(80)
val confirmationTitle = item.optString("confirmation_title").trim().take(120)
val confirmationMessage = item.optString("confirmation_message").trim().take(1600)
val confirmationLabel = item.optString("confirmation_label").trim().take(80)
val progressLabel = item.optString("progress_label").trim().take(80)
val preparingMessage = item.optString("preparing_message").trim().take(240)
val stoppingMessage = item.optString("stopping_message").trim().take(240)
val openingMessage = item.optString("opening_message").trim().take(240)
val successMessage = item.optString("success_message").trim().take(400)
val cancelledMessage = item.optString("cancelled_message").trim().take(240)
val failureMessage = item.optString("failure_message").trim().take(240)
val compactMessage = item.optString("compact_message").trim().take(400)
val compactLabel = item.optString("compact_label").trim().take(80)
val compactLinkText = item.optString("compact_link_text").trim().take(120)
val compactButtonVisible = item.optBoolean("compact_button_visible", true)
val cancelLabel = item.optString("cancel_label").trim().take(80)
val primary = item.optString("url").trim()
val fallback = item.optString("fallback").trim()
val handler = item.optString("handler").trim()
val alternateHandlers = parseAlternateHandlers(item) ?: return null
val formSource = item.optJSONObject("form")
val form = formSource?.let(::parseForm)
if (title.isBlank() || message.isBlank() || label.isBlank()) return null
if (!safeExternalUrl(primary)) return null
if (fallback.isNotBlank() && !safeExternalUrl(fallback)) return null
if (handler.isNotBlank() && !safePackageName(handler)) return null
if (formSource != null && form == null) return null
return RemoteUiAction(
title = title,
message = message,
label = label,
confirmationTitle = confirmationTitle,
confirmationMessage = confirmationMessage,
confirmationLabel = confirmationLabel,
progressLabel = progressLabel,
preparingMessage = preparingMessage,
stoppingMessage = stoppingMessage,
openingMessage = openingMessage,
successMessage = successMessage,
cancelledMessage = cancelledMessage,
failureMessage = failureMessage,
compactMessage = compactMessage,
compactLabel = compactLabel,
compactLinkText = compactLinkText,
compactButtonVisible = compactButtonVisible,
cancelLabel = cancelLabel,
form = form,
target = RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternateHandlers,
),
)
}
private fun parseForm(item: JSONObject): RemoteActionForm? {
val token = item.optString("token").trim()
val submitUrl = item.optString("submit_url").trim()
val title = item.optString("title").trim().take(120)
val message = item.optString("message").trim().take(600)
val inputLabel = item.optString("input_label").trim().take(80)
val inputSuffix = item.optString("input_suffix").trim().take(16)
val initialValue = item.optString("initial_value").trim().take(32)
val minimum = item.optLong("minimum", Long.MIN_VALUE)
val maximum = item.optLong("maximum", Long.MIN_VALUE)
val maxCharacters = item.optInt("max_characters", 0)
val supportingText = item.optString("supporting_text").trim().take(160)
val invalidText = item.optString("invalid_text").trim().take(160)
val submitLabel = item.optString("submit_label").trim().take(120)
val busyLabel = item.optString("busy_label").trim().take(80)
val failureMessage = item.optString("failure_message").trim().take(240)
val fallbackLabel = item.optString("fallback_label").trim().take(80)
val choicesSource = item.optJSONArray("choices") ?: return null
if (
!validOpaqueToken(token) ||
!safeExternalUrl(submitUrl) ||
title.isBlank() ||
message.isBlank() ||
inputLabel.isBlank() ||
initialValue.isBlank() ||
minimum < 0 ||
maximum < minimum ||
maximum > 1_000_000_000L ||
maxCharacters !in 1..12 ||
supportingText.isBlank() ||
invalidText.isBlank() ||
submitLabel.isBlank() ||
busyLabel.isBlank() ||
failureMessage.isBlank() ||
fallbackLabel.isBlank() ||
choicesSource.length() !in 1..8
) {
return null
}
val initialNumber = initialValue.toLongOrNull() ?: return null
if (initialNumber !in minimum..maximum) return null
val choices = (0 until choicesSource.length()).mapNotNull { index ->
val choice = choicesSource.optJSONObject(index) ?: return@mapNotNull null
val choiceLabel = choice.optString("label").trim().take(40)
val choiceValue = choice.optString("value").trim()
if (choiceLabel.isBlank() || choiceValue.length !in 1..256) {
null
} else {
RemoteActionFormChoice(choiceLabel, choiceValue)
}
}
if (choices.size != choicesSource.length()) return null
return RemoteActionForm(
token = token,
submitUrl = submitUrl,
title = title,
message = message,
choices = choices,
inputLabel = inputLabel,
inputSuffix = inputSuffix,
initialValue = initialValue,
minimum = minimum,
maximum = maximum,
maxCharacters = maxCharacters,
supportingText = supportingText,
invalidText = invalidText,
submitLabel = submitLabel,
busyLabel = busyLabel,
failureMessage = failureMessage,
fallbackLabel = fallbackLabel,
)
}
internal fun parseExecutionTarget(body: String): RemoteLaunchTarget {
if (body.length > MAX_RESPONSE_CHARS) {
throw RemoteActionExecutionException("Получен слишком большой ответ.")
}
val root = runCatching { JSONObject(body) }.getOrNull()
?: throw RemoteActionExecutionException("Получен некорректный ответ.")
if (root.optInt("version", 0) != 1) {
throw RemoteActionExecutionException("Версия ответа не поддерживается.")
}
val primary = root.optString("url").trim()
val fallback = root.optString("fallback").trim()
val handler = root.optString("handler").trim()
val alternateHandlers = parseAlternateHandlers(root)
?: throw RemoteActionExecutionException("Получены небезопасные обработчики действия.")
if (
!safeExternalUrl(primary) ||
(fallback.isNotBlank() && !safeExternalUrl(fallback)) ||
(handler.isNotBlank() && !safePackageName(handler))
) {
throw RemoteActionExecutionException("Получен небезопасный адрес действия.")
}
return RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternateHandlers,
)
}
private fun validOpaqueToken(value: String): Boolean =
value.length in 24..256 && Regex("^[A-Za-z0-9._-]+$").matches(value)
private fun safeExternalUrl(value: String): Boolean {
if (value.length !in 1..2048) return false
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safePackageName(value: String): Boolean =
value.length in 3..255 &&
Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value)
private fun parseAlternateHandlers(item: JSONObject): List<String>? {
val handlers = item.optJSONArray("alternate_handlers") ?: return emptyList()
if (handlers.length() > 7) return null
return (0 until handlers.length())
.map { index -> handlers.optString(index).trim() }
.takeIf { values ->
values.all { it.isNotBlank() && safePackageName(it) } &&
values.distinct().size == values.size
}
}
}
object RemoteUiActionLauncher {
suspend fun open(context: Context, action: RemoteUiAction): Boolean =
withContext(Dispatchers.Main.immediate) {
runCatching {
RemoteContinuationLauncher.launch(context, action.target)
true
}.getOrDefault(false)
}
}
@@ -0,0 +1,276 @@
package com.wdtt.plus
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.browser.auth.AuthTabIntent
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.net.URLDecoder
data class RemoteLaunchTarget(
val primaryUrl: String,
val fallbackUrl: String = "",
val preferredHandler: String = "",
val alternateHandlers: List<String> = emptyList(),
val returnScheme: String = "",
) {
internal fun handlerPackages(): List<String> =
(listOf(preferredHandler) + alternateHandlers)
.filter(String::isNotBlank)
.distinct()
}
object RemoteContinuationLauncher {
suspend fun begin(capability: RemoteContinuation, device: String): RemoteLaunchTarget {
require(capability.available && opaqueValue(capability.key)) {
"Автоматическое заполнение недоступно для этого профиля."
}
require(safeServiceUrl(capability.url)) { "Автоматическое заполнение сейчас недоступно." }
require(validDevice(device)) { "Не удалось определить текущее устройство." }
return withContext(Dispatchers.IO) {
val payload = JSONObject()
.put("key", capability.key.trim())
.put("device", device.trim())
.put("return_transport", "auth_tab")
.toString()
.toByteArray(Charsets.UTF_8)
var connection: HttpURLConnection? = null
try {
connection = URL(capability.url).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.connectTimeout = 10_000
connection.readTimeout = 15_000
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val body = readBody(connection, status)
if (status !in 200..299) {
val detail = runCatching { JSONObject(body).optString("detail") }.getOrDefault("")
throw IllegalStateException(
detail.ifBlank { "Не удалось продолжить действие. Откройте свежую ссылку подключения." }
)
}
val response = runCatching { JSONObject(body) }
.getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") }
val primary = response.optString("url").trim()
val fallback = response.optString("fallback").trim()
val handler = response.optString("handler").trim()
val alternateHandlers = parseAlternateHandlers(response)
val returnScheme = response.optString("return_scheme").trim()
require(safeExternalUrl(primary)) {
"WDTT Plus вернул повреждённый адрес продолжения."
}
require(fallback.isBlank() || safeExternalUrl(fallback)) {
"WDTT Plus вернул повреждённый резервный адрес."
}
require(handler.isBlank() || safePackageName(handler)) {
"WDTT Plus вернул повреждённый обработчик продолжения."
}
require(alternateHandlers != null) {
"WDTT Plus вернул повреждённые резервные обработчики."
}
require(returnScheme.isBlank() || returnScheme == AUTH_TAB_RETURN_SCHEME) {
"WDTT Plus вернул повреждённый способ возврата."
}
RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternateHandlers,
returnScheme = returnScheme,
)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
if (error is IllegalStateException) throw error
throw IllegalStateException(
"Не удалось связаться с WDTT Plus. Проверьте интернет и повторите попытку."
)
} finally {
connection?.disconnect()
}
}
}
fun launch(
context: Context,
target: RemoteLaunchTarget,
authTabLauncher: ActivityResultLauncher<Intent>? = null,
) {
require(safeExternalUrl(target.primaryUrl)) { "Адрес продолжения повреждён." }
val handlerPackages = target.handlerPackages()
require(handlerPackages.size <= MAX_HANDLER_PACKAGES) {
"Получено слишком много обработчиков продолжения."
}
handlerPackages.forEach { handler ->
require(safePackageName(handler)) { "Обработчик продолжения повреждён." }
try {
context.startActivity(
Intent(Intent.ACTION_VIEW, Uri.parse(target.primaryUrl)).apply {
addCategory(Intent.CATEGORY_BROWSABLE)
setPackage(handler)
}
)
return
} catch (_: ActivityNotFoundException) {
// The fallback preserves the remote operation when its preferred app is unavailable.
} catch (_: SecurityException) {
// Some Android builds reject explicit package launches; use the browser below.
}
}
if (target.returnScheme == AUTH_TAB_RETURN_SCHEME && authTabLauncher != null) {
AuthTabIntent.Builder()
.build()
.launch(
authTabLauncher,
Uri.parse(authTabLaunchUrl(target)),
AUTH_TAB_RETURN_SCHEME,
)
return
}
var lastFailure: Exception? = null
for (browserUrl in browserLaunchUrls(target)) {
try {
context.startActivity(
Intent(Intent.ACTION_VIEW, Uri.parse(browserUrl)).apply {
addCategory(Intent.CATEGORY_BROWSABLE)
}
)
return
} catch (error: ActivityNotFoundException) {
lastFailure = error
} catch (error: SecurityException) {
lastFailure = error
}
}
throw IllegalStateException(
"Не удалось открыть VK или страницу продолжения. Проверьте приложение VK и браузер.",
lastFailure,
)
}
internal fun authTabLaunchUrl(target: RemoteLaunchTarget): String =
browserLaunchUrls(target).first()
internal fun browserLaunchUrls(target: RemoteLaunchTarget): List<String> =
(
if (target.handlerPackages().isNotEmpty() && target.fallbackUrl.isNotBlank()) {
listOf(target.fallbackUrl, target.primaryUrl)
} else {
listOf(target.primaryUrl, target.fallbackUrl)
}
)
.filter { it.isNotBlank() }
.onEach {
require(safeExternalUrl(it)) { "Резервный адрес продолжения повреждён." }
}
.distinct()
internal fun callbackDocumentUri(callback: Uri?): Uri? {
val document = callbackDocumentUrl(callback?.toString().orEmpty()) ?: return null
return Uri.parse(document)
}
internal fun isCancellationCallback(callback: Uri?): Boolean =
isCancellationCallback(callback?.toString().orEmpty())
internal fun isCancellationCallback(rawCallback: String): Boolean {
val uri = runCatching { URI(rawCallback.trim()) }.getOrNull() ?: return false
return uri.scheme.equals(AUTH_TAB_RETURN_SCHEME, ignoreCase = true) &&
uri.host.equals("return", ignoreCase = true) &&
uri.port == -1 &&
uri.rawUserInfo.isNullOrBlank() &&
uri.path.orEmpty().isBlank() &&
uri.rawQuery.isNullOrBlank() &&
uri.rawFragment.isNullOrBlank()
}
internal fun callbackDocumentUrl(rawCallback: String): String? {
val callback = runCatching { URI(rawCallback.trim()) }.getOrNull() ?: return null
if (
!callback.scheme.equals(AUTH_TAB_RETURN_SCHEME, ignoreCase = true) ||
!callback.host.equals("return", ignoreCase = true) ||
callback.port != -1 ||
!callback.rawUserInfo.isNullOrBlank() ||
!callback.rawFragment.isNullOrBlank() ||
callback.path.orEmpty().isNotBlank()
) {
return null
}
val documents = callback.rawQuery.orEmpty()
.split('&')
.mapNotNull { item ->
val separator = item.indexOf('=')
if (separator <= 0) return@mapNotNull null
val key = URLDecoder.decode(
item.substring(0, separator),
Charsets.UTF_8.name(),
)
if (key != "document") return@mapNotNull null
URLDecoder.decode(
item.substring(separator + 1),
Charsets.UTF_8.name(),
)
}
val document = documents.singleOrNull()?.trim().orEmpty()
return RemoteDocumentGateway.extractLink(document)?.url
}
private fun safeServiceUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) &&
uri.rawUserInfo.isNullOrBlank() &&
uri.rawQuery.isNullOrBlank() &&
uri.rawFragment.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safeExternalUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safePackageName(value: String): Boolean =
value.length in 3..255 &&
Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value)
private fun parseAlternateHandlers(source: JSONObject): List<String>? {
val handlers = source.optJSONArray("alternate_handlers") ?: return emptyList()
if (handlers.length() > MAX_HANDLER_PACKAGES - 1) return null
return (0 until handlers.length())
.map { index -> handlers.optString(index).trim() }
.takeIf { values ->
values.all { it.isNotBlank() && safePackageName(it) } &&
values.distinct().size == values.size
}
}
private fun opaqueValue(value: String): Boolean =
value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value)
private fun validDevice(value: String): Boolean =
Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim())
private fun readBody(connection: HttpURLConnection, status: Int): String {
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_BYTES) }.orEmpty()
}
private const val AUTH_TAB_RETURN_SCHEME = "wdtt"
private const val MAX_HANDLER_PACKAGES = 8
private const val MAX_RESPONSE_BYTES = 32 * 1024
}
@@ -0,0 +1,388 @@
package com.wdtt.plus
import android.net.Uri
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.util.TimeZone
data class RemoteDocumentLink(val url: String)
data class RemoteDocumentFailureAction(
val label: String,
val target: RemoteLaunchTarget,
)
class RemoteDocumentFailure(
message: String,
val action: RemoteDocumentFailureAction? = null,
) : IllegalStateException(message)
data class RemoteContinuation(
val available: Boolean,
val key: String = "",
val url: String = "",
val expiresAt: Long = 0,
val message: String = ""
)
enum class RemoteDocumentKind {
BASE,
UPDATE
}
data class RemoteDocumentDelivery(
val document: String,
val binding: String,
val continuation: RemoteContinuation,
val access: RemoteAccessCapability,
val kind: RemoteDocumentKind,
val profileMaxWorkers: Int = 0,
val profileRevision: Long = 0,
)
internal fun RemoteDocumentDelivery.shouldPreserveLocalVkHashes(
existingProfileRedelivery: Boolean = false,
): Boolean {
val deliveredHashes = WdttDeepLink.parse(document, allowMissingHashes = true)
?.hashes
.orEmpty()
return deliveredHashes.isBlank() &&
(
kind == RemoteDocumentKind.UPDATE ||
(kind == RemoteDocumentKind.BASE && existingProfileRedelivery)
)
}
internal fun RemoteDocumentDelivery.requiresInitialContinuationWarning(
existingProfileHasVkHashes: Boolean = false,
): Boolean =
kind == RemoteDocumentKind.BASE &&
!continuation.available &&
!existingProfileHasVkHashes
object RemoteDocumentGateway {
private const val MAX_RESPONSE_CHARS = 32 * 1024
fun extractLink(uri: Uri): RemoteDocumentLink? = extractLink(uri.toString())
fun extractLink(rawUri: String): RemoteDocumentLink? {
val uri = runCatching { URI(rawUri.trim()) }.getOrNull() ?: return null
val path = uri.path.orEmpty()
val code = path.takeIf { it.startsWith("/c/") }
?.removePrefix("/c/")
?.trim()
.orEmpty()
val navigationMarkerValid = uri.rawQuery.isNullOrBlank() ||
Regex("^open=[0-9]{1,20}$").matches(uri.rawQuery)
val valid = trustedServiceUri(uri) &&
navigationMarkerValid &&
uri.rawFragment.isNullOrBlank() &&
Regex("^[A-Za-z0-9_-]{6,64}$").matches(code)
if (!valid) return null
return RemoteDocumentLink("https://${BuildConfig.WDTT_PLUS_DOMAIN}/c/$code")
}
suspend fun receive(
link: RemoteDocumentLink,
device: String,
label: String,
client: String,
system: String,
localBindings: Collection<String>? = null,
): RemoteDocumentDelivery {
require(extractLink(link.url) != null) { "Ссылка повреждена или неполна." }
require(validDevice(device)) { "Не удалось определить текущее устройство." }
return withContext(Dispatchers.IO) {
val request = JSONObject()
.put("device", device.trim())
.put("label", label.trim().take(160))
.put("client", client.trim().take(64))
.put("system", system.trim().take(64))
.put("timezone", TimeZone.getDefault().id.take(64))
if (localBindings != null) {
val bindings = localBindings
.map(String::trim)
.filter(::opaqueValue)
.distinct()
.take(6)
request.put("bindings", JSONArray(bindings))
}
val payload = request
.toString()
.toByteArray(Charsets.UTF_8)
var connection: HttpURLConnection? = null
try {
connection = URL(link.url).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.connectTimeout = 10_000
connection.readTimeout = 12_000
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val body = readBody(connection, status)
if (status !in 200..299) {
val failure = parseFailure(body)
throw RemoteDocumentFailure(
failure.first.ifBlank {
"Ссылка недоступна. Получите новую ссылку подключения."
},
failure.second,
)
}
parse(body)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
if (error is IllegalStateException) throw error
throw IllegalStateException(
"Не удалось связаться с WDTT Plus. Проверьте интернет и попробуйте ещё раз."
)
} finally {
connection?.disconnect()
}
}
}
internal fun parse(body: String): RemoteDocumentDelivery {
require(body.length <= MAX_RESPONSE_CHARS) { "Ответ WDTT Plus слишком большой." }
val root = runCatching { JSONObject(body) }
.getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") }
if (root.optInt("version", 0) != 1) {
throw IllegalStateException("Для этой ссылки нужна более новая версия WDTT Plus.")
}
val kind = when (root.optString("type").trim()) {
"base" -> RemoteDocumentKind.BASE
"update" -> RemoteDocumentKind.UPDATE
else -> throw IllegalStateException("WDTT Plus вернул неподдерживаемый тип данных.")
}
val document = root.optString("document").trim()
val documentParts = WdttDeepLink.parse(document, allowMissingHashes = true)
if (documentParts == null) {
throw IllegalStateException("WDTT Plus вернул неполные данные подключения.")
}
val binding = root.optString("binding").trim().takeIf(::opaqueValue).orEmpty()
val action = root.optJSONObject("continuation")
val key = action?.optString("key").orEmpty().trim()
val url = action?.optString("url").orEmpty().trim()
val available = action?.optBoolean("available", false) == true &&
opaqueValue(key) && safeServiceUrl(url)
val accessSource = root.optJSONObject("access")
val accessKey = accessSource?.optString("key").orEmpty().trim()
val accessUrl = accessSource?.optString("url").orEmpty().trim()
val accessBinding = accessSource?.optString("binding").orEmpty().trim()
val accessAvailable = accessSource?.optBoolean("available", false) == true &&
opaqueValue(accessKey) &&
safeServiceUrl(accessUrl) &&
opaqueValue(accessBinding)
val cachedAction = accessSource
?.optJSONObject("cached_action")
?.let(::parseCachedAction)
?: CachedRemoteAction.Unavailable
val exchange = accessSource
?.optJSONObject("exchange")
?.let(::parseProfileExchange)
?: RemoteProfileExchange.Unavailable
val initialAccessStatus = if (accessAvailable) {
accessSource
?.optJSONObject("status")
?.let { nested ->
AccessLifecycleGateway.parseStatus(
JSONObject(nested.toString()).put("version", 1).toString()
)
}
} else {
null
}
when (kind) {
RemoteDocumentKind.BASE -> {
if (documentParts.hashes.isNotBlank()) {
throw IllegalStateException(
"Ссылка подключения содержит лишние данные. Получите новую ссылку."
)
}
}
RemoteDocumentKind.UPDATE -> {
if (
binding.isBlank() ||
action != null
) {
throw IllegalStateException(
"Обновление профиля неполное или относится к другому действию."
)
}
}
}
val workers = root.optJSONObject("limits")?.optInt("workers", 0)
?.takeIf {
it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
it % TUNNEL_WORKERS_PER_GROUP == 0
}
?: 0
val profileRevision = root.optLong("profile_revision", 0L).coerceAtLeast(0)
return RemoteDocumentDelivery(
document = document,
binding = binding,
continuation = RemoteContinuation(
available = available,
key = key.takeIf { available }.orEmpty(),
url = url.takeIf { available }.orEmpty(),
expiresAt = action?.optLong("expires", 0L) ?: 0L,
message = action?.optString("message").orEmpty().trim()
),
access = RemoteAccessCapability(
available = accessAvailable,
key = accessKey.takeIf { accessAvailable }.orEmpty(),
url = accessUrl.takeIf { accessAvailable }.orEmpty(),
binding = accessBinding.takeIf { accessAvailable }.orEmpty(),
initialStatus = initialAccessStatus.takeIf { accessAvailable },
cachedAction = cachedAction.takeIf { accessAvailable }
?: CachedRemoteAction.Unavailable,
exchange = exchange.takeIf { accessAvailable }
?: RemoteProfileExchange.Unavailable,
),
kind = kind,
profileMaxWorkers = workers,
profileRevision = profileRevision,
)
}
internal fun parseFailure(body: String): Pair<String, RemoteDocumentFailureAction?> {
if (body.length > MAX_RESPONSE_CHARS) return "" to null
val root = runCatching { JSONObject(body) }.getOrNull() ?: return "" to null
val detail = root.optString("detail").trim().take(600)
val source = root.optJSONObject("action") ?: return detail to null
if (!source.optBoolean("available", false)) return detail to null
val label = source.optString("label").trim().take(120)
val primary = source.optString("url").trim()
val fallback = source.optString("fallback").trim()
val handler = source.optString("handler").trim()
val alternatesSource = source.optJSONArray("alternate_handlers") ?: JSONArray()
if (alternatesSource.length() > 8) return detail to null
val alternates = buildList {
repeat(alternatesSource.length()) { index ->
val value = alternatesSource.optString(index).trim()
if (!safePackageName(value)) return detail to null
add(value)
}
}.distinct()
val valid = label.isNotBlank() &&
safeExternalUrl(primary) &&
(fallback.isBlank() || safeExternalUrl(fallback)) &&
(handler.isBlank() || safePackageName(handler))
if (!valid) return detail to null
return detail to RemoteDocumentFailureAction(
label = label,
target = RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternates,
),
)
}
private fun safeServiceUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return trustedServiceUri(uri) &&
uri.rawQuery.isNullOrBlank() &&
uri.rawFragment.isNullOrBlank()
}
internal fun parseCachedAction(source: JSONObject): CachedRemoteAction {
val payload = source.optString("payload").trim()
val primary = source.optString("url").trim()
val fallback = source.optString("fallback").trim()
val handler = source.optString("handler").trim()
val available = source.optBoolean("available", false) &&
opaquePayload(payload) &&
safeExternalUrl(primary) &&
(fallback.isBlank() || safeExternalUrl(fallback)) &&
(handler.isBlank() || safePackageName(handler))
if (!available) return CachedRemoteAction.Unavailable
return CachedRemoteAction(
available = true,
payload = payload,
target = RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
),
title = source.optString("title").trim().take(120),
message = source.optString("message").trim().take(600),
label = source.optString("label").trim().take(120),
clipboardLabel = source.optString("clipboard_label").trim().take(120),
copiedMessage = source.optString("copied_message").trim().take(240),
failedMessage = source.optString("failed_message").trim().take(240),
helpTitle = source.optString("help_title").trim().take(120),
helpIntro = source.optString("help_intro").trim().take(600),
helpSteps = source.optString("help_steps").trim().take(1200),
)
}
internal fun parseProfileExchange(source: JSONObject): RemoteProfileExchange {
val submit = source.optJSONObject("submit")
val action = source.optJSONObject("action")
val submitToken = submit?.optString("token").orEmpty().trim()
val actionToken = action?.optString("token").orEmpty().trim()
val submitAvailable =
submit?.optBoolean("available", false) == true && opaqueValue(submitToken)
val label = action?.optString("label").orEmpty().trim().take(80)
val message = action?.optString("message").orEmpty().trim().take(300)
val actionAvailable =
action?.optBoolean("available", false) == true &&
opaqueValue(actionToken) &&
label.isNotBlank()
return if (submitAvailable || opaqueValue(actionToken)) {
RemoteProfileExchange(
submitAvailable = submitAvailable,
submitToken = submitToken.takeIf { submitAvailable }.orEmpty(),
actionAvailable = actionAvailable,
actionToken = actionToken.takeIf(::opaqueValue).orEmpty(),
label = label,
message = message,
)
} else {
RemoteProfileExchange.Unavailable
}
}
private fun safeExternalUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safePackageName(value: String): Boolean =
value.length in 3..255 &&
Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value)
private fun opaquePayload(value: String): Boolean =
value.length in 24..512 && Regex("^[A-Za-z0-9._-]+$").matches(value)
private fun trustedServiceUri(uri: URI): Boolean =
uri.scheme.equals("https", ignoreCase = true) &&
uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
private fun opaqueValue(value: String): Boolean =
value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value)
private fun validDevice(value: String): Boolean =
Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim())
private fun readBody(connection: HttpURLConnection, status: Int): String {
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty()
}
}
@@ -12,6 +12,11 @@ import javax.crypto.spec.GCMParameterSpec
class SecureStringStore(context: Context) {
private val appContext = context.applicationContext
private val decryptedCache = object : LinkedHashMap<String, String>(32, 0.75f, true) {
override fun removeEldestEntry(
eldest: MutableMap.MutableEntry<String, String>?
): Boolean = size > 64
}
companion object {
private const val KEY_ALIAS = "wdtt.settings.secrets"
@@ -29,14 +34,21 @@ class SecureStringStore(context: Context) {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())
val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
return VERSION_PREFIX +
val encoded = VERSION_PREFIX +
Base64.encodeToString(cipher.iv, Base64.NO_WRAP) +
":" +
Base64.encodeToString(encrypted, Base64.NO_WRAP)
synchronized(decryptedCache) {
decryptedCache[encoded] = value
}
return encoded
}
fun decrypt(value: String?): String? {
if (value.isNullOrBlank() || !value.startsWith(VERSION_PREFIX)) return null
synchronized(decryptedCache) {
decryptedCache[value]?.let { return it }
}
val payload = value.removePrefix(VERSION_PREFIX)
val parts = payload.split(":", limit = 2)
if (parts.size != 2) return null
@@ -47,7 +59,11 @@ class SecureStringStore(context: Context) {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
cipher.doFinal(encrypted).toString(Charsets.UTF_8)
}.getOrNull()
}.getOrNull()?.also { decrypted ->
synchronized(decryptedCache) {
decryptedCache[value] = decrypted
}
}
}
private fun getOrCreateKey(): SecretKey {
@@ -21,7 +21,7 @@ data class ServerAdminProfileInfo(
val vkHashes: String = "",
val secondaryVkHash: String = "",
val profileName: String = "",
val workersPerHash: Int = 16,
val workersPerHash: Int = 18,
val protocol: String = "udp",
val listenPort: Int = 9000,
val sni: String = "",
@@ -42,6 +42,7 @@ data class ServerAdminState(
val maxPasswords: Int,
val passwordCount: Int,
val deviceCount: Int,
val ownerDeviceCount: Int,
val expiredCount: Int,
val orphanDeviceCount: Int,
val orphanDevices: List<ServerDeviceInfo>,
@@ -393,6 +394,13 @@ object ServerAdminClient {
maxPasswords = server.optInt("max_passwords", 50),
passwordCount = server.optInt("password_count", clients.size),
deviceCount = server.optInt("device_count", 0),
ownerDeviceCount = server.optInt(
"owner_device_count",
server.optJSONObject("admin_profile")
?.optJSONArray("device_ids")
?.length()
?: 0
),
expiredCount = server.optInt("expired_count", 0),
orphanDeviceCount = server.optInt("orphan_device_count", 0),
orphanDevices = buildList {
@@ -423,7 +431,7 @@ object ServerAdminClient {
vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(),
secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(),
profileName = vpnProfileRestorableName(json?.optString("profile_name", "").orEmpty()),
workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128),
workersPerHash = (json?.optInt("workers_per_hash", 18) ?: 18).coerceIn(1, 128),
protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
listenPort = listenPort,
sni = json?.optString("sni", "").orEmpty().trim(),
@@ -565,7 +573,7 @@ internal fun buildAdminProfilePatchArgs(profile: ServerAdminProfileInfo): List<S
add("--profile-name")
add(it)
}
profile.workersPerHash.coerceIn(1, 128).takeIf { it != 16 }?.let {
profile.workersPerHash.coerceIn(1, 128).takeIf { it != 18 }?.let {
add("--workers")
add(it.toString())
}
@@ -655,7 +663,8 @@ fun buildServerConnectionLink(
publicHost: String,
profileName: String = ""
): String? {
if (hashes.isBlank() || password.isBlank()) return null
if (password.isBlank()) return null
val normalizedHashes = VkJoinLink.normalizeHashes(hashes) ?: return null
val parts = ports.split(",").map { it.trim().toIntOrNull() }
if (parts.size != 3) return null
val dtls = parts[0]?.takeIf { it in 1..65535 } ?: return null
@@ -670,7 +679,7 @@ fun buildServerConnectionLink(
wgPort = wg,
localPort = local,
password = password,
hashes = hashes,
hashes = normalizedHashes,
profileName = profileName
)
)
@@ -1,7 +1,7 @@
package com.wdtt.plus
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7)
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12)
data class ServerMigrationState(
val pendingLevel: Int,
File diff suppressed because it is too large. Load diff
@@ -45,6 +45,12 @@ object WdttTransferCodec {
normalizeVpnProfileName(parts.profileName)
.takeIf { it.isNotBlank() }
?.let { values["name"] = it }
parts.maxWorkers
.takeIf {
it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
it % TUNNEL_WORKERS_PER_GROUP == 0
}
?.let { values["max_workers"] = it.toString() }
return "wdtt://connect?" + values.entries.joinToString("&") { (key, value) ->
"${encode(key)}=${encode(value)}"
}
@@ -66,6 +72,12 @@ object WdttTransferCodec {
}
.toMap()
if (values["v"] != "1") return null
val maxWorkers = values["max_workers"]?.takeIf { it.isNotBlank() }?.let { raw ->
raw.toIntOrNull()?.takeIf {
it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
it % TUNNEL_WORKERS_PER_GROUP == 0
} ?: return null
} ?: 0
return WdttLinkParts(
host = values["host"].orEmpty(),
dtlsPort = values["dtls"]?.toIntOrNull() ?: return null,
@@ -73,7 +85,8 @@ object WdttTransferCodec {
localPort = values["local"]?.toIntOrNull() ?: return null,
password = values["password"].orEmpty(),
hashes = values["hashes"].orEmpty(),
profileName = values["name"].orEmpty()
profileName = values["name"].orEmpty(),
maxWorkers = maxWorkers
)
}
@@ -13,6 +13,7 @@ import android.provider.Settings
import androidx.core.content.ContextCompat
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.util.concurrent.ConcurrentHashMap
private const val UNKNOWN_WIFI_SSID = "<unknown ssid>"
private const val BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION"
@@ -23,6 +24,50 @@ data class TrustedWifiRuntimeState(
val status: String = ""
)
internal data class TrustedWifiResumeRetryPlan(
val delayMs: Long,
val keepCpuAwake: Boolean
)
internal fun trustedWifiResumeRetryPlan(retryCount: Int): TrustedWifiResumeRetryPlan =
if (retryCount.coerceAtLeast(0) < 12) {
TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true)
} else {
TrustedWifiResumeRetryPlan(delayMs = 30_000L, keepCpuAwake = false)
}
internal class TrustedWifiValidatedNetworkTracker<T : Any> {
private val validatedNetworks = ConcurrentHashMap.newKeySet<T>()
private val wifiNetworks = ConcurrentHashMap.newKeySet<T>()
@Synchronized
fun update(network: T, validated: Boolean, wifi: Boolean) {
if (validated) validatedNetworks.add(network) else validatedNetworks.remove(network)
if (wifi) wifiNetworks.add(network) else wifiNetworks.remove(network)
}
@Synchronized
fun lost(network: T) {
validatedNetworks.remove(network)
wifiNetworks.remove(network)
}
@Synchronized
fun forgetWifi() {
wifiNetworks.forEach { network -> validatedNetworks.remove(network) }
wifiNetworks.clear()
}
@Synchronized
fun hasUsableNetwork(): Boolean = validatedNetworks.isNotEmpty()
@Synchronized
fun clear() {
validatedNetworks.clear()
wifiNetworks.clear()
}
}
object TrustedWifiManager {
private val _state = MutableStateFlow(TrustedWifiRuntimeState())
val state = _state.asStateFlow()
+499 -59
View File
@@ -40,19 +40,35 @@ data class LogEntry(
val isError: Boolean get() = severity == LogSeverity.Error
}
@Stable
enum class ConnectionIssueKind {
GENERAL,
ACCESS,
}
@Stable
data class ConnectionIssue(
val title: String,
val action: String,
val isError: Boolean = true
val isError: Boolean = true,
val kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL,
)
internal val ConnectionIssue.isStandaloneUiIssue: Boolean
get() = kind != ConnectionIssueKind.ACCESS
enum class NetworkRecoveryAction {
SoftRestart,
RecreateVpn,
StopVpn
}
internal fun stableNetworkRecoveryAction(completedAttempts: Int): NetworkRecoveryAction = when {
completedAttempts <= 0 -> NetworkRecoveryAction.SoftRestart
completedAttempts == 1 -> NetworkRecoveryAction.RecreateVpn
else -> NetworkRecoveryAction.StopVpn
}
enum class TunnelStopReason(val displayText: String) {
User("отключено пользователем"),
VpnSlotTransferred("VPN-слот передан другому приложению"),
@@ -64,7 +80,14 @@ enum class TunnelStopReason(val displayText: String) {
CaptchaCancelled("проверка отменена пользователем"),
TrustedWifi("подключена доверенная сеть Wi-Fi"),
RestoreFailed("не удалось восстановить VPN"),
ServiceDestroyed("служба VPN остановлена системой")
ServiceDestroyed("служба VPN остановлена системой"),
AccessExpired("срок доступа закончился")
}
enum class TunnelTransition {
IDLE,
STARTING,
STOPPING,
}
private val stoppedStatsTrafficPairRegex = Regex(
@@ -121,6 +144,13 @@ internal fun classifyRecoverableWorkerRetry(
}
}
internal fun isExpiredAccessAuthFailure(line: String): Boolean =
line.contains("DENIED:expired", ignoreCase = true) ||
line.contains("срок действия пароля истёк", ignoreCase = true)
internal const val WRAP_HANDSHAKE_RETRY_MESSAGE =
"[WRAP] Отдельные каналы не ответили, выполняется повтор"
const val AMNEZIA_STYLE_RECOVERY = true
private const val RECOVERABLE_NETWORK_GRACE_MS = 90_000L
private const val HARD_NETWORK_GRACE_MS = 30_000L
@@ -177,6 +207,8 @@ object TunnelManager {
var isLoggingEnabled = true
val running = MutableStateFlow(false)
val transition = MutableStateFlow(TunnelTransition.IDLE)
val activeTunnelProfile = MutableStateFlow<Int?>(null)
val logs = MutableStateFlow<List<LogEntry>>(emptyList())
val unreadErrorCount = MutableStateFlow(0)
val config = MutableStateFlow<String?>(null)
@@ -192,16 +224,45 @@ object TunnelManager {
unreadErrorCount.value = 0
}
fun clearConnectionIssue() {
fun noteStartRequested() {
transition.value = TunnelTransition.STARTING
}
fun noteStopRequested() {
transition.value = TunnelTransition.STOPPING
}
fun clearTransition() {
transition.value = TunnelTransition.IDLE
}
fun clearConnectionIssue(kind: ConnectionIssueKind? = null) {
if (kind == null || connectionIssue.value?.kind == kind) {
connectionIssue.value = null
}
private fun setConnectionIssue(title: String, action: String, isError: Boolean = true) {
connectionIssue.value = ConnectionIssue(title = title, action = action, isError = isError)
}
fun reportConnectionIssue(title: String, action: String, isError: Boolean = true) {
setConnectionIssue(title, action, isError)
private fun setConnectionIssue(
title: String,
action: String,
isError: Boolean = true,
kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL,
) {
connectionIssue.value = ConnectionIssue(
title = title,
action = action,
isError = isError,
kind = kind,
)
}
fun reportConnectionIssue(
title: String,
action: String,
isError: Boolean = true,
kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL,
) {
setConnectionIssue(title, action, isError, kind)
}
fun isCaptchaInProgress(): Boolean =
@@ -427,12 +488,23 @@ object TunnelManager {
if (now - lastRecoveryAtMs < STABLE_RECOVERY_RETRY_MS) return null
lastRecoveryAtMs = now
val action = stableNetworkRecoveryAction(recoveryAttempts)
recoveryAttempts++
setConnectionIssue(
when (action) {
NetworkRecoveryAction.SoftRestart -> setConnectionIssue(
"Восстанавливаю транспорт",
"Сеть долго не подаёт признаков жизни. Выполняется одна мягкая попытка без пересоздания VPN."
"Сеть долго не подаёт признаков жизни. Выполняется тихая попытка без пересоздания VPN."
)
return NetworkRecoveryAction.SoftRestart
NetworkRecoveryAction.RecreateVpn -> setConnectionIssue(
"Пересоздаю VPN",
"Тихое восстановление не помогло. Системный VPN-интерфейс будет пересоздан один раз."
)
NetworkRecoveryAction.StopVpn -> setConnectionIssue(
"VPN остановлен, чтобы вернуть интернет",
"Пересоздание VPN не восстановило связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета."
)
}
return action
}
private fun buildDeviceInfoJson(context: Context): String {
@@ -461,6 +533,7 @@ object TunnelManager {
}
private var observersInitialized = false
private var accessRefreshRequestedForProcess = false
fun initObservers(context: Context) {
if (observersInitialized) return
@@ -494,6 +567,26 @@ object TunnelManager {
updateLog("deploy_ok_$hash", message, 2, false)
}
fun noteTrustedWifiEvent(key: String, message: String, warning: Boolean = false) {
val logKey = "trusted_wifi_$key"
val text = "[ДОВЕРЕННЫЙ WI-FI] $message"
if (warning) {
updateWarningLog(logKey, text, 2)
} else {
updateLog(logKey, text, 2, false)
}
}
fun noteAccessLifecycleEvent(key: String, message: String, warning: Boolean = false) {
val logKey = "access_$key"
val text = "[ДОСТУП] $message"
if (warning) {
updateWarningLog(logKey, text, 20)
} else {
updateLog(logKey, text, 20, false)
}
}
private fun updateLog(key: String, message: String, priority: Int, isError: Boolean = false) {
if (!isLoggingEnabled) return
val severity = if (isError) LogSeverity.Error else LogSeverity.Info
@@ -546,16 +639,25 @@ object TunnelManager {
}
}
fun start(context: Context, params: TunnelParams, isSwitching: Boolean = false) {
fun start(
context: Context,
params: TunnelParams,
isSwitching: Boolean = false,
preserveLogs: Boolean = false
) {
if (!isSwitching) noteStartRequested()
scope.launch {
startStopMutex.lock()
try {
if (running.value && !isSwitching) return@launch
if (running.value && !isSwitching) {
clearTransition()
return@launch
}
val appContext = context.applicationContext // Защита от Memory Leak
if (!isSwitching) {
clearLogs()
if (!preserveLogs) clearLogs()
config.value = null
stats.value = "Ожидание данных..."
floodCount = 0
@@ -573,6 +675,7 @@ object TunnelManager {
activeHashIndex = 0
currentParams = params
lastContext = appContext
accessRefreshRequestedForProcess = false
forceRegenerateUA = false
currentCaptchaMode = params.captchaMode
currentCaptchaSolveMethod = params.captchaSolveMethod
@@ -582,6 +685,22 @@ object TunnelManager {
val targetHash = if (activeHashIndex == 0) params.vkHashes else params.secondaryVkHash
val customCredentials = CustomVkClientCredentials(
enabled = params.customVkCredentialsEnabled,
clientId = params.customVkClientId,
clientSecret = params.customVkClientSecret
)
customVkCredentialsError(customCredentials)?.let { error ->
updateLog("custom_vk_credentials_error", "Ошибка: пользовательские реквизиты VK не заполнены", 99, true)
setConnectionIssue(
"Не заполнены реквизиты VK",
"$error Откройте «Настройки → Клиент ID» или выключите пользовательский режим."
)
running.value = false
currentParams = null
return@launch
}
// Robust hash parsing: split by comma, newline, or whitespace
val hashList = targetHash
.split(Regex("[,\\s\\n]+"))
@@ -607,7 +726,10 @@ object TunnelManager {
}
val hashCount = hashList.size.coerceIn(1, 4)
val totalWorkers = params.workersPerHash.coerceIn(1, 128)
val totalWorkers = normalizeTunnelWorkerCount(
requested = params.workersPerHash,
profileMaxWorkers = params.profileMaxWorkers
)
val hashMode = if (activeHashIndex == 0) "Основной" else "Запасной"
updateLog("config_info", "[$hashMode] Хешей=$hashCount, Потоков=$totalWorkers", 1)
@@ -644,7 +766,7 @@ object TunnelManager {
// stops flag.Parse and silently drops every argument after it.
cmd.add("-vkcalls-preflight=${params.vkCallsPreflight}")
val androidId = android.provider.Settings.Secure.getString(context.contentResolver, android.provider.Settings.Secure.ANDROID_ID) ?: "unknown"
val androidId = SettingsStore(appContext).getOrCreateTunnelDeviceId()
cmd.add("-device-id")
cmd.add(androidId)
cmd.add("-device-info")
@@ -653,6 +775,15 @@ object TunnelManager {
cmd.add("-password")
cmd.add(params.connectionPassword)
if (
params.managedConfigFirstStart &&
params.profileMaxWorkers == TUNNEL_WORKERS_PER_GROUP &&
totalWorkers == TUNNEL_WORKERS_PER_GROUP
) {
cmd.add("-config-first-start=true")
cmd.add("-hash-fallback=true")
}
cmd.add("-captcha-mode")
cmd.add(params.captchaMode)
@@ -662,12 +793,20 @@ object TunnelManager {
val env = pb.environment()
env["LD_LIBRARY_PATH"] = context.applicationInfo.nativeLibraryDir
if (params.customVkCredentialsEnabled) {
env["WDTT_CUSTOM_VK_CLIENT_ID"] = params.customVkClientId
env["WDTT_CUSTOM_VK_CLIENT_SECRET"] = params.customVkClientSecret
} else {
env.remove("WDTT_CUSTOM_VK_CLIENT_ID")
env.remove("WDTT_CUSTOM_VK_CLIENT_SECRET")
}
process = pb.start()
processStartedAtMs = System.currentTimeMillis()
wrapAuthTimeoutCount = 0
resetStatsLivenessState()
running.value = true
clearTransition()
startLogReader()
startWatchdog(appContext, params)
@@ -678,7 +817,9 @@ object TunnelManager {
e.printStackTrace()
running.value = false
currentParams = null
clearTransition()
} finally {
if (!isSwitching) clearTransition()
startStopMutex.unlock()
}
}
@@ -707,6 +848,26 @@ object TunnelManager {
val msgPrefixReplaced = line.replace(Regex("^\\d{4}/\\d{2}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?\\s"), "")
val lineTrim = msgPrefixReplaced.trim()
if (lineTrim.contains("[МОЩНОСТЬ] Лимит временно занят", true)) {
updateLog(
"worker_policy_wait",
"[МОЩНОСТЬ] Свободные потоки этого профиля временно заняты; повторяем подключение автоматически",
20,
false
)
return@forEachLine
}
if (lineTrim.contains("[МОЩНОСТЬ] Сервер остановил лишний поток", true)) {
updateLog(
"worker_policy_limit",
"[МОЩНОСТЬ] Лишние потоки остановлены согласно ограничению этого доступа; подключение продолжает работать",
20,
false
)
return@forEachLine
}
val isCaptchaV2FallbackStatus = lineTrim.contains("[КАПЧА] v2", true) &&
(
lineTrim.contains("fallback продолжит", true) ||
@@ -719,7 +880,8 @@ object TunnelManager {
(
lineTrim.contains("preflight не сработал", true) ||
lineTrim.contains("временно ограничил", true) ||
lineTrim.contains("временно пропущен", true)
lineTrim.contains("временно пропущен", true) ||
lineTrim.contains("пробуем совместимый резерв", true)
)
val isError = !isCaptchaV2FallbackStatus && !isCaptchaProtocolResult && !isVkCallsFallback && (
lineTrim.contains("Ошибка", true) ||
@@ -739,7 +901,7 @@ object TunnelManager {
wrapAuthTimeoutCount = 0
updateLog(
"wrap_timeout_recovered",
"[WRAP] Один поток не прошёл handshake, активных=${activeWorkers.value}; повторяем",
WRAP_HANDSHAKE_RETRY_MESSAGE,
20,
false
)
@@ -747,31 +909,68 @@ object TunnelManager {
wrapAuthTimeoutCount++
updateWarningLog(
"wrap_timeout_wait",
"[WRAP] Handshake не подтвердился, проверяем пароль/сеть ($wrapAuthTimeoutCount)",
WRAP_HANDSHAKE_RETRY_MESSAGE,
50
)
}
return@forEachLine
}
val accessExpired = isExpiredAccessAuthFailure(lineTrim)
val reason = when {
lineTrim.contains("неверный пароль") -> "Неверный пароль подключения"
lineTrim.contains("истёк") -> "Срок действия пароля истёк"
accessExpired -> "Срок действия пароля истёк"
lineTrim.contains("другому устройству") -> "Пароль привязан к другому устройству"
else -> "Ошибка авторизации"
}
val action = when {
lineTrim.contains("неверный пароль") ->
"Проверьте пароль в «Секретах» или вставьте актуальную wdtt:// ссылку."
lineTrim.contains("истёк") ->
"Создайте новый пароль у администратора или продлите текущий в Telegram-боте."
accessExpired ->
"Откройте профиль, чтобы проверить срок и доступные действия."
lineTrim.contains("другому устройству") ->
"Этот пароль уже закреплён за другим устройством. Отвяжите устройство в Telegram-боте или создайте новый пароль."
(
"Этот пароль уже закреплён за другим устройством. " +
"Запросите отвязку или новый профиль у поставщика."
)
else ->
"Проверьте пароль, VK-хеш и состояние сервера, затем попробуйте подключиться снова."
}
setConnectionIssue(reason, action)
handleCriticalError("\uD83D\uDD12 $reason. Воркеры остановлены.")
setConnectionIssue(
reason,
action,
kind = if (accessExpired) {
ConnectionIssueKind.ACCESS
} else {
ConnectionIssueKind.GENERAL
},
)
if (accessExpired) {
updateLog(
"access_expired",
"[ДОСТУП] Срок действия профиля закончился. Откройте вкладку «Туннель», чтобы проверить доступные действия.",
20,
true,
)
val accessContext = lastContext
val accessProfile = currentParams?.profileIndex
if (accessContext != null && accessProfile != null) {
scope.launch {
AccessLifecycleCoordinator.noteServerDenied(
accessContext,
accessProfile,
)
}
}
}
handleCriticalError(
"\uD83D\uDD12 $reason. Воркеры остановлены.",
if (accessExpired) {
TunnelStopReason.AccessExpired
} else {
TunnelStopReason.CriticalError
},
)
return@forEachLine
}
@@ -802,7 +1001,7 @@ object TunnelManager {
wrapAuthTimeoutCount = 0
updateLog(
"wrap_timeout_recovered",
"[WRAP] Один поток не прошёл handshake, активных=${activeWorkers.value}; повторяем",
WRAP_HANDSHAKE_RETRY_MESSAGE,
20,
false
)
@@ -810,7 +1009,7 @@ object TunnelManager {
wrapAuthTimeoutCount++
updateWarningLog(
"wrap_timeout_wait",
"[WRAP] Handshake не подтвердился, проверяем пароль/сеть ($wrapAuthTimeoutCount)",
WRAP_HANDSHAKE_RETRY_MESSAGE,
50
)
}
@@ -827,7 +1026,7 @@ object TunnelManager {
val redirectUri = parts[2]
val sessionToken = parts[3]
scope.launch {
handleCaptchaSolve(requestId, requestMode, redirectUri, sessionToken)
handleCaptchaSolve(observedProcess, requestId, requestMode, redirectUri, sessionToken)
}
}
3 -> {
@@ -835,18 +1034,18 @@ object TunnelManager {
val redirectUri = parts[1]
val sessionToken = parts[2]
scope.launch {
handleCaptchaSolve("", requestMode, redirectUri, sessionToken)
handleCaptchaSolve(observedProcess, "", requestMode, redirectUri, sessionToken)
}
}
2 -> {
val redirectUri = parts[0]
val sessionToken = parts[1]
scope.launch {
handleCaptchaSolve("", "selected", redirectUri, sessionToken)
handleCaptchaSolve(observedProcess, "", "selected", redirectUri, sessionToken)
}
}
else -> {
writeCaptchaResult("", "error:invalid CAPTCHA_SOLVE format")
writeCaptchaResult(observedProcess, "", "error:invalid CAPTCHA_SOLVE format")
}
}
return@forEachLine
@@ -912,6 +1111,19 @@ object TunnelManager {
}
if (active > 0) {
if (!accessRefreshRequestedForProcess) {
accessRefreshRequestedForProcess = true
val accessContext = lastContext
val accessProfile = currentParams?.profileIndex
if (accessContext != null && accessProfile != null) {
scope.launch {
AccessLifecycleCoordinator.refreshAfterSuccessfulConnect(
accessContext,
accessProfile,
)
}
}
}
lastActiveAtMs = now
wrapAuthTimeoutCount = 0
@@ -944,8 +1156,21 @@ object TunnelManager {
val workerRetry = classifyRecoverableWorkerRetry(lineTrim, activeWorkers.value)
when {
workerRetry != null ->
workerRetry != null -> {
if (activeWorkers.value <= 0) {
when (workerRetry.first) {
"worker_turn_allocate_retry" -> noteRecoverableNetworkIssue(
"TURN/UDP не отвечает",
"VK API выдал TURN-данные, но TURN Allocate не получил ответ. WDTT Plus попробует другие TURN-пути и повторы; если ошибка повторяется, оператор может ограничивать UDP/TURN."
)
"worker_dtls_retry" -> noteRecoverableNetworkIssue(
"VPS не отвечает на DTLS",
"TURN Allocate прошёл, но рукопожатие DTLS до сервера не завершилось. Проверьте порт сервера, доступность VPS и пароль подключения."
)
}
}
updateWarningLog(workerRetry.first, workerRetry.second, 20)
}
lineTrim.contains("[ВОРКЕР #", true) &&
lineTrim.contains("Невосстановимая TURN/STUN ошибка", true) ->
updateWarningLog(
@@ -953,22 +1178,100 @@ object TunnelManager {
"[TURN] Отдельные каналы завершили попытки подключения; остальные продолжают работу",
50
)
lineTrim.contains("[DNS]", true) -> {
val text = lineTrim.substringAfter("[DNS]").trim()
when {
text.contains("Прямой DNS клиента недоступен", true) &&
text.contains("системный DNS", true) -> {
noteRecoverableNetworkIssue(
"Прямой DNS клиента недоступен",
"Оператор не ответил на прямые DNS-запросы клиента. WDTT Plus использует системный DNS устройства для этого запуска."
)
updateWarningLog(
"dns_system_fallback",
"[DNS] Прямой DNS клиента недоступен, используем системный DNS устройства",
20
)
}
text.contains("DNS до VK недоступен", true) -> {
noteRecoverableNetworkIssue(
"DNS до VK недоступен",
"Прямой DNS клиента и системный DNS устройства не ответили. Проверьте Private DNS, сеть оператора или попробуйте другую сеть."
)
updateWarningLog("dns_vk_unavailable", "[DNS] DNS до VK недоступен", 99)
}
else -> updateLog("dns_status", "[DNS] $text", 2, false)
}
}
lineTrim.contains("[VKCalls]", true) -> {
when {
lineTrim.contains("TURN credentials получены", true) ->
updateLog("vkcalls_ok", "[VKCalls] Анонимные TURN-данные получены ✓", 2, false)
updateLog("vkcalls_ok", "[VKCalls] Основной бескапчевый провайдер сработал ✓", 2, false)
lineTrim.contains("preflight не сработал", true) ||
lineTrim.contains("временно ограничил", true) ||
lineTrim.contains("временно пропущен", true) ->
updateLog("vkcalls_fallback", "[VKCalls] Анонимный вход временно недоступен — используется капча", 20, false)
updateLog("vkcalls_fallback", "[VKCalls] Основной провайдер временно недоступен — пробуем legacy-резерв", 20, false)
lineTrim.contains("пробуем совместимый резерв", true) ->
updateLog("vkcalls_api_fallback", "[VKCalls] Основной API-домен не ответил — пробуем совместимый резерв", 20, false)
lineTrim.endsWith("[VKCalls] preflight", true) ->
updateLog("vkcalls_start", "[VKCalls] Пробуем анонимный вход...", 2, false)
updateLog("vkcalls_start", "[VKCalls] Пробуем основной бескапчевый провайдер...", 2, false)
else -> {
if (isError) updateWarningLog("vkcalls_status", lineTrim, 20)
else updateLog("vkcalls_status", lineTrim, 20, false)
}
}
}
lineTrim.contains("[VK Provider]", true) -> {
when {
lineTrim.contains("TURN-данные сохранены", true) -> {
val lifetime = lineTrim.substringAfter("сохранены на", "").trim()
updateLog(
"vk_provider_cache",
"[ВК] TURN-данные сохранены${lifetime.takeIf(String::isNotBlank)?.let { " на $it" }.orEmpty()}",
2,
false
)
}
lineTrim.contains("legacy-custom", true) && lineTrim.contains("успешно", true) ->
updateLog("vk_provider_custom", "[ВК] Собственный legacy Client ID сработал ✓", 5, false)
lineTrim.contains("legacy-custom", true) && lineTrim.contains("пробуем", true) ->
updateLog("vk_provider_custom", "[ВК] Пробуем собственный legacy Client ID...", 5, false)
lineTrim.contains("legacy-custom", true) && lineTrim.contains("CAPTCHA_WAIT_REQUIRED", true) ->
updateLog("vk_provider_custom_wait", "[КАПЧА] Собственный legacy-провайдер ждёт следующую безопасную попытку", 20, false)
lineTrim.contains("legacy-custom", true) && lineTrim.contains("не сработал", true) ->
updateLog("vk_provider_custom_fallback", "[ВК] Собственный legacy Client ID не сработал — пробуем встроенный резерв", 20, false)
lineTrim.contains("legacy-built-in", true) && lineTrim.contains("успешно", true) ->
updateLog("vk_provider_builtin", "[ВК] Встроенный legacy Client ID сработал ✓", 5, false)
lineTrim.contains("legacy-built-in", true) && lineTrim.contains("пробуем", true) ->
updateLog("vk_provider_builtin", "[ВК] Пробуем встроенный legacy Client ID...", 5, false)
lineTrim.contains("legacy-built-in", true) && lineTrim.contains("CAPTCHA_WAIT_REQUIRED", true) ->
updateLog("vk_provider_builtin_wait", "[КАПЧА] Встроенный legacy-провайдер ждёт следующую безопасную попытку", 20, false)
lineTrim.contains("legacy-built-in", true) && lineTrim.contains("не сработал", true) ->
updateLog("vk_provider_builtin_fallback", "[ВК] Этот встроенный Client ID не сработал — пробуем следующий", 20, false)
lineTrim.contains("modern-vkcalls", true) && lineTrim.contains("успешно", true) ->
updateLog("vk_provider_modern", "[ВК] Используется современный VKCalls ✓", 2, false)
else -> updateLog("vk_provider_status", lineTrim, 20, false)
}
}
lineTrim.contains("[VK Auth]", true) -> {
when {
lineTrim.contains("Using cached credentials", true) ->
updateLog("vk_credentials_cache", "[ВК] Используются ранее полученные TURN-данные", 2, false)
lineTrim.contains("Throttling", true) ->
updateLog("vk_credentials_throttle", "[ВК] Безопасная пауза между запросами к VK", 20, false)
lineTrim.contains("Credentials cache invalidated", true) ->
updateLog("vk_credentials_refresh", "[ВК] TURN-данные устарели — получаем свежие", 5, false)
lineTrim.contains("getCallPreview failed", true) ->
updateLog("vk_preview_optional", "[ВК] Предпросмотр legacy-звонка недоступен, продолжаем получение TURN-данных", 20, false)
lineTrim.contains("Rate limit detected", true) ->
updateLog("vk_legacy_rate_limit", "[ВК] Этот legacy Client ID временно ограничен — пробуем следующий", 20, false)
lineTrim.contains("Все legacy-провайдеры", true) ->
updateLog("vk_legacy_retry", "[ВК] Legacy-провайдеры временно не ответили — выполняется безопасный повтор", 20, false)
else -> {
if (isError) updateWarningLog("vk_auth_status", lineTrim, 20)
}
}
}
lineTrim.contains("[КАПЧА] AUTO:") -> {
var text = lineTrim.substringAfter("[КАПЧА] AUTO:").trim()
text = text.replace(Regex("\\s*\\([^)]+\\)\\s*"), " ").trim()
@@ -1109,15 +1412,26 @@ object TunnelManager {
val errorKey = when {
isHardNetworkFailure(lineTrim) -> "err_hard_network"
isLocalDnsRefused(lineTrim) -> "err_local_dns_refused"
lineTrim.contains("lookup login.vk.ru", true) -> "err_vk_dns"
lineTrim.contains("lookup ", true) &&
(
lineTrim.contains("login.vk.ru", true) ||
lineTrim.contains("api.vk.ru", true) ||
lineTrim.contains("api.vk.me", true) ||
lineTrim.contains("calls.okcdn.ru", true)
) -> "err_vk_dns"
lineTrim.contains("VK HTTPS", true) -> "err_vk_https"
lineTrim.contains("connection refused") -> "err_conn_refused"
lineTrim.contains("timeout") -> "err_timeout"
lineTrim.contains("кредов") -> "err_creds"
lineTrim.contains("DTLS") -> "err_dtls"
else -> "general_error_" + lineTrim.take(15).hashCode()
}
val failedVkHost = listOf("login.vk.ru", "api.vk.ru", "api.vk.me", "calls.okcdn.ru")
.firstOrNull { lineTrim.contains(it, true) }
val errorMessage = if (errorKey == "err_vk_dns") {
"[СЕТЬ] DNS до VK недоступен: login.vk.ru"
"[СЕТЬ] DNS до VK недоступен: ${failedVkHost ?: "VK/OK"}"
} else if (errorKey == "err_vk_https") {
"[VK] HTTPS до VK/OK не отвечает"
} else {
lineTrim
}
@@ -1138,6 +1452,11 @@ object TunnelManager {
"DNS до VK недоступен",
"WDTT Plus попробует восстановить транспорт автоматически. Если не восстановится, проверьте интернет без VPN и DNS на устройстве."
)
} else if (errorKey == "err_vk_https") {
noteRecoverableNetworkIssue(
"HTTPS до VK/OK не отвечает",
"DNS сработал, но HTTPS-запрос к VK/OK не завершился. WDTT Plus попробует восстановить транспорт; если повторяется, проверьте ограничения сети оператора."
)
} else if (errorKey == "err_timeout" || errorKey == "err_conn_refused") {
noteRecoverableNetworkIssue(
"Транспорт не отвечает",
@@ -1148,6 +1467,7 @@ object TunnelManager {
"err_hard_network",
"err_local_dns_refused",
"err_vk_dns",
"err_vk_https",
"err_conn_refused",
"err_timeout",
"err_creds"
@@ -1205,12 +1525,15 @@ object TunnelManager {
}
}
private fun handleCriticalError(message: String) {
private fun handleCriticalError(
message: String,
stopReason: TunnelStopReason = TunnelStopReason.CriticalError,
) {
if (connectionIssue.value == null) {
setConnectionIssue("Подключение остановлено", "$message Проверьте настройки и попробуйте снова.")
}
updateLog("circuit_breaker", "[СТОП] $message", -1, true)
stop(TunnelStopReason.CriticalError)
stop(stopReason)
}
private fun handleHashError() {
@@ -1332,14 +1655,78 @@ object TunnelManager {
updateLog("network_restart", reason, 50, false)
activeWorkers.value = 0
resetStatsLivenessState()
killProcess()
val restartDelayMs = transportRecoveryPolicy(
params.managedConfigFirstStart
).processRestartDelayMs
scope.launch {
delay(2500)
killProcess()
delay(restartDelayMs)
if (currentParams === params && running.value) {
start(context, params, isSwitching = true)
}
}
return true
}
internal fun applyUpdatedProfileConfiguration(
context: Context,
params: TunnelParams,
restartTransport: Boolean,
): TunnelProfileRuntimeApplyResult {
val previous = currentParams ?: return TunnelProfileRuntimeApplyResult.INACTIVE
if (!running.value || previous.profileIndex != params.profileIndex) {
return TunnelProfileRuntimeApplyResult.INACTIVE
}
if (!tunnelProfileRuntimeConfigurationChanged(previous, params)) {
return TunnelProfileRuntimeApplyResult.UNCHANGED
}
val appContext = context.applicationContext
currentParams = params
lastContext = appContext
activeHashIndex = 0
currentHashErrorCount = 0
wrapAuthTimeoutCount = 0
currentCaptchaMode = params.captchaMode
currentCaptchaSolveMethod = params.captchaSolveMethod
accessRefreshRequestedForProcess = false
resetNetworkRecoveryState()
resetStatsLivenessState()
clearConnectionIssue(ConnectionIssueKind.GENERAL)
activeWorkers.value = 0
if (!restartTransport) {
updateLog(
"profile_runtime_update_pending",
"[ПРОФИЛЬ] Новые параметры сохранены и будут применены при возобновлении VPN.",
20,
false,
)
return TunnelProfileRuntimeApplyResult.STORED_FOR_RESUME
}
updateLog(
"profile_runtime_update",
"[ПРОФИЛЬ] Параметры активного подключения обновлены. Мягко переподключаю транспорт.",
20,
false,
)
scope.launch {
startStopMutex.lock()
try {
if (currentParams !== params || !running.value) return@launch
killProcess()
delay(250L)
} finally {
startStopMutex.unlock()
}
if (currentParams === params && running.value) {
start(appContext, params, isSwitching = true, preserveLogs = true)
}
}
return TunnelProfileRuntimeApplyResult.RESTARTED
}
fun noteUnderlyingNetworkChanged(
reason: String,
graceMs: Long = RECOVERABLE_NETWORK_GRACE_MS,
@@ -1503,8 +1890,15 @@ object TunnelManager {
val proc = process
process = null
if (proc != null) {
try {
proc.outputStream.write("STOP\n".toByteArray(Charsets.UTF_8))
proc.outputStream.flush()
} catch (_: Exception) {}
try { proc.waitFor(1500, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
if (proc.isAlive) {
try { proc.destroy() } catch (_: Exception) {}
try { proc.waitFor(500, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
try { proc.waitFor(750, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
}
if (proc.isAlive) {
try { proc.destroyForcibly() } catch (_: Exception) {}
try { proc.waitFor(1000, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
@@ -1525,6 +1919,7 @@ object TunnelManager {
}
fun onWireGuardStoppedExternally() {
noteStopRequested()
scope.launch {
startStopMutex.lock()
try {
@@ -1542,12 +1937,14 @@ object TunnelManager {
currentParams = null
ManlCaptchaWebViewManager.cancelCaptcha()
} finally {
clearTransition()
startStopMutex.unlock()
}
}
}
fun stop(reason: TunnelStopReason = TunnelStopReason.User) {
noteStopRequested()
scope.launch {
startStopMutex.lock()
try {
@@ -1563,28 +1960,45 @@ object TunnelManager {
resetNetworkRecoveryState()
ManlCaptchaWebViewManager.cancelCaptcha()
} finally {
if (reason == TunnelStopReason.User) {
startCooldown(1500L)
}
clearTransition()
startStopMutex.unlock()
}
}
}
suspend fun stopAndWait(reason: TunnelStopReason = TunnelStopReason.User) {
suspend fun stopAndWait(
reason: TunnelStopReason = TunnelStopReason.User,
context: Context? = null,
forceVpnRelease: Boolean = false,
) {
noteStopRequested()
startStopMutex.lock()
try {
if (!running.value && currentParams == null) return
val hadManagedSession = running.value || currentParams != null || process != null
if (!hadManagedSession && !forceVpnRelease) return
val stopHelper = wgHelper ?: context?.applicationContext?.let(::WireGuardHelper)
withContext(Dispatchers.Main) {
wgHelper?.stopTunnel()
stopHelper?.stopTunnel()
}
withContext(Dispatchers.IO) {
killProcess()
running.value = false
if (hadManagedSession) {
markLogSessionStopped(reason)
}
resetStatsLivenessState()
currentParams = null
resetNetworkRecoveryState()
ManlCaptchaWebViewManager.cancelCaptcha()
}
} finally {
if (reason == TunnelStopReason.User) {
startCooldown(1500L)
}
clearTransition()
startStopMutex.unlock()
}
}
@@ -1597,9 +2011,15 @@ object TunnelManager {
}
}
private suspend fun handleCaptchaSolve(requestId: String, requestMode: String, redirectUri: String, sessionToken: String) {
private suspend fun handleCaptchaSolve(
expectedProcess: Process,
requestId: String,
requestMode: String,
redirectUri: String,
sessionToken: String
) {
val ctx = lastContext ?: run {
writeCaptchaResult(requestId, "error:context is null")
writeCaptchaResult(expectedProcess, requestId, "error:context is null")
return
}
val mode = requestMode.lowercase()
@@ -1622,7 +2042,7 @@ object TunnelManager {
}
}
updateLog("captcha_wv_step_4", "[КАПЧА WBV] Капча решена ✓", 5, false)
writeCaptchaResult(requestId, token)
writeCaptchaResult(expectedProcess, requestId, token)
} catch (e: IllegalStateException) {
val errorMsg = e.message ?: "WV state error"
val autoFallback = mode == "auto" && (
@@ -1636,23 +2056,23 @@ object TunnelManager {
} else {
updateWarningLog("captcha_wv_err", "[КАПЧА WBV] $errorMsg", 5)
}
writeCaptchaResult(requestId, "error:$errorMsg")
writeCaptchaResult(expectedProcess, requestId, "error:$errorMsg")
} catch (e: kotlinx.coroutines.TimeoutCancellationException) {
if (mode == "auto") {
updateLog("captcha_wv_timeout", "[КАПЧА WBV] Авто WebView не успел, идём дальше", 5, false)
} else {
updateWarningLog("captcha_wv_err", "[КАПЧА WBV] WebView не ответил вовремя", 5)
}
writeCaptchaResult(requestId, "error:timeout")
writeCaptchaResult(expectedProcess, requestId, "error:timeout")
} catch (e: kotlin.coroutines.cancellation.CancellationException) {
updateWarningLog("captcha_wv_err", "[КАПЧА WBV] Проверка отменена", 5)
writeCaptchaResult(requestId, "error:cancelled")
writeCaptchaResult(expectedProcess, requestId, "error:cancelled")
} catch (e: Exception) {
val errorMsg = e.message ?: "${e::class.simpleName}"
if (errorMsg != "tunnel stopped") {
updateWarningLog("captcha_wv_err", "[КАПЧА WBV] Текущая попытка не выполнена — $errorMsg", 5)
}
writeCaptchaResult(requestId, "error:$errorMsg")
writeCaptchaResult(expectedProcess, requestId, "error:$errorMsg")
} finally {
updateLog("captcha_wv_step_6", "[КАПЧА WBV] WebView уничтожен", 5, false)
endCaptchaSolve(captchaRequestId)
@@ -1701,16 +2121,23 @@ object TunnelManager {
return ManlCaptchaWebViewManager.solveCaptchaAsync(ctx, redirectUri, sessionToken)
}
private fun writeCaptchaResult(requestId: String, result: String) {
val proc = process
if (proc == null || !proc.isAlive) return
private fun writeCaptchaResult(expectedProcess: Process, requestId: String, result: String) {
if (process !== expectedProcess || !expectedProcess.isAlive) return
try {
val payload = if (requestId.isBlank()) result else "$requestId|$result"
val line = "CAPTCHA_RESULT|$payload\n"
proc.outputStream.write(line.toByteArray(Charsets.UTF_8))
proc.outputStream.flush()
expectedProcess.outputStream.write(line.toByteArray(Charsets.UTF_8))
expectedProcess.outputStream.flush()
} catch (e: Exception) {
updateLog("captcha_write_err", "[КАПЧА] Ошибка записи: ${e.message}", 200, true)
// Остановка туннеля может закрыть stdin между проверкой isAlive и записью.
// Это штатная гонка завершения, а не ошибка подключения пользователя.
if (process === expectedProcess && expectedProcess.isAlive) {
updateWarningLog(
"captcha_write_err",
"[КАПЧА] Нативный клиент не принял результат: ${e.message ?: e::class.simpleName}",
5
)
}
}
}
@@ -1749,5 +2176,18 @@ data class TunnelParams(
val captchaMode: String = "auto",
val captchaSolveMethod: String = "auto",
val fingerprint: String = "firefox",
val clientIds: String = "6287487,8202606"
val clientIds: String = DEFAULT_VK_CLIENT_IDS,
val customVkCredentialsEnabled: Boolean = false,
val customVkClientId: String = "",
val customVkClientSecret: String = "",
val profileMaxWorkers: Int = 0,
val managedConfigFirstStart: Boolean = false,
val profileIndex: Int = 0,
)
internal enum class TunnelProfileRuntimeApplyResult {
INACTIVE,
UNCHANGED,
STORED_FOR_RESUME,
RESTARTED,
}
@@ -0,0 +1,51 @@
package com.wdtt.plus
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
internal object TunnelProfileRuntimeUpdateBus {
private val mutableRequests = MutableSharedFlow<Int>(
extraBufferCapacity = 3,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
val requests = mutableRequests.asSharedFlow()
fun request(profileIndex: Int) {
if (profileIndex in 0..2) {
mutableRequests.tryEmit(profileIndex)
}
}
}
internal fun shouldRequestTunnelProfileRuntimeUpdate(
updatedProfile: Int,
activeTunnelProfile: Int?,
tunnelRunning: Boolean,
trustedWifiWaiting: Boolean,
): Boolean =
updatedProfile in 0..2 &&
activeTunnelProfile == updatedProfile &&
(tunnelRunning || trustedWifiWaiting)
internal fun tunnelProfileRuntimeConfigurationChanged(
current: TunnelParams,
updated: TunnelParams,
): Boolean =
current.profileIndex == updated.profileIndex &&
current != updated
internal fun requestTunnelProfileRuntimeUpdate(profileIndex: Int) {
if (profileIndex !in 0..2) return
if (
!shouldRequestTunnelProfileRuntimeUpdate(
updatedProfile = profileIndex,
activeTunnelProfile = TunnelManager.activeTunnelProfile.value,
tunnelRunning = TunnelManager.running.value,
trustedWifiWaiting = TrustedWifiManager.state.value.waiting,
)
) {
return
}
TunnelProfileRuntimeUpdateBus.request(profileIndex)
}
+482 -76
View File
@@ -23,14 +23,18 @@ import androidx.core.app.NotificationCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4"
private const val TUNNEL_ALERT_CHANNEL_ID = "wdtt_tunnel_alert_v1"
@@ -39,33 +43,42 @@ private const val TUNNEL_ALERT_NOTIFICATION_ID = 2
private const val NETWORK_CHANGE_SETTLE_MS = 90_000L
private const val NETWORK_RETURN_SETTLE_MS = 45_000L
private const val NETWORK_LOSS_GRACE_MS = 2 * 60_000L
private const val STABLE_NETWORK_RECONNECT_DELAY_MS = 15_000L
private const val STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS = 2 * 60_000L
private const val WAKE_RESCUE_GRACE_MS = 60_000L
private const val WAKE_RESCUE_FAIL_OPEN_MS = 2 * 60_000L
private const val ACTIVE_PROFILE_REFRESH_INTERVAL_MS = 2 * 60_000L
private const val INITIAL_VPN_START_GRACE_MS = 90_000L
private const val TRUSTED_WIFI_ENTER_DELAY_MS = 2_000L
private const val TRUSTED_WIFI_EXIT_DELAY_MS = 5_000L
private const val TRUSTED_WIFI_FAST_RESUME_RETRY_COUNT = 12
private const val TRUSTED_WIFI_SLOW_RESUME_RETRY_MS = 30_000L
private const val TRUSTED_WIFI_RESUME_START_TIMEOUT_MS = 30_000L
private const val TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS = 75_000L
class TunnelService : Service() {
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val startRequestGate = TunnelStartRequestGate()
private var pendingStartJob: Job? = null
private var profileRuntimeUpdateJob: Job? = null
private var activeProfileRefreshJob: Job? = null
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
private var trustedWifiTransitionWakeLock: PowerManager.WakeLock? = null
private var updateJob: Job? = null
private var profileNameJob: Job? = null
private var networkChangeJob: Job? = null
private var lastNotificationTitle: String? = null
private var lastNotificationText: String? = null
private var notificationProfileTitle: String = "WDTT Plus"
private var connectionProfileIndex: Int? = null
private var profileStateJob: Job? = null
private var requestedStopReason: TunnelStopReason? = null
private var stopSequenceJob: Job? = null
private var intentionalStopCompleted = false
// Network Monitoring
private var connectivityManager: ConnectivityManager? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
private var lastNetworkChangeTime = 0L
private val activeNetworks = mutableSetOf<Network>()
private val activeNetworks = ConcurrentHashMap.newKeySet<Network>()
private val trustedWifiValidatedNetworks = TrustedWifiValidatedNetworkTracker<Network>()
private var isTunnelPaused = false
private var lastValidatedNetwork: Network? = null
private var lastStableNetworkReconnectAt = 0L
@@ -79,11 +92,15 @@ class TunnelService : Service() {
private val trustedWifiEvaluationScheduleLock = Any()
private var trustedWifiPendingEvaluationDelayMs: Long? = null
private var trustedWifiResumeRetryJob: Job? = null
private val trustedWifiResumeRetryLock = Any()
private var trustedWifiResumeRetryCount = 0
@Volatile
private var trustedWifiResumeInProgress = false
private var trustedWifiResumeStartedAt = 0L
private val trustedWifiTransitionMutex = Mutex()
@Volatile
private var trustedWifiWaiting = false
@Volatile
private var trustedWifiWaitingSsid = ""
private var lastStartParams: TunnelParams? = null
@@ -96,6 +113,9 @@ class TunnelService : Service() {
setupTrustedWifiMonitoring()
registerScreenStateReceiver()
registerTrustedWifiStateReceiver()
serviceScope.launch {
TunnelProfileRuntimeUpdateBus.requests.collect(::applyUpdatedTunnelProfile)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@@ -113,7 +133,7 @@ class TunnelService : Service() {
peer = intent.getStringExtra("peer") ?: "",
vkHashes = intent.getStringExtra("vk_hashes") ?: "",
secondaryVkHash = intent.getStringExtra("secondary_vk_hash") ?: "",
workersPerHash = intent.getIntExtra("workers_per_hash", 16),
workersPerHash = intent.getIntExtra("workers_per_hash", 18),
port = intent.getIntExtra("port", 9000),
sni = intent.getStringExtra("sni") ?: "",
connectionPassword = intent.getStringExtra("connection_password") ?: "",
@@ -122,12 +142,16 @@ class TunnelService : Service() {
captchaMode = sanitizeCaptchaMode(intent.getStringExtra("captcha_mode")),
captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto",
fingerprint = intent.getStringExtra("fingerprint") ?: "firefox",
clientIds = intent.getStringExtra("client_ids") ?: "6287487,8202606"
clientIds = intent.getStringExtra("client_ids") ?: DEFAULT_VK_CLIENT_IDS,
customVkCredentialsEnabled = intent.getBooleanExtra("custom_vk_credentials_enabled", false),
customVkClientId = intent.getStringExtra("custom_vk_client_id") ?: "",
customVkClientSecret = intent.getStringExtra("custom_vk_client_secret") ?: "",
profileMaxWorkers = intent.getIntExtra("profile_max_workers", 0),
managedConfigFirstStart =
intent.getBooleanExtra(MANAGED_CONFIG_FIRST_START_EXTRA, false),
profileIndex = intent.getIntExtra(TUNNEL_PROFILE_INDEX_EXTRA, 0).coerceIn(0, 2),
)
lastStartParams = params
TunnelManager.scope.launch(Dispatchers.Main) {
startOrWaitForTrustedWifi(params)
}
requestTunnelStart(params)
}
"STOP" -> stopTunnel(TunnelStopReason.User)
"DEPLOY_START" -> {
@@ -161,6 +185,9 @@ class TunnelService : Service() {
startPersistentForeground(createNotification("Проверка доверенной Wi-Fi сети..."))
startNotificationProfileWatcher()
startStatsUpdater()
acquireTrustedWifiTransitionWakeLock()
releaseWakeLock()
releaseWifiLock()
}
scheduleTrustedWifiEvaluation(delayMs = 0L)
}
@@ -173,42 +200,163 @@ class TunnelService : Service() {
startPersistentForeground(notification)
val appContext = applicationContext
TunnelManager.scope.launch {
val generation = startRequestGate.next()
pendingStartJob?.cancel()
pendingStartJob = serviceScope.launch {
try {
val store = SettingsStore(appContext)
val params = buildTunnelParamsFromSettings(appContext)
val savedTunnelProfile = store.activeTunnelProfile.first()
val params = buildTunnelParamsFromSettings(appContext, savedTunnelProfile)
if (!startRequestGate.isCurrent(generation)) return@launch
if (params != null) {
launch(Dispatchers.Main) {
lastStartParams = params
val restoreWaiting = store.trustedWifiEnabled.first() && store.trustedWifiWaiting.first()
val access = AccessLifecycleCoordinator.prepareStart(
appContext,
params.profileIndex,
)
if (!startRequestGate.isCurrent(generation)) return@launch
if (access is AccessStartDecision.Denied) {
reportAccessDenied(access.status)
stopTunnel(TunnelStopReason.AccessExpired)
return@launch
}
val refreshedParams = buildTunnelParamsFromSettings(
appContext,
params.profileIndex,
)
if (refreshedParams == null) {
stopTunnel(TunnelStopReason.RestoreFailed)
return@launch
}
rememberConnectionProfile(
refreshedParams.profileIndex,
persist = savedTunnelProfile == null
)
lastStartParams = refreshedParams
val restoreWaiting = store.trustedWifiEnabled.first() &&
store.trustedWifiWaiting.first()
if (!startRequestGate.isCurrent(generation)) return@launch
if (restoreWaiting) {
trustedWifiWaiting = true
trustedWifiWaitingSsid = store.trustedWifiWaitingSsid.first()
if (!startRequestGate.isCurrent(generation)) return@launch
TrustedWifiManager.setWaiting(trustedWifiWaitingSsid)
TunnelManager.noteTrustedWifiEvent(
"waiting_restored",
"Android восстановил службу ожидания; проверяем текущую сеть."
)
startNotificationProfileWatcher()
startStatsUpdater()
acquireTrustedWifiTransitionWakeLock()
releaseWakeLock()
releaseWifiLock()
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
startOrWaitForTrustedWifi(params)
}
startOrWaitForTrustedWifi(refreshedParams)
}
} else {
launch(Dispatchers.Main) {
stopTunnel(TunnelStopReason.RestoreFailed)
}
}
} catch (e: Exception) {
launch(Dispatchers.Main) {
if (startRequestGate.isCurrent(generation)) {
stopTunnel(TunnelStopReason.RestoreFailed)
}
}
}
}
private fun requestTunnelStart(params: TunnelParams) {
val generation = startRequestGate.next()
pendingStartJob?.cancel()
pendingStartJob = serviceScope.launch {
val access = withContext(Dispatchers.IO) {
AccessLifecycleCoordinator.prepareStart(
applicationContext,
params.profileIndex,
)
}
if (!startRequestGate.isCurrent(generation)) return@launch
when (access) {
AccessStartDecision.Allowed -> {
val refreshedParams = withContext(Dispatchers.IO) {
buildTunnelParamsFromSettings(
applicationContext,
params.profileIndex,
)
}
if (refreshedParams == null) {
stopTunnel(TunnelStopReason.RestoreFailed)
return@launch
}
rememberConnectionProfile(refreshedParams.profileIndex)
lastStartParams = refreshedParams
startOrWaitForTrustedWifi(refreshedParams)
}
is AccessStartDecision.Denied -> {
reportAccessDenied(access.status)
stopTunnel(TunnelStopReason.AccessExpired)
}
}
}
}
private fun applyUpdatedTunnelProfile(profileIndex: Int) {
if (profileIndex !in 0..2) return
val activeProfile = connectionProfileIndex
?: TunnelManager.activeTunnelProfile.value
?: return
if (activeProfile != profileIndex) return
profileRuntimeUpdateJob?.cancel()
profileRuntimeUpdateJob = serviceScope.launch {
val refreshedParams = withContext(Dispatchers.IO) {
buildTunnelParamsFromSettings(
applicationContext,
profileIndex,
)
}
if (refreshedParams == null) {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profileIndex}_runtime_update_invalid",
message = "Новые параметры профиля пока не удалось применить",
warning = true,
)
return@launch
}
lastStartParams = refreshedParams
if (trustedWifiWaiting) {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profileIndex}_runtime_update_waiting",
message = "Новые параметры будут применены после выхода из доверенной сети",
warning = false,
)
return@launch
}
when (
TunnelManager.applyUpdatedProfileConfiguration(
context = applicationContext,
params = refreshedParams,
restartTransport = !isTunnelPaused,
)
) {
TunnelProfileRuntimeApplyResult.RESTARTED ->
updateNotification("Обновление подключения...")
TunnelProfileRuntimeApplyResult.STORED_FOR_RESUME ->
updateNotification("Ожидание сети")
TunnelProfileRuntimeApplyResult.INACTIVE,
TunnelProfileRuntimeApplyResult.UNCHANGED -> Unit
}
}
}
private fun invalidatePendingStart() {
startRequestGate.invalidate()
pendingStartJob?.cancel()
pendingStartJob = null
}
private fun startTunnel(params: TunnelParams, fromTrustedWifiResume: Boolean = false) {
trustedWifiResumeRetryJob?.cancel()
trustedWifiResumeRetryJob = null
trustedWifiResumeRetryCount = 0
cancelTrustedWifiResumeRetry(resetCount = !fromTrustedWifiResume)
trustedWifiResumeInProgress = fromTrustedWifiResume
trustedWifiResumeStartedAt = if (fromTrustedWifiResume) System.currentTimeMillis() else 0L
trustedWifiWaiting = false
@@ -222,35 +370,48 @@ class TunnelService : Service() {
updateNotification("Подключение...")
acquireWakeLock()
acquireWifiLock()
releaseTrustedWifiTransitionWakeLock()
// Подготавливаем CaptchaWebViewManager (не создаёт WebView — просто сохраняет контекст)
// Вызываем всегда — дёшево, а WebView создаётся на лету при каждом запросе капчи
CaptchaWebViewManager.onTunnelStart(applicationContext)
TunnelManager.start(this, params)
if (fromTrustedWifiResume) {
TunnelManager.noteTrustedWifiEvent(
"resume_start",
"Рабочая сеть подтверждена — запускаем VPN после доверенной Wi-Fi."
)
}
TunnelManager.start(this, params, preserveLogs = fromTrustedWifiResume)
startNotificationProfileWatcher()
startStatsUpdater()
startActiveProfileRefresh(params.profileIndex)
}
private fun stopTunnel(reason: TunnelStopReason = TunnelStopReason.User) {
TunnelManager.noteStopRequested()
if (stopSequenceJob?.isActive == true) return
invalidatePendingStart()
val effectiveReason = requestedStopReason ?: reason
requestedStopReason = effectiveReason
updateJob?.cancel()
profileNameJob?.cancel()
activeProfileRefreshJob?.cancel()
networkChangeJob?.cancel()
wakeRescueJob?.cancel()
trustedWifiResumeRetryJob?.cancel()
cancelTrustedWifiResumeRetry(resetCount = true)
profileNameJob = null
activeProfileRefreshJob = null
networkChangeJob = null
wakeRescueJob = null
trustedWifiResumeRetryJob = null
trustedWifiResumeRetryCount = 0
trustedWifiResumeInProgress = false
trustedWifiResumeStartedAt = 0L
releaseTrustedWifiTransitionWakeLock()
cancelTrustedWifiEvaluations()
trustedWifiWaiting = false
trustedWifiWaitingSsid = ""
lastStartParams = null
forgetConnectionProfile()
TrustedWifiManager.clear()
TunnelManager.scope.launch {
SettingsStore(applicationContext).saveTrustedWifiWaiting(false)
@@ -259,30 +420,39 @@ class TunnelService : Service() {
// Уничтожаем текущий WebView (если капча решается) и чистим контекст
CaptchaWebViewManager.onTunnelStop()
TunnelManager.stop(effectiveReason)
releaseWakeLock()
releaseWifiLock()
lastValidatedNetwork = null
lastStableNetworkReconnectAt = 0L
stableNetworkWasLost = false
activeNetworks.clear()
trustedWifiValidatedNetworks.clear()
updateNotification("Отключение…")
// Служба должна жить до фактической остановки WireGuard и нативного клиента.
// Иначе быстрый повторный тап создаёт новую службу, пока прежний транспорт
// ещё завершается, а onDestroy ошибочно записывает системную остановку.
stopSequenceJob = serviceScope.launch {
try {
TunnelManager.stopAndWait(effectiveReason)
} finally {
intentionalStopCompleted = true
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
}
private fun startNotificationProfileWatcher() {
profileNameJob?.cancel()
val settingsStore = SettingsStore(applicationContext)
profileNameJob = TunnelManager.scope.launch(Dispatchers.Main) {
combine(
settingsStore.activeProfile,
settingsStore.profileNames
) { activeProfile, profileNames ->
val profile = activeProfile.coerceIn(0, 2)
val profile = connectionProfileIndex
?: settingsStore.activeTunnelProfile.first()
?: settingsStore.activeProfile.first().coerceIn(0, 2)
settingsStore.profileNames.collect { profileNames ->
val profileLabel = vpnProfileDisplayName(profile, profileNames)
"WDTT Plus · $profileLabel"
}.collect { prefix ->
notificationProfileTitle = prefix
notificationProfileTitle = "WDTT Plus · $profileLabel"
if (trustedWifiWaiting) {
updateTrustedWifiNotification()
} else if (TunnelManager.running.value && !isTunnelPaused) {
@@ -292,6 +462,50 @@ class TunnelService : Service() {
}
}
private fun startActiveProfileRefresh(profileIndex: Int) {
activeProfileRefreshJob?.cancel()
activeProfileRefreshJob = serviceScope.launch(Dispatchers.IO) {
while (isActive) {
delay(ACTIVE_PROFILE_REFRESH_INTERVAL_MS)
if (
connectionProfileIndex != profileIndex ||
!TunnelManager.running.value ||
isTunnelPaused ||
trustedWifiWaiting ||
TunnelManager.isCaptchaInProgress() ||
!hasAnyRealNetwork()
) {
continue
}
AccessLifecycleCoordinator.refreshProfile(
context = applicationContext,
profileIndex = profileIndex,
force = true,
)
}
}
}
private fun rememberConnectionProfile(profile: Int, persist: Boolean = true) {
val normalized = profile.coerceIn(0, 2)
connectionProfileIndex = normalized
TunnelManager.activeTunnelProfile.value = normalized
if (!persist) return
profileStateJob?.cancel()
profileStateJob = TunnelManager.scope.launch {
SettingsStore(applicationContext).saveActiveTunnelProfile(normalized)
}
}
private fun forgetConnectionProfile() {
connectionProfileIndex = null
TunnelManager.activeTunnelProfile.value = null
profileStateJob?.cancel()
profileStateJob = TunnelManager.scope.launch {
SettingsStore(applicationContext).saveActiveTunnelProfile(null)
}
}
private fun registerScreenStateReceiver() {
if (screenStateReceiver != null) return
screenStateReceiver = object : BroadcastReceiver() {
@@ -340,6 +554,8 @@ class TunnelService : Service() {
WifiManager.WIFI_STATE_DISABLING,
WifiManager.WIFI_STATE_DISABLED,
WifiManager.WIFI_STATE_UNKNOWN -> {
trustedWifiValidatedNetworks.forgetWifi()
acquireTrustedWifiTransitionWakeLock()
keepTrustedWifiForeground("Ожидание рабочей сети")
scheduleTrustedWifiEvaluation(delayMs = 0L)
scheduleTrustedWifiResumeRetry()
@@ -349,7 +565,9 @@ class TunnelService : Service() {
}
WifiManager.NETWORK_STATE_CHANGED_ACTION -> {
keepTrustedWifiForeground()
scheduleTrustedWifiEvaluation(delayMs = 0L)
// Сам broadcast не содержит стабильного Network-идентификатора:
// при быстрой смене двух Wi-Fi он может относиться уже к старой сети.
// Авторитетные lost/validated события придут через NetworkCallback.
}
}
}
@@ -382,13 +600,23 @@ class TunnelService : Service() {
return@launch
}
TunnelManager.noteWakeRescueReconnect()
updateNotification("Восстановление VPN...")
if (TunnelManager.isNetworkTransitionGraceActive()) {
updateNotification(buildTunnelNotificationText())
return@launch
}
val reconnectAt = System.currentTimeMillis()
TunnelManager.restartTransport(
val restarted = TunnelManager.restartTransport(
reason = "[СОН] После пробуждения VPN не подал признаков жизни. Мягко переподключаю транспорт.",
minIntervalMs = 60_000L
)
if (!restarted) {
// Другая ветка восстановления уже перезапускает транспорт либо ещё действует
// её защитный интервал. Не запускаем параллельный таймер, который мог бы
// ошибочно остановить уже восстанавливающийся VPN.
updateNotification(buildTunnelNotificationText())
return@launch
}
updateNotification("Восстановление VPN...")
delay(WAKE_RESCUE_FAIL_OPEN_MS)
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
@@ -447,17 +675,30 @@ class TunnelService : Service() {
}
trustedWifiNetworkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (trustedWifiWaiting) {
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS)
}
}
override fun onLost(network: Network) {
if (trustedWifiWaiting) {
trustedWifiValidatedNetworks.lost(network)
acquireTrustedWifiTransitionWakeLock()
scheduleTrustedWifiEvaluation(delayMs = 0L)
scheduleTrustedWifiResumeRetry()
} else {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS)
}
}
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
scheduleTrustedWifiEvaluation(
if (trustedWifiWaiting) TRUSTED_WIFI_EXIT_DELAY_MS else TRUSTED_WIFI_ENTER_DELAY_MS
)
if (trustedWifiWaiting) {
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS)
}
}
}
val request = NetworkRequest.Builder()
@@ -521,19 +762,41 @@ class TunnelService : Service() {
}
private fun scheduleTrustedWifiResumeRetry() {
trustedWifiResumeRetryJob?.cancel()
val delayMs = if (trustedWifiResumeRetryCount < TRUSTED_WIFI_FAST_RESUME_RETRY_COUNT) {
TRUSTED_WIFI_EXIT_DELAY_MS
synchronized(trustedWifiResumeRetryLock) {
if (trustedWifiResumeRetryJob?.isActive == true) return
val plan = trustedWifiResumeRetryPlan(trustedWifiResumeRetryCount)
if (plan.keepCpuAwake) {
acquireTrustedWifiTransitionWakeLock()
} else {
TRUSTED_WIFI_SLOW_RESUME_RETRY_MS
releaseTrustedWifiTransitionWakeLock()
}
trustedWifiResumeRetryCount += 1
trustedWifiResumeRetryJob = TunnelManager.scope.launch {
delay(delayMs)
delay(plan.delayMs)
val shouldEvaluate = synchronized(trustedWifiResumeRetryLock) {
trustedWifiResumeRetryJob = null
if (trustedWifiWaiting) {
evaluateTrustedWifiState()
trustedWifiResumeRetryCount += 1
true
} else {
false
}
}
if (shouldEvaluate) evaluateTrustedWifiState()
}
}
}
private fun cancelTrustedWifiResumeRetry(resetCount: Boolean) {
synchronized(trustedWifiResumeRetryLock) {
trustedWifiResumeRetryJob?.cancel()
trustedWifiResumeRetryJob = null
if (resetCount) trustedWifiResumeRetryCount = 0
}
}
private fun isTrustedWifiResumeRetryScheduled(): Boolean =
synchronized(trustedWifiResumeRetryLock) {
trustedWifiResumeRetryJob?.isActive == true
}
private suspend fun evaluateTrustedWifiState() {
@@ -581,6 +844,11 @@ class TunnelService : Service() {
TrustedWifiManager.setWaiting(wifi.ssid)
store.saveTrustedWifiWaiting(true, wifi.ssid)
withContext(Dispatchers.Main) { updateTrustedWifiNotification() }
cancelTrustedWifiResumeRetry(resetCount = true)
releaseTrustedWifiTransitionWakeLock()
}
if (trustedWifiWaiting && !isTrustedWifiResumeRetryScheduled()) {
releaseTrustedWifiTransitionWakeLock()
}
}
}
@@ -597,17 +865,26 @@ class TunnelService : Service() {
trustedWifiWaiting = true
trustedWifiWaitingSsid = cleanSsid
isTunnelPaused = false
trustedWifiResumeRetryCount = 0
trustedWifiValidatedNetworks.forgetWifi()
networkChangeJob?.cancel()
wakeRescueJob?.cancel()
trustedWifiResumeRetryJob?.cancel()
trustedWifiResumeRetryJob = null
activeProfileRefreshJob?.cancel()
activeProfileRefreshJob = null
cancelTrustedWifiResumeRetry(resetCount = true)
// Авто-WebView может ещё решать капчу, когда нативный процесс уже
// останавливается. Завершаем его до закрытия stdin клиента.
CaptchaWebViewManager.onTunnelStop()
TunnelManager.stopAndWait(TunnelStopReason.TrustedWifi)
WireGuardHelper(applicationContext).stopTunnel()
TunnelManager.noteTrustedWifiEvent(
"waiting_enter",
"Подключена доверенная сеть — VPN остановлен и ждёт выхода из неё."
)
TrustedWifiManager.setWaiting(cleanSsid)
SettingsStore(applicationContext).saveTrustedWifiWaiting(true, cleanSsid)
withContext(Dispatchers.Main) {
releaseTrustedWifiTransitionWakeLock()
releaseWakeLock()
releaseWifiLock()
startNotificationProfileWatcher()
@@ -623,6 +900,10 @@ class TunnelService : Service() {
if (!trustedWifiWaiting) return
if (!hasUsableRealNetworkForTrustedWifiResume()) {
val status = "Ожидание рабочей сети"
TunnelManager.noteTrustedWifiEvent(
"resume_wait_network",
"Wi-Fi покинута, но Android ещё не подтвердил рабочую сеть; повторяем проверку."
)
TrustedWifiManager.setStatus(status)
withContext(Dispatchers.Main) {
keepTrustedWifiForeground(status)
@@ -633,6 +914,12 @@ class TunnelService : Service() {
}
if (android.net.VpnService.prepare(applicationContext) != null) {
val status = "VPN-разрешение недоступно. Откройте WDTT Plus для восстановления."
releaseTrustedWifiTransitionWakeLock()
TunnelManager.noteTrustedWifiEvent(
"resume_permission",
"Android не дал повторно занять VPN-слот; требуется открыть приложение.",
warning = true
)
TrustedWifiManager.setStatus(status)
withContext(Dispatchers.Main) { updateNotification(status) }
return
@@ -641,17 +928,54 @@ class TunnelService : Service() {
val params = lastStartParams ?: buildTunnelParamsFromSettings(applicationContext)
if (params == null) {
val status = "Не удалось прочитать профиль VPN. Откройте WDTT Plus."
releaseTrustedWifiTransitionWakeLock()
TunnelManager.noteTrustedWifiEvent(
"resume_profile",
"Не удалось прочитать профиль для автоматического запуска.",
warning = true
)
TrustedWifiManager.setStatus(status)
withContext(Dispatchers.Main) { updateNotification(status) }
return
}
val access = AccessLifecycleCoordinator.prepareStart(
applicationContext,
params.profileIndex,
)
if (access is AccessStartDecision.Denied) {
withContext(Dispatchers.Main) {
reportAccessDenied(access.status)
stopTunnel(TunnelStopReason.AccessExpired)
}
return
}
val refreshedParams = buildTunnelParamsFromSettings(
applicationContext,
params.profileIndex,
)
if (refreshedParams == null) {
val status = "Не удалось прочитать обновлённый профиль VPN. Откройте WDTT Plus."
releaseTrustedWifiTransitionWakeLock()
TunnelManager.noteTrustedWifiEvent(
"resume_profile_refresh",
"Не удалось повторно прочитать профиль после проверки перед запуском.",
warning = true,
)
TrustedWifiManager.setStatus(status)
withContext(Dispatchers.Main) { updateNotification(status) }
return
}
lastStartParams = refreshedParams
withContext(Dispatchers.Main) {
acquireTrustedWifiTransitionWakeLock()
Log.i("TunnelService", "Доверенная Wi-Fi покинута, запускаем VPN на рабочей сети")
// startTunnel синхронно включает защитный resumeInProgress до снятия waiting.
// Поэтому очередной сетевой callback уже не может оставить сервис между
// состояниями: без VPN, без ожидания и с удалённым уведомлением.
startTunnel(params, fromTrustedWifiResume = true)
startTunnel(refreshedParams, fromTrustedWifiResume = true)
VpnWidgetProvider.updateAllWidgets(applicationContext)
}
}
@@ -661,6 +985,23 @@ class TunnelService : Service() {
keepTrustedWifiForeground()
}
private fun reportAccessDenied(status: AccessLifecycleStatus) {
val title = status.title.ifBlank { "Профиль временно недоступен" }
val message = status.message.ifBlank {
"Откройте вкладку «Туннель», чтобы проверить доступные действия."
}
TunnelManager.reportConnectionIssue(
title,
message,
kind = ConnectionIssueKind.ACCESS,
)
TunnelManager.noteAccessLifecycleEvent(
key = "start_denied",
message = title,
warning = true,
)
}
private fun keepTrustedWifiForeground(statusOverride: String? = null) {
val networkName = trustedWifiWaitingSsid.ifBlank { "доверенная Wi-Fi" }
val text = statusOverride ?: "VPN выключен в сети «$networkName» · ожидание выхода"
@@ -673,6 +1014,7 @@ class TunnelService : Service() {
private fun setupNetworkCallback() {
connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
activeNetworks.clear()
trustedWifiValidatedNetworks.clear()
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
@@ -698,10 +1040,13 @@ class TunnelService : Service() {
override fun onLost(network: Network) {
super.onLost(network)
if (trustedWifiWaiting) {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS)
}
activeNetworks.remove(network)
trustedWifiValidatedNetworks.lost(network)
if (trustedWifiWaiting) {
acquireTrustedWifiTransitionWakeLock()
scheduleTrustedWifiEvaluation(delayMs = 0L)
scheduleTrustedWifiResumeRetry()
}
if (AMNEZIA_STYLE_RECOVERY) {
if (lastValidatedNetwork == network) {
lastValidatedNetwork = null
@@ -726,9 +1071,23 @@ class TunnelService : Service() {
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities)
val usableRealNetwork =
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
trustedWifiValidatedNetworks.update(
network = network,
validated = usableRealNetwork,
wifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
)
if (trustedWifiWaiting) {
if (usableRealNetwork) {
acquireTrustedWifiTransitionWakeLock()
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS)
}
}
if (AMNEZIA_STYLE_RECOVERY) {
handleStableNetworkCapabilities(network, networkCapabilities)
return
@@ -772,7 +1131,9 @@ class TunnelService : Service() {
if (TunnelManager.running.value) {
TunnelManager.noteUnderlyingNetworkChanged(
"Android подтвердил рабочую сеть",
graceMs = STABLE_NETWORK_RECONNECT_DELAY_MS,
graceMs = transportRecoveryPolicy(
lastStartParams?.managedConfigFirstStart == true
).networkSettleDelayMs,
replaceGrace = false
)
}
@@ -789,27 +1150,31 @@ class TunnelService : Service() {
lastNetworkChangeTime = now
if (!TunnelManager.running.value || isTunnelPaused) return
val recoveryPolicy = transportRecoveryPolicy(
lastStartParams?.managedConfigFirstStart == true
)
TunnelManager.noteUnderlyingNetworkChanged(
reason,
graceMs = STABLE_NETWORK_RECONNECT_DELAY_MS + 30_000L,
graceMs = recoveryPolicy.networkSettleDelayMs + 30_000L,
replaceGrace = true
)
networkChangeJob?.cancel()
networkChangeJob = TunnelManager.scope.launch(Dispatchers.Main) {
Log.d("TunnelService", "$reason, ждём короткую стабилизацию перед reconnect")
delay(STABLE_NETWORK_RECONNECT_DELAY_MS)
delay(recoveryPolicy.networkSettleDelayMs)
if (lastNetworkChangeTime != now) return@launch
if (!TunnelManager.running.value || !hasAnyRealNetwork() || TunnelManager.isCaptchaInProgress()) return@launch
val sinceLastReconnect = System.currentTimeMillis() - lastStableNetworkReconnectAt
if (sinceLastReconnect < STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS) {
if (sinceLastReconnect < recoveryPolicy.reconnectMinIntervalMs) {
Log.d("TunnelService", "Пропускаем reconnect: недавний reconnect уже был")
return@launch
}
lastStableNetworkReconnectAt = System.currentTimeMillis()
TunnelManager.restartTransport(
reason = "[СЕТЬ] Android подтвердил новую сеть. Мягко переподключаю транспорт.",
minIntervalMs = STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS
minIntervalMs = recoveryPolicy.reconnectMinIntervalMs,
force = recoveryPolicy.forceRestart,
)
}
}
@@ -827,16 +1192,7 @@ class TunnelService : Service() {
@Suppress("DEPRECATION")
private fun hasUsableRealNetworkForTrustedWifiResume(): Boolean {
val cm = connectivityManager
?: (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).also {
connectivityManager = it
}
return cm.allNetworks.any { network ->
val caps = cm.getNetworkCapabilities(network) ?: return@any false
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
return trustedWifiValidatedNetworks.hasUsableNetwork()
}
private fun scheduleNetworkSettleCheck(
@@ -925,6 +1281,37 @@ class TunnelService : Service() {
}
}
@Synchronized
private fun acquireTrustedWifiTransitionWakeLock() {
val lock = trustedWifiTransitionWakeLock ?: run {
val pm = getSystemService(POWER_SERVICE) as PowerManager
pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"wdtt:trusted_wifi_transition"
).apply {
setReferenceCounted(false)
trustedWifiTransitionWakeLock = this
}
}
runCatching {
if (!lock.isHeld) {
lock.acquire(TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS)
}
}.onFailure {
Log.w("TunnelService", "Не удалось удержать CPU для выхода из доверенной Wi-Fi: ${it.message}")
}
}
@Synchronized
private fun releaseTrustedWifiTransitionWakeLock() {
trustedWifiTransitionWakeLock?.let { lock ->
runCatching {
if (lock.isHeld) lock.release()
}
}
trustedWifiTransitionWakeLock = null
}
@Suppress("DEPRECATION")
private fun acquireWifiLock() {
if (wifiLock?.isHeld == true) return
@@ -968,6 +1355,8 @@ class TunnelService : Service() {
TunnelManager.running.value -> {
trustedWifiResumeInProgress = false
trustedWifiResumeStartedAt = 0L
cancelTrustedWifiResumeRetry(resetCount = true)
releaseTrustedWifiTransitionWakeLock()
}
trustedWifiResumeStartedAt > 0L &&
System.currentTimeMillis() - trustedWifiResumeStartedAt >=
@@ -977,6 +1366,15 @@ class TunnelService : Service() {
trustedWifiWaiting = true
val status = "VPN не запустился, повторяем восстановление"
Log.w("TunnelService", status)
CaptchaWebViewManager.onTunnelStop()
releaseWakeLock()
releaseWifiLock()
acquireTrustedWifiTransitionWakeLock()
TunnelManager.noteTrustedWifiEvent(
"resume_timeout",
"Автоматический запуск не начался за 30 секунд; повторяем.",
warning = true
)
TrustedWifiManager.setWaiting("", status)
SettingsStore(applicationContext).saveTrustedWifiWaiting(true)
keepTrustedWifiForeground(status)
@@ -1169,6 +1567,10 @@ class TunnelService : Service() {
override fun onDestroy() {
super.onDestroy()
val stopReasonOnUnexpectedDestroy = requestedStopReason ?: TunnelStopReason.ServiceDestroyed
val stopWasCompleted = intentionalStopCompleted
invalidatePendingStart()
serviceScope.cancel()
wakeRescueJob?.cancel()
networkChangeJob?.cancel()
screenStateReceiver?.let {
@@ -1187,13 +1589,17 @@ class TunnelService : Service() {
}
trustedWifiSettingsJob?.cancel()
cancelTrustedWifiEvaluations()
trustedWifiResumeRetryJob?.cancel()
cancelTrustedWifiResumeRetry(resetCount = false)
releaseTrustedWifiTransitionWakeLock()
if (trustedWifiWaiting || trustedWifiResumeInProgress) {
releaseWakeLock()
releaseWifiLock()
TrustedWifiManager.setStatus("Служба ожидания будет восстановлена Android")
} else {
stopTunnel(TunnelStopReason.ServiceDestroyed)
} else if (!stopWasCompleted) {
CaptchaWebViewManager.onTunnelStop()
releaseWakeLock()
releaseWifiLock()
TunnelManager.stop(stopReasonOnUnexpectedDestroy)
}
}
@@ -2,62 +2,141 @@ package com.wdtt.plus
import android.content.Context
import android.content.Intent
import kotlinx.coroutines.flow.first
suspend fun buildTunnelParamsFromSettings(context: Context): TunnelParams? {
internal const val TUNNEL_PROFILE_INDEX_EXTRA = "profile_index"
internal const val MANAGED_CONFIG_FIRST_START_EXTRA = "managed_config_first_start"
internal data class TransportRecoveryPolicy(
val networkSettleDelayMs: Long,
val reconnectMinIntervalMs: Long,
val processRestartDelayMs: Long,
val forceRestart: Boolean,
)
internal fun transportRecoveryPolicy(
managedConfigFirstStart: Boolean,
): TransportRecoveryPolicy = if (managedConfigFirstStart) {
TransportRecoveryPolicy(
networkSettleDelayMs = 3_000L,
reconnectMinIntervalMs = 8_000L,
processRestartDelayMs = 250L,
forceRestart = true,
)
} else {
TransportRecoveryPolicy(
networkSettleDelayMs = 15_000L,
reconnectMinIntervalMs = 2 * 60_000L,
processRestartDelayMs = 2_500L,
forceRestart = false,
)
}
internal enum class TunnelToggleAction {
START,
STOP,
REQUEST_VPN_PERMISSION,
}
internal fun tunnelToggleAction(
running: Boolean,
trustedWifiWaiting: Boolean,
vpnPermissionRequired: Boolean,
): TunnelToggleAction = when {
running || trustedWifiWaiting -> TunnelToggleAction.STOP
vpnPermissionRequired -> TunnelToggleAction.REQUEST_VPN_PERMISSION
else -> TunnelToggleAction.START
}
internal fun displayedTunnelProfile(
selectedProfile: Int,
activeTunnelProfile: Int?,
running: Boolean,
trustedWifiWaiting: Boolean,
): Int = if (running || trustedWifiWaiting) {
activeTunnelProfile ?: selectedProfile
} else {
selectedProfile
}.coerceIn(0, 2)
internal fun shouldUseManagedConfigFirstStart(
remoteManaged: Boolean,
profileMaxWorkers: Int,
): Boolean = remoteManaged && profileMaxWorkers == TUNNEL_WORKERS_PER_GROUP
suspend fun buildTunnelParamsFromSettings(
context: Context,
profileIndex: Int? = null,
): TunnelParams? {
val store = SettingsStore(context.applicationContext)
val linkMode = store.wdttLinkMode.first()
val workersPerHash = store.workersPerHash.first()
val sni = store.sni.first()
val protocol = store.protocol.first()
val vkCallsPreflight = store.vkCallsPreflight.first()
val captchaMode = sanitizeTunnelCaptchaMode(store.captchaMode.first())
val captchaSolveMethod = store.captchaSolveMethod.first()
val fingerprint = store.selectedFingerprint.first()
val clientIds = store.activeClientIds.first()
val saved = store.tunnelProfileSnapshot(profileIndex)
return buildTunnelParams(saved)
}
return if (linkMode) {
val parts = WdttDeepLink.validate(store.wdttLink.first()).parts ?: return null
internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
val workersPerHash = normalizeTunnelWorkerCount(
saved.workersPerHash,
saved.profileMaxWorkers
)
val managedConfigFirstStart = shouldUseManagedConfigFirstStart(
remoteManaged = saved.remoteManaged,
profileMaxWorkers = saved.profileMaxWorkers,
)
val linkParts = saved.link
.takeIf { saved.linkMode }
?.let { WdttDeepLink.validate(it).parts }
return if (linkParts != null) {
TunnelParams(
peer = "${parts.host}:${parts.dtlsPort}",
vkHashes = parts.hashes,
peer = "${linkParts.host}:${linkParts.dtlsPort}",
vkHashes = linkParts.hashes,
secondaryVkHash = "",
workersPerHash = workersPerHash,
port = parts.localPort,
sni = sni,
connectionPassword = parts.password,
protocol = protocol,
vkCallsPreflight = vkCallsPreflight,
captchaMode = captchaMode,
captchaSolveMethod = captchaSolveMethod,
fingerprint = fingerprint,
clientIds = clientIds
port = linkParts.localPort,
sni = saved.sni,
connectionPassword = linkParts.password,
protocol = saved.protocol,
vkCallsPreflight = saved.vkCallsPreflight,
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
captchaSolveMethod = saved.captchaSolveMethod,
fingerprint = saved.fingerprint,
clientIds = saved.clientIds,
customVkCredentialsEnabled = saved.customVkCredentialsEnabled,
customVkClientId = saved.customVkClientId,
customVkClientSecret = saved.customVkClientSecret,
profileMaxWorkers = saved.profileMaxWorkers,
managedConfigFirstStart = managedConfigFirstStart,
profileIndex = saved.profileIndex,
)
} else {
val basePeer = store.peer.first().trim()
val hashes = store.vkHashes.first().trim()
val password = store.connectionPassword.first()
val basePeer = saved.peer.trim()
val hashes = saved.vkHashes.trim()
val password = saved.connectionPassword
if (basePeer.isBlank() || hashes.isBlank() || password.isBlank()) return null
val manualPortsEnabled = store.manualPortsEnabled.first()
val serverDtlsPort = if (manualPortsEnabled) store.serverDtlsPort.first() else 56000
val localPort = if (manualPortsEnabled) store.listenPort.first() else 9000
val serverDtlsPort = if (saved.manualPortsEnabled) saved.serverDtlsPort else 56000
val localPort = if (saved.manualPortsEnabled) saved.listenPort else 9000
val peerWithPort = if (basePeer.contains(":")) basePeer else "$basePeer:$serverDtlsPort"
TunnelParams(
peer = peerWithPort,
vkHashes = hashes,
secondaryVkHash = store.secondaryVkHash.first(),
secondaryVkHash = saved.secondaryVkHash,
workersPerHash = workersPerHash,
port = localPort,
sni = sni,
sni = saved.sni,
connectionPassword = password,
protocol = protocol,
vkCallsPreflight = vkCallsPreflight,
captchaMode = captchaMode,
captchaSolveMethod = captchaSolveMethod,
fingerprint = fingerprint,
clientIds = clientIds
protocol = saved.protocol,
vkCallsPreflight = saved.vkCallsPreflight,
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
captchaSolveMethod = saved.captchaSolveMethod,
fingerprint = saved.fingerprint,
clientIds = saved.clientIds,
customVkCredentialsEnabled = saved.customVkCredentialsEnabled,
customVkClientId = saved.customVkClientId,
customVkClientSecret = saved.customVkClientSecret,
profileMaxWorkers = saved.profileMaxWorkers,
managedConfigFirstStart = managedConfigFirstStart,
profileIndex = saved.profileIndex,
)
}
}
@@ -79,6 +158,12 @@ suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? {
putExtra("captcha_solve_method", params.captchaSolveMethod)
putExtra("fingerprint", params.fingerprint)
putExtra("client_ids", params.clientIds)
putExtra("custom_vk_credentials_enabled", params.customVkCredentialsEnabled)
putExtra("custom_vk_client_id", params.customVkClientId)
putExtra("custom_vk_client_secret", params.customVkClientSecret)
putExtra("profile_max_workers", params.profileMaxWorkers)
putExtra(MANAGED_CONFIG_FIRST_START_EXTRA, params.managedConfigFirstStart)
putExtra(TUNNEL_PROFILE_INDEX_EXTRA, params.profileIndex)
}
}
@@ -0,0 +1,20 @@
package com.wdtt.plus
/** Keeps delayed service starts from reviving an obsolete or explicitly stopped request. */
internal class TunnelStartRequestGate {
private var generation: Long = 0
@Synchronized
fun next(): Long {
generation += 1
return generation
}
@Synchronized
fun invalidate() {
generation += 1
}
@Synchronized
fun isCurrent(value: Long): Boolean = value == generation
}
@@ -0,0 +1,61 @@
package com.wdtt.plus
import android.content.Context
import android.content.Intent
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
enum class TunnelStopResult {
ALREADY_STOPPED,
STOPPED,
TIMED_OUT,
FAILED;
val succeeded: Boolean
get() = this == ALREADY_STOPPED || this == STOPPED
}
object TunnelStopCoordinator {
const val DEFAULT_TIMEOUT_MS = 20_000L
const val DIRECT_NETWORK_SETTLE_MS = 1_000L
suspend fun stopAndAwait(
context: Context,
timeoutMs: Long = DEFAULT_TIMEOUT_MS,
): TunnelStopResult {
val appContext = context.applicationContext
val helper = WireGuardHelper(appContext)
val managerActive = TunnelManager.running.value ||
TunnelManager.transition.value != TunnelTransition.IDLE
val wireGuardActive = runCatching { helper.isTunnelUp() }.getOrDefault(false)
if (!managerActive && !wireGuardActive) return TunnelStopResult.ALREADY_STOPPED
val serviceRequested = runCatching {
appContext.startService(
Intent(appContext, TunnelService::class.java).apply { action = "STOP" }
)
}.isSuccess
if (!serviceRequested) return TunnelStopResult.FAILED
val stopped = withTimeoutOrNull(timeoutMs.coerceAtLeast(1_000L)) {
// The service owns foreground/lifecycle cleanup. Calling the manager as well makes
// this operation awaitable and repairs a stale `running=false` state with a live
// WireGuard tunnel. Both paths are idempotent behind the same start/stop mutex.
TunnelManager.stopAndWait(
reason = TunnelStopReason.User,
context = appContext,
forceVpnRelease = true,
)
while (
TunnelManager.running.value ||
TunnelManager.transition.value != TunnelTransition.IDLE ||
helper.isTunnelUp()
) {
delay(50L)
}
true
} == true
return if (stopped) TunnelStopResult.STOPPED else TunnelStopResult.TIMED_OUT
}
}
@@ -0,0 +1,14 @@
package com.wdtt.plus
internal const val TUNNEL_WORKERS_PER_GROUP = 9
internal const val APP_MAX_WORKERS = 108
internal fun normalizeTunnelWorkerCount(requested: Int, profileMaxWorkers: Int = 0): Int {
val configuredMaximum = (profileMaxWorkers / TUNNEL_WORKERS_PER_GROUP) * TUNNEL_WORKERS_PER_GROUP
val maximum = configuredMaximum.takeIf { it >= TUNNEL_WORKERS_PER_GROUP }
?.coerceAtMost(APP_MAX_WORKERS)
?: APP_MAX_WORKERS
val rounded = ((requested.coerceAtLeast(TUNNEL_WORKERS_PER_GROUP) + TUNNEL_WORKERS_PER_GROUP / 2) /
TUNNEL_WORKERS_PER_GROUP) * TUNNEL_WORKERS_PER_GROUP
return rounded.coerceIn(TUNNEL_WORKERS_PER_GROUP, maximum)
}
@@ -0,0 +1,30 @@
package com.wdtt.plus
const val DEFAULT_VK_CLIENT_IDS = "6287487,8202606"
val BUILT_IN_VK_CLIENT_IDS: List<String> = DEFAULT_VK_CLIENT_IDS.split(',')
data class CustomVkClientCredentials(
val enabled: Boolean = false,
val clientId: String = "",
val clientSecret: String = ""
) {
val complete: Boolean
get() = isValidVkClientId(clientId) && clientSecret.isNotBlank()
}
fun normalizeVkClientId(value: String): String =
value.filter(Char::isDigit).take(20)
fun normalizeVkClientSecret(value: String): String =
value.trim().take(512)
fun isValidVkClientId(value: String): Boolean =
value.isNotBlank() && value.length <= 20 && value.all(Char::isDigit)
fun customVkCredentialsError(credentials: CustomVkClientCredentials): String? = when {
!credentials.enabled -> null
!isValidVkClientId(credentials.clientId) -> "Укажите числовой Client ID приложения VK."
credentials.clientSecret.isBlank() -> "Укажите защищённый ключ (Client secret) приложения VK."
else -> null
}
+28 -1
View File
@@ -1,6 +1,8 @@
package com.wdtt.plus
object VkJoinLink {
private val hashPattern = Regex("^[A-Za-z0-9_-]{1,512}$")
fun extractHash(input: String): String {
var s = input.trim().trim('<', '>', '"', '\'')
if (s.isBlank()) return ""
@@ -20,5 +22,30 @@ object VkJoinLink {
}
return s.trim().trimEnd('/')
}
}
fun isValidHash(value: String): Boolean = hashPattern.matches(value.trim())
fun isValidInput(input: String): Boolean {
val clean = input.trim().trim('<', '>', '"', '\'')
if (clean.isBlank()) return false
val isLink = clean.startsWith("http://", ignoreCase = true) ||
clean.startsWith("https://", ignoreCase = true)
return if (isLink) {
clean.contains("/call/join/", ignoreCase = true) &&
isValidHash(extractHash(clean))
} else {
isValidHash(clean)
}
}
fun normalizeHashes(input: String): String? {
if (input.isBlank()) return ""
val values = input.split(Regex("[,\\s]+"))
.filter { it.isNotBlank() }
if (values.isEmpty() || values.any { !isValidInput(it) }) return null
return values.map(::extractHash).distinct().joinToString(",")
}
fun extractValidHash(input: String): String =
extractHash(input).takeIf { isValidInput(input) }.orEmpty()
}
@@ -43,9 +43,24 @@ class VpnCompactWidgetProvider : AppWidgetProvider() {
val waiting = TrustedWifiManager.state.value.waiting
scope.launch {
val settingsStore = SettingsStore(context)
val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2)
val selectedProfile = settingsStore.activeProfile.first().coerceIn(0, 2)
val activeTunnelProfile = TunnelManager.activeTunnelProfile.value
?: settingsStore.activeTunnelProfile.first()
val displayedProfile = displayedTunnelProfile(
selectedProfile = selectedProfile,
activeTunnelProfile = activeTunnelProfile,
running = running,
trustedWifiWaiting = waiting,
)
val profileNames = settingsStore.profileNames.first()
val profileName = vpnProfileDisplayName(activeProfile, profileNames)
val profileName = vpnProfileDisplayName(displayedProfile, profileNames)
val accessLifecycle =
settingsStore.accessLifecycleForProfile(displayedProfile).toUiState()
val accessBlocked =
accessLifecycle.managed &&
!accessLifecycle.allowConnect &&
!running &&
!waiting
appWidgetIds.forEach { appWidgetId ->
val views = RemoteViews(context.packageName, R.layout.vpn_widget_compact)
@@ -56,7 +71,12 @@ class VpnCompactWidgetProvider : AppWidgetProvider() {
)
views.setTextViewText(
R.id.compact_widget_profile,
if (waiting) "Ожидание" else profileName
when {
waiting -> "Ожидание"
accessBlocked ->
accessLifecycle.title.ifBlank { accessLifecycle.fallbackTitle() }
else -> profileName
}
)
val toggleIntent = Intent(context, VpnWidgetProvider::class.java).apply {
@@ -45,8 +45,18 @@ class VpnWidgetProvider : AppWidgetProvider() {
val trustedWifi = TrustedWifiManager.state.value
scope.launch {
val settingsStore = SettingsStore(context)
val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2)
val selectedProfile = settingsStore.activeProfile.first().coerceIn(0, 2)
val activeTunnelProfile = TunnelManager.activeTunnelProfile.value
?: settingsStore.activeTunnelProfile.first()
val displayedProfile = displayedTunnelProfile(
selectedProfile = selectedProfile,
activeTunnelProfile = activeTunnelProfile,
running = running,
trustedWifiWaiting = trustedWifi.waiting,
)
val profileNames = settingsStore.profileNames.first()
val accessLifecycle =
settingsStore.accessLifecycleForProfile(displayedProfile).toUiState()
for (appWidgetId in appWidgetIds) {
updateWidgetState(
context = context,
@@ -54,8 +64,9 @@ class VpnWidgetProvider : AppWidgetProvider() {
appWidgetId = appWidgetId,
running = running,
trustedWifi = trustedWifi,
activeProfile = activeProfile,
profileNames = profileNames
activeProfile = displayedProfile,
profileNames = profileNames,
accessLifecycle = accessLifecycle,
)
}
}
@@ -65,26 +76,36 @@ class VpnWidgetProvider : AppWidgetProvider() {
super.onReceive(context, intent)
if (intent.action == ACTION_WIDGET_TOGGLE) {
runCatching {
if (TunnelManager.running.value || TrustedWifiManager.state.value.waiting) {
// Останавливаем туннель
val stopIntent = Intent(context, TunnelService::class.java).apply { action = "STOP" }
context.startService(stopIntent)
when (
tunnelToggleAction(
running = TunnelManager.running.value,
trustedWifiWaiting = TrustedWifiManager.state.value.waiting,
vpnPermissionRequired = VpnService.prepare(context) != null,
)
) {
TunnelToggleAction.STOP -> {
context.startService(
Intent(context, TunnelService::class.java).apply { action = "STOP" }
)
updateAllWidgets(context)
return
}
if (VpnService.prepare(context) != null) {
Toast.makeText(context, "Откройте WDTT Plus и выдайте VPN-разрешение", Toast.LENGTH_LONG).show()
TunnelToggleAction.REQUEST_VPN_PERMISSION -> {
Toast.makeText(
context,
"Откройте WDTT Plus и выдайте VPN-разрешение",
Toast.LENGTH_LONG
).show()
openMainActivity(context)
return
}
// Запуск туннеля в фоне
scope.launch {
TunnelToggleAction.START -> scope.launch {
try {
val startIntent = buildTunnelStartIntentFromSettings(context)
if (startIntent == null) {
Toast.makeText(context, "Заполните настройки подключения в WDTT Plus", Toast.LENGTH_LONG).show()
Toast.makeText(
context,
"Заполните настройки подключения в WDTT Plus",
Toast.LENGTH_LONG
).show()
openMainActivity(context)
return@launch
}
@@ -96,7 +117,12 @@ class VpnWidgetProvider : AppWidgetProvider() {
}
} catch (e: Exception) {
Log.e("VpnWidget", "Failed to start tunnel from widget", e)
Toast.makeText(context, "Ошибка запуска: ${e.localizedMessage}", Toast.LENGTH_SHORT).show()
Toast.makeText(
context,
"Ошибка запуска: ${e.localizedMessage}",
Toast.LENGTH_SHORT
).show()
}
}
}
}.onFailure { e ->
@@ -112,7 +138,8 @@ class VpnWidgetProvider : AppWidgetProvider() {
running: Boolean,
trustedWifi: TrustedWifiRuntimeState,
activeProfile: Int,
profileNames: List<String>
profileNames: List<String>,
accessLifecycle: AccessLifecycleUiState,
) {
val views = RemoteViews(context.packageName, R.layout.vpn_widget)
@@ -129,8 +156,24 @@ class VpnWidgetProvider : AppWidgetProvider() {
views.setTextColor(R.id.widget_status, 0xFF00E5FF.toInt()) // Неоновый голубой
views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_active)
} else {
views.setTextViewText(R.id.widget_status, "Отключено")
views.setTextColor(R.id.widget_status, 0xFF888888.toInt()) // Матовый серый
val accessBlocked = accessLifecycle.managed && !accessLifecycle.allowConnect
views.setTextViewText(
R.id.widget_status,
accessLifecycle.title.takeIf { accessBlocked && it.isNotBlank() }
?: accessLifecycle.fallbackTitle().takeIf { accessBlocked }
?: "Отключено"
)
views.setTextColor(
R.id.widget_status,
if (
accessLifecycle.severity == AccessLifecycleSeverity.ERROR &&
accessBlocked
) {
0xFFFF6B6B.toInt()
} else {
0xFF888888.toInt()
}
)
views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_inactive)
}
@@ -37,6 +37,12 @@ class WdttApplication : Application() {
}
val settingsStore = SettingsStore(this)
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
RemoteActionCatalogGateway.fetch(force = true)
}
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
AccessLifecycleCoordinator.refreshAllIfStale(this@WdttApplication)
}
// Реактивно обновляем виджеты при изменении туннеля, активного профиля или его названия.
CoroutineScope(SupervisorJob() + Dispatchers.Main).launch {
@@ -45,8 +51,9 @@ class WdttApplication : Application() {
TunnelManager.running,
TrustedWifiManager.state,
settingsStore.activeProfile,
settingsStore.profileNames
) { _, _, _, _ -> Unit }.collect {
settingsStore.profileNames,
settingsStore.activeAccessLifecycle
) { _, _, _, _, _ -> Unit }.collect {
VpnWidgetProvider.updateAllWidgets(this@WdttApplication)
}
} catch (e: Exception) {
@@ -0,0 +1,28 @@
package com.wdtt.plus
object WdttDocument {
const val MIME_TYPE = "application/vnd.wdtt.plus"
const val FILE_EXTENSION = ".wdtt"
const val LEGACY_TRANSFER_MIME_TYPE = "application/vnd.wdtt.plus.transfer"
const val LEGACY_CLIENT_MIME_TYPE = "application/vnd.wdtt.plus.client"
fun acceptedMimeTypes(): Array<String> = arrayOf(
MIME_TYPE,
LEGACY_TRANSFER_MIME_TYPE,
LEGACY_CLIENT_MIME_TYPE,
"application/json",
"application/octet-stream",
"text/plain",
)
fun isAcceptedMimeType(value: String?): Boolean {
val normalized = value?.substringBefore(';')?.trim()?.lowercase().orEmpty()
return acceptedMimeTypes().any { it == normalized }
}
fun fileName(stem: String): String {
val cleanStem = stem.trim().removeSuffix(FILE_EXTENSION).ifBlank { "WDTT-Plus" }
return cleanStem + FILE_EXTENSION
}
}
@@ -16,6 +16,7 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.io.ByteArrayInputStream
import java.security.MessageDigest
class WireGuardHelper(context: Context) {
private val appContext = context.applicationContext
@@ -24,6 +25,7 @@ class WireGuardHelper(context: Context) {
private companion object {
val wgMutex = Mutex()
var sharedTunnel: WgTunnel? = null
var sharedConfigFingerprint: String? = null
}
class WgTunnel(
@@ -38,6 +40,7 @@ class WireGuardHelper(context: Context) {
val isCurrentTunnel = sharedTunnel === this
if (isCurrentTunnel) {
sharedTunnel = null
sharedConfigFingerprint = null
}
if (isCurrentTunnel && !suppressDownCallback) {
onExternalDown?.invoke()
@@ -55,19 +58,6 @@ class WireGuardHelper(context: Context) {
throw IllegalStateException("VPN-разрешение не выдано")
}
ensureGoBackendServiceStarted()
sharedTunnel?.let { existingTunnel ->
try {
existingTunnel.suppressDownCallback = true
backend.setState(existingTunnel, Tunnel.State.DOWN, null)
} catch (e: Exception) {
Log.w("WG", "Failed to stop previous tunnel before restart: ${e.readableMessage()}")
}
sharedTunnel = null
delay(150)
}
val parsedConfig = Config.parse(ByteArrayInputStream(configString.toByteArray(Charsets.UTF_8)))
val builder = Interface.Builder()
@@ -132,11 +122,42 @@ class WireGuardHelper(context: Context) {
.addPeer(peerBuilder.build())
.build()
sharedTunnel?.let { existingTunnel ->
val existingUp = runCatching {
backend.getState(existingTunnel) == Tunnel.State.UP
}.getOrDefault(false)
if (
shouldReuseRunningWireGuard(
tunnelUp = existingUp,
currentConfigFingerprint = sharedConfigFingerprint,
updatedConfig = finalConfig,
)
) {
Log.d("WG", "WireGuard config unchanged; keeping the current VPN interface")
return@withContext
}
}
ensureGoBackendServiceStarted()
sharedTunnel?.let { existingTunnel ->
try {
existingTunnel.suppressDownCallback = true
backend.setState(existingTunnel, Tunnel.State.DOWN, null)
} catch (e: Exception) {
Log.w("WG", "Failed to stop previous tunnel before restart: ${e.readableMessage()}")
}
sharedTunnel = null
sharedConfigFingerprint = null
delay(150)
}
val nextTunnel = WgTunnel {
TunnelManager.onWireGuardStoppedExternally()
}
setTunnelUpWithRetry(nextTunnel, finalConfig)
sharedTunnel = nextTunnel
sharedConfigFingerprint = wireGuardConfigFingerprint(finalConfig)
Log.d("WG", "WireGuard tunnel started successfully")
} catch (e: Exception) {
val detailed = "WireGuard start failed: ${e.readableMessage()}; ${configString.describeWireGuardConfig()}"
@@ -154,6 +175,7 @@ class WireGuardHelper(context: Context) {
currentTunnel.suppressDownCallback = true
backend.setState(currentTunnel, Tunnel.State.DOWN, null)
sharedTunnel = null
sharedConfigFingerprint = null
delay(150)
startTunnelLocked(configFlow)
Log.d("WG", "WireGuard tunnel reloaded for new exceptions")
@@ -179,6 +201,7 @@ class WireGuardHelper(context: Context) {
it.suppressDownCallback = true
backend.setState(it, Tunnel.State.DOWN, null)
sharedTunnel = null
sharedConfigFingerprint = null
Log.d("WG", "WireGuard tunnel stopped")
}
} catch (e: Exception) {
@@ -236,3 +259,17 @@ class WireGuardHelper(context: Context) {
return "config lines=${lines.size}, interface=$hasInterface, peer=$hasPeer, privateKey=$hasPrivateKey, publicKey=$hasPublicKey, address=$hasAddress, endpoint=$endpoint"
}
}
internal fun shouldReuseRunningWireGuard(
tunnelUp: Boolean,
currentConfigFingerprint: String?,
updatedConfig: Config,
): Boolean =
tunnelUp &&
currentConfigFingerprint != null &&
currentConfigFingerprint == wireGuardConfigFingerprint(updatedConfig)
internal fun wireGuardConfigFingerprint(config: Config): String =
MessageDigest.getInstance("SHA-256")
.digest(config.toWgQuickString().toByteArray(Charsets.UTF_8))
.joinToString(separator = "") { byte -> "%02x".format(byte.toInt() and 0xff) }
@@ -0,0 +1,13 @@
package com.wdtt.plus.ui
internal fun collapsingHeaderOffsetAfterScroll(
currentOffsetPx: Float,
headerHeightPx: Float,
deltaPx: Float,
allowExpand: Boolean,
): Float {
if (headerHeightPx <= 0f || deltaPx == 0f) return currentOffsetPx
if (deltaPx > 0f && !allowExpand) return currentOffsetPx
return (currentOffsetPx + deltaPx).coerceIn(-headerHeightPx, 0f)
}
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,9 @@ package com.wdtt.plus.ui
import android.content.pm.PackageManager
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
@@ -57,76 +59,6 @@ object AppCache {
var cachedList: List<AppItem>? = null
}
private val VpnDetectionExactPackages = setOf(
"ru.sberbankmobile",
"ru.tinkoff.mb",
"ru.vtb24.mobilebanking.android",
"ru.alfabank.mobile.android",
"ru.ozon.app.android",
"com.wildberries.ru",
"ru.beru.android",
"ru.megamarket",
"ru.sbermarket",
"ru.samokat.android",
"com.avito.android",
"ru.yandex.searchplugin",
"ru.yandex.yandexmaps",
"ru.yandex.music",
"ru.kinopoisk",
"com.yandex.browser",
"ru.yandex.taxi",
"com.vkontakte.android",
"com.vk.vkvideo",
"ru.vk.music",
"ru.ok.android",
"ru.rutube.app",
"ru.mail.mailapp",
"ru.mail.cloud",
"ru.mts",
"ru.beeline.services",
"ru.tele2.mytele2",
"ru.megafon.mlk",
"ru.rostel",
"ru.gosuslugi.mobile",
"ru.vk.store",
"ru.dublgis.dgismobile",
"ru.maximoff.max"
)
private val VpnDetectionKeywords = listOf(
"sber", "сбер",
"tinkoff", "t-bank", "tbank", "тинькофф", "тбанк",
"vtb", "втб",
"alfa", "alpha", "альфа",
"ozon", "озон",
"wildberries", "вайлдберриз",
"yandex", "яндекс",
"vkontakte", "вконтакте",
"rutube", "рутуб",
"gosuslugi", "госуслуг",
"dublgis", "2gis", "dgis", "дубльгис",
"avito", "авито",
"mts", "мтс",
"beeline", "билайн",
"megafon", "мегафон",
"tele2", "теле2",
"mail.ru", "mailapp",
"ok.ru", "odnoklassniki",
"kinopoisk", "кинопоиск",
"samokat", "самокат",
"megamarket", "sbermarket",
"rostel", "ростел",
"maximoff"
)
private fun AppItem.matchesVpnDetectionApp(): Boolean {
val packageLower = packageName.lowercase()
if (packageLower in VpnDetectionExactPackages) return true
val titleLower = name.lowercase()
val haystack = "$packageLower $titleLower"
return VpnDetectionKeywords.any { keyword -> haystack.contains(keyword) }
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ExceptionsTab(
@@ -229,22 +161,50 @@ fun ExceptionsTab(
}
}
val collapsingHeaderConnection = remember(topBlockHeightPx) {
fun consumeHeaderScroll(deltaPx: Float, allowExpand: Boolean): Float {
val previousOffset = topBlockOffsetPx
val nextOffset = collapsingHeaderOffsetAfterScroll(
currentOffsetPx = previousOffset,
headerHeightPx = topBlockHeightPx,
deltaPx = deltaPx,
allowExpand = allowExpand,
)
if (nextOffset != previousOffset) {
topBlockOffsetPx = nextOffset
topBlockPositionInitialized = true
}
return nextOffset - previousOffset
}
val collapsingHeaderConnection = remember(topBlockHeightPx, listState) {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (topBlockHeightPx <= 0f) return Offset.Zero
val delta = available.y
val canCollapse = delta < 0f && topBlockOffsetPx > -topBlockHeightPx
val canExpand = delta > 0f && topBlockOffsetPx < 0f
if (!canCollapse && !canExpand) return Offset.Zero
val consumed = consumeHeaderScroll(
deltaPx = delta,
allowExpand = !listState.canScrollBackward,
)
return Offset(x = 0f, y = consumed)
}
val previousOffset = topBlockOffsetPx
topBlockOffsetPx = (previousOffset + delta).coerceIn(-topBlockHeightPx, 0f)
topBlockPositionInitialized = true
return Offset(x = 0f, y = topBlockOffsetPx - previousOffset)
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource,
): Offset {
if (available.y <= 0f) return Offset.Zero
val headerConsumed = consumeHeaderScroll(
deltaPx = available.y,
allowExpand = true,
)
return Offset(x = 0f, y = headerConsumed)
}
}
}
val searchHeaderScrollState = rememberScrollableState { deltaPx ->
consumeHeaderScroll(deltaPx = deltaPx, allowExpand = true)
}
val collapseFraction = if (topBlockHeightPx > 0f) {
(-topBlockOffsetPx / topBlockHeightPx).coerceIn(0f, 1f)
} else {
@@ -356,7 +316,12 @@ fun ExceptionsTab(
OutlinedButton(
onClick = {
val detectedPackages = appsList
.filter { it.matchesVpnDetectionApp() }
.filter {
matchesQuickExclusionApp(
name = it.name,
packageName = it.packageName,
)
}
.map { it.packageName }
.toSet()
if (detectedPackages.isEmpty()) {
@@ -383,7 +348,7 @@ fun ExceptionsTab(
)
}
Text(
"Банки, маркетплейсы и другие приложения, чувствительные к VPN. Поиск выполняется по известным названиям.",
"Приложения из белых списков мобильного интернета и другие сервисы, чувствительные к VPN. Выбираются только найденные на устройстве.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 6.dp)
@@ -409,7 +374,11 @@ fun ExceptionsTab(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp * collapseFraction, bottom = 12.dp)
.height(52.dp),
.height(52.dp)
.scrollable(
state = searchHeaderScrollState,
orientation = Orientation.Vertical,
),
shape = RoundedCornerShape(16.dp),
leadingIcon = { Icon(Icons.Default.Search, null, modifier = Modifier.size(20.dp)) },
singleLine = true,
@@ -12,6 +12,7 @@ import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -19,7 +20,6 @@ import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import kotlinx.coroutines.launch
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -37,7 +37,11 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.TunnelStopCoordinator
import com.wdtt.plus.TunnelStopResult
import com.wdtt.plus.sanitizeVpnProfileNameInput
import com.wdtt.plus.vpnProfileDefaultName
import com.wdtt.plus.vpnProfileDisplayName
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
@@ -56,6 +60,12 @@ import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Share
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import android.widget.Toast
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
private const val PROFILE_RESET_TIMEOUT_MS = 10_000L
@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
@Composable
@@ -65,6 +75,7 @@ fun FloatingToolbar(
onActiveProfileChange: (Int) -> Unit,
onProfileNameChange: (Int, String) -> Unit,
interfaceRole: String,
adminModeAllowed: Boolean,
onInterfaceRoleChange: (String) -> Unit,
currentTheme: String,
onThemeChange: (String) -> Unit,
@@ -80,10 +91,19 @@ fun FloatingToolbar(
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false)
val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList())
val trustedWifiRuntime by com.wdtt.plus.TrustedWifiManager.state.collectAsStateWithLifecycle()
val customVkCredentialsEnabled by settingsStore.customVkCredentialsEnabled.collectAsStateWithLifecycle(initialValue = false)
val customVkCredentialsComplete by settingsStore.customVkCredentialsComplete.collectAsStateWithLifecycle(initialValue = false)
val savedToolbarYFraction by settingsStore.floatingToolbarYFraction.collectAsStateWithLifecycle(
initialValue = -2f
)
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
val tunnelTransition by TunnelManager.transition.collectAsStateWithLifecycle()
val connectedProfile by TunnelManager.activeTunnelProfile.collectAsStateWithLifecycle()
val configuration = LocalConfiguration.current
val density = LocalDensity.current
val screenHeightPx = remember(configuration.screenHeightDp, density) {
@@ -96,19 +116,39 @@ fun FloatingToolbar(
var parentWidthPx by remember { mutableFloatStateOf(0f) }
var parentHeightPx by remember { mutableFloatStateOf(0f) }
var offsetY by rememberSaveable { mutableFloatStateOf(-1f) }
var offsetY by remember { mutableFloatStateOf(-1f) }
var toolbarPositionRestored by remember { mutableStateOf(false) }
var isRightSide by rememberSaveable { mutableStateOf(true) }
var isExpanded by rememberSaveable { mutableStateOf(false) }
var tabHeightPx by remember { mutableFloatStateOf(0f) }
var panelHeightPx by remember { mutableFloatStateOf(0f) }
var renamingProfile by remember { mutableStateOf<Int?>(null) }
var resettingProfile by remember { mutableStateOf<Int?>(null) }
var resetCountdown by remember { mutableIntStateOf(5) }
var resetInProgress by remember { mutableStateOf(false) }
var profileNameInput by rememberSaveable { mutableStateOf("") }
var showTrustedWifiSettings by rememberSaveable { mutableStateOf(false) }
var showVkClientSettings by rememberSaveable { mutableStateOf(false) }
val tabWidthDp = 42.dp
val tabHeightDp = 52.dp
val panelWidthDp = 220.dp
val isAdminRole = interfaceRole != "user"
// Move the thumb immediately on tap instead of waiting for the DataStore round trip.
// The persisted value still remains the source of truth and resynchronizes this state.
var displayedInterfaceRole by remember(interfaceRole, adminModeAllowed) {
mutableStateOf(if (adminModeAllowed) interfaceRole else "user")
}
val isAdminRole = adminModeAllowed && displayedInterfaceRole == "admin"
LaunchedEffect(resettingProfile) {
resetCountdown = 5
if (resettingProfile != null) {
while (resetCountdown > 0) {
delay(1_000L)
resetCountdown--
}
}
}
val tabWidthPx = remember(density) { with(density) { tabWidthDp.toPx() } }
val fallbackTabHeightPx = remember(density) { with(density) { tabHeightDp.toPx() } }
@@ -128,7 +168,7 @@ fun FloatingToolbar(
val minOffsetY = safeTopPx + edgePaddingPx
val maxOffsetY = (currentParentHeight - safeBottomPx - floatingHeightPx - edgePaddingPx)
.coerceAtLeast(minOffsetY)
val defaultOffsetY = (currentParentHeight * 0.24f).coerceIn(minOffsetY, maxOffsetY)
val defaultOffsetY = (currentParentHeight * 0.30f).coerceIn(minOffsetY, maxOffsetY)
val targetXPx = if (isRightSide) currentParentWidth - tabWidthPx else 0f
@@ -138,8 +178,29 @@ fun FloatingToolbar(
label = "tab_shift"
)
LaunchedEffect(minOffsetY, maxOffsetY) {
offsetY = if (offsetY < 0f) defaultOffsetY else offsetY.coerceIn(minOffsetY, maxOffsetY)
LaunchedEffect(savedToolbarYFraction, minOffsetY, maxOffsetY) {
if (savedToolbarYFraction < -1f) return@LaunchedEffect
offsetY = if (!toolbarPositionRestored || offsetY < 0f) {
if (savedToolbarYFraction >= 0f && maxOffsetY > minOffsetY) {
minOffsetY + (maxOffsetY - minOffsetY) * savedToolbarYFraction
} else {
defaultOffsetY
}
} else {
offsetY.coerceIn(minOffsetY, maxOffsetY)
}
toolbarPositionRestored = true
}
fun persistToolbarPosition() {
if (!toolbarPositionRestored) return
val availableRange = maxOffsetY - minOffsetY
val fraction = if (availableRange > 0f) {
((offsetY - minOffsetY) / availableRange).coerceIn(0f, 1f)
} else {
0f
}
scope.launch { settingsStore.saveFloatingToolbarYFraction(fraction) }
}
Box(
@@ -159,6 +220,8 @@ fun FloatingToolbar(
}
.pointerInput(minOffsetY, maxOffsetY) {
detectDragGestures(
onDragEnd = { persistToolbarPosition() },
onDragCancel = { persistToolbarPosition() },
onDrag = { change, dragAmount ->
change.consume()
offsetY = (offsetY + dragAmount.y).coerceIn(minOffsetY, maxOffsetY)
@@ -248,7 +311,10 @@ fun FloatingToolbar(
.widthIn(min = 72.dp, max = 180.dp)
.clip(profileShape)
.combinedClickable(
onClick = { onActiveProfileChange(profile) },
onClick = {
onActiveProfileChange(profile)
isExpanded = false
},
onLongClick = {
renamingProfile = profile
profileNameInput = profileLabel
@@ -280,7 +346,7 @@ fun FloatingToolbar(
shape = RoundedCornerShape(12.dp)
) {
Icon(Icons.Filled.Share, contentDescription = null, modifier = Modifier.size(18.dp))
Text(" Передать или получить", fontSize = 12.sp)
Text(" Получить или передать", fontSize = 12.sp)
}
HorizontalDivider(
@@ -340,7 +406,14 @@ fun FloatingToolbar(
color = MaterialTheme.colorScheme.onSurface
)
Text(
if (isAdminRole) "VPN и настройка своего сервера" else "Подключение и работа VPN",
when {
!adminModeAllowed ->
"Режим «Админ» доступен для самостоятельного профиля"
isAdminRole ->
"VPN и настройка своего сервера"
else ->
"Подключение и работа VPN"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 15.sp
@@ -348,7 +421,14 @@ fun FloatingToolbar(
}
Switch(
checked = isAdminRole,
onCheckedChange = { checked -> onInterfaceRoleChange(if (checked) "admin" else "user") },
onCheckedChange = { checked ->
val role = if (checked) "admin" else "user"
if (role != displayedInterfaceRole) {
displayedInterfaceRole = role
onInterfaceRoleChange(role)
}
},
enabled = adminModeAllowed,
modifier = Modifier.scale(0.85f)
)
}
@@ -501,94 +581,41 @@ fun FloatingToolbar(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
Text(
"Client IDs",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(start = 4.dp, bottom = 4.dp)
)
val scope = rememberCoroutineScope()
val clientIdsList = activeClientIds.split(",").map { it.trim() }.filter { it.isNotEmpty() }
val checkResultsJson by settingsStore.clientIdCheckResults.collectAsStateWithLifecycle(initialValue = "{}")
var checkResults by remember(checkResultsJson) {
mutableStateOf(try {
val json = org.json.JSONObject(checkResultsJson)
val map = mutableMapOf<String, Boolean>()
val keys = json.keys()
while (keys.hasNext()) {
val key = keys.next() as String
map[key] = json.getBoolean(key)
}
map
} catch (e: Exception) { emptyMap() })
}
var isChecking by remember { mutableStateOf(false) }
val knownIds = listOf("6287487", "8202606")
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
knownIds.forEach { id ->
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
modifier = Modifier
.fillMaxWidth()
.clickable { showVkClientSettings = true }
.padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(
checked = clientIdsList.contains(id),
onCheckedChange = { checked ->
val newList = if (checked) {
if (!clientIdsList.contains(id)) clientIdsList + id else clientIdsList
} else {
clientIdsList - id
}
if (newList.isNotEmpty()) {
onClientIdsChange(newList.joinToString(","))
}
},
modifier = Modifier.scale(0.8f)
)
Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) {
Text(
text = id,
style = MaterialTheme.typography.bodySmall,
"Клиенты VK",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
}
if (checkResults.containsKey(id)) {
Text(
text = if (checkResults[id] == true) "✅" else "❌",
fontSize = 12.sp
when {
!customVkCredentialsEnabled -> "VKCalls → встроенный резерв"
customVkCredentialsComplete -> "VKCalls → свой → встроенный резерв"
else -> "Заполните резервные реквизиты"
},
style = MaterialTheme.typography.bodySmall,
color = if (customVkCredentialsEnabled && !customVkCredentialsComplete) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
lineHeight = 15.sp
)
}
}
}
Button(
onClick = {
isChecking = true
scope.launch(kotlinx.coroutines.Dispatchers.IO) {
val results = checkResults.toMutableMap()
knownIds.forEach { id ->
results[id] = checkVkClientId(id)
}
val newJson = org.json.JSONObject()
results.forEach { (k, v) -> newJson.put(k, v) }
settingsStore.saveClientIdCheckResults(newJson.toString())
isChecking = false
}
},
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp),
enabled = !isChecking,
contentPadding = PaddingValues(0.dp)
) {
Text(if (isChecking) "Checking..." else "Проверить", fontSize = 12.sp)
}
Switch(
checked = customVkCredentialsEnabled,
onCheckedChange = null,
modifier = Modifier.scale(0.85f)
)
}
}
}
@@ -596,39 +623,73 @@ fun FloatingToolbar(
}
renamingProfile?.let { profile ->
AlertDialog(
onDismissRequest = { renamingProfile = null },
title = {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text("Название профиля")
IconButton(onClick = { renamingProfile = null }) {
Icon(Icons.Filled.Close, contentDescription = "Закрыть")
}
}
ProfileMenuDialog(
profileNameInput = profileNameInput,
onProfileNameInputChange = { profileNameInput = sanitizeVpnProfileNameInput(it) },
onResetRequested = {
resetCountdown = 5
resettingProfile = profile
},
text = {
OutlinedTextField(
value = profileNameInput,
onValueChange = { profileNameInput = sanitizeVpnProfileNameInput(it) },
label = { Text("Название") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
},
confirmButton = {
Button(
onClick = {
onSave = {
onProfileNameChange(profile, profileNameInput)
renamingProfile = null
},
onDismiss = { renamingProfile = null }
)
}
) {
Text("Сохранить")
resettingProfile?.let { profile ->
val profileLabel = vpnProfileDisplayName(profile, profileNames)
val potentiallyConnectedProfile = profile == (connectedProfile ?: activeProfile)
val resetsConnectedProfile = potentiallyConnectedProfile &&
(tunnelRunning || tunnelTransition != com.wdtt.plus.TunnelTransition.IDLE)
ProfileResetDialog(
profileLabel = profileLabel,
defaultProfileLabel = vpnProfileDefaultName(profile),
countdown = resetCountdown,
inProgress = resetInProgress,
disconnectsActiveVpn = resetsConnectedProfile,
onConfirm = {
if (resetCountdown > 0 || resetInProgress) return@ProfileResetDialog
resetInProgress = true
scope.launch {
runCatching {
if (potentiallyConnectedProfile) {
val stopResult = TunnelStopCoordinator.stopAndAwait(context)
check(stopResult.succeeded) {
when (stopResult) {
TunnelStopResult.TIMED_OUT ->
"VPN не остановился за отведённое время"
else -> "Не удалось остановить VPN"
}
}
}
val resetCompleted = withTimeoutOrNull(PROFILE_RESET_TIMEOUT_MS) {
settingsStore.resetProfile(profile)
true
} == true
check(resetCompleted) {
"Очистка профиля не завершилась за 10 секунд. Повторите попытку."
}
}.onSuccess {
profileNameInput = vpnProfileDefaultName(profile)
resettingProfile = null
renamingProfile = null
isExpanded = false
Toast.makeText(context, "Профиль «$profileLabel» очищен", Toast.LENGTH_SHORT).show()
}.onFailure { error ->
Toast.makeText(
context,
error.message ?: "Не удалось очистить профиль",
Toast.LENGTH_LONG
).show()
}
resetInProgress = false
}
},
onDismiss = {
if (!resetInProgress) resettingProfile = null
}
)
}
@@ -638,36 +699,250 @@ fun FloatingToolbar(
onDismiss = { showTrustedWifiSettings = false }
)
}
if (showVkClientSettings) {
VkClientSettingsDialog(
settingsStore = settingsStore,
activeClientIds = activeClientIds,
onClientIdsChange = onClientIdsChange,
onDismiss = { showVkClientSettings = false }
)
}
}
}
private fun checkVkClientId(appId: String): Boolean {
for (i in 0..1) {
try {
val url = java.net.URL("https://oauth.vk.com/authorize?client_id=$appId&display=mobile&response_type=token")
val conn = url.openConnection() as java.net.HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 5000
conn.readTimeout = 5000
@Composable
private fun ProfileMenuDialog(
profileNameInput: String,
onProfileNameInputChange: (String) -> Unit,
onResetRequested: () -> Unit,
onSave: () -> Unit,
onDismiss: () -> Unit
) {
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
BoxWithConstraints(
modifier = Modifier.fillMaxSize().padding(8.dp),
contentAlignment = Alignment.Center
) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.widthIn(max = 560.dp)
.heightIn(max = maxHeight * 0.92f),
shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
tonalElevation = 8.dp
) {
Box {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(22.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Text(
"Профиль",
modifier = Modifier.padding(end = 48.dp),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = profileNameInput,
onValueChange = onProfileNameInputChange,
label = { Text("Название") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onResetRequested,
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp)
) {
Text("Очистить", fontWeight = FontWeight.SemiBold)
}
Button(
onClick = onSave,
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
shape = RoundedCornerShape(16.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp)
) {
Text("Сохранить", fontWeight = FontWeight.SemiBold)
}
}
Spacer(Modifier.height(4.dp))
}
val code = conn.responseCode
val stream = if (code >= 400) conn.errorStream else conn.inputStream
val response = stream?.bufferedReader()?.readText() ?: ""
// If it returns a json error like {"error":"invalid_client"...}
if (response.contains("\"error\"") && (response.contains("invalid_client") || response.contains("invalid_request"))) {
return false
}
// If it returns HTML (login form or captcha), it's a valid client ID
return true
} catch (e: Exception) {
// Error, will retry
ProfileDialogCloseButton(
contentDescription = "Вернуться в настройки",
onClick = onDismiss,
modifier = Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 10.dp)
)
}
}
}
}
return false
}
@Composable
private fun ProfileResetDialog(
profileLabel: String,
defaultProfileLabel: String,
countdown: Int,
inProgress: Boolean,
disconnectsActiveVpn: Boolean,
onConfirm: () -> Unit,
onDismiss: () -> Unit
) {
Dialog(
onDismissRequest = { if (!inProgress) onDismiss() },
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
BoxWithConstraints(
modifier = Modifier.fillMaxSize().padding(8.dp),
contentAlignment = Alignment.Center
) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.widthIn(max = 560.dp)
.heightIn(max = maxHeight * 0.92f),
shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
tonalElevation = 8.dp
) {
Box {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(22.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Text(
"Очистить профиль?",
modifier = Modifier.padding(end = 48.dp),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.error
)
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer
) {
Column(
modifier = Modifier.padding(15.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
"Будет полностью очищена вся локальная информация профиля «$profileLabel».",
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.bodyLarge
)
Text(
"Удалятся настройки подключения, VK-хеши, ссылки, пароли и SSH-ключи, параметры сервера, списки приложений и остальные данные этого профиля.",
style = MaterialTheme.typography.bodyMedium
)
Text(
"Название вернётся к стандартному: «$defaultProfileLabel». Операция необратима. Вы уверены?",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold
)
}
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.72f)
) {
Text(
buildString {
append("На самом VPS и в других профилях ничего не удаляется.")
if (disconnectsActiveVpn) append(" Активное VPN-подключение этого профиля будет остановлено.")
},
modifier = Modifier.padding(14.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Button(
onClick = onConfirm,
enabled = countdown <= 0 && !inProgress,
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.error,
contentColor = MaterialTheme.colorScheme.onError,
disabledContainerColor = MaterialTheme.colorScheme.errorContainer,
disabledContentColor = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.68f)
)
) {
Text(
when {
inProgress -> "Очищаю профиль…"
countdown > 0 -> "Очистить через $countdown с"
else -> "Полностью очистить профиль"
},
fontWeight = FontWeight.Bold
)
}
Spacer(Modifier.height(4.dp))
}
ProfileDialogCloseButton(
contentDescription = "Вернуться к профилю",
onClick = onDismiss,
enabled = !inProgress,
modifier = Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 10.dp)
)
}
}
}
}
}
@Composable
private fun ProfileDialogCloseButton(
contentDescription: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true
) {
IconButton(onClick = onClick, modifier = modifier, enabled = enabled) {
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.78f),
modifier = Modifier.size(34.dp)
) {
Box(contentAlignment = Alignment.Center) {
Icon(
Icons.Filled.Close,
contentDescription = contentDescription,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(22.dp)
)
}
}
}
}
@Composable
private fun ThemeOption(
+603 -26
View File
@@ -52,11 +52,14 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Cloud
import androidx.compose.material.icons.filled.Code
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Info
@@ -65,13 +68,17 @@ import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -94,6 +101,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@@ -104,6 +112,11 @@ import com.wdtt.plus.BuildConfig
import com.wdtt.plus.DeviceCheckAction
import com.wdtt.plus.DeviceCompatibility
import com.wdtt.plus.R
import com.wdtt.plus.RemoteActionCatalogGateway
import com.wdtt.plus.RemoteActionForm
import com.wdtt.plus.RemoteContinuationLauncher
import com.wdtt.plus.RemoteUiAction
import com.wdtt.plus.RemoteUiActionLauncher
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.TrustedWifiManager
@@ -114,7 +127,9 @@ import com.wdtt.plus.WDTTColors
import com.wdtt.plus.AppReleaseInfo
import com.wdtt.plus.AppUpdateCandidate
import com.wdtt.plus.AppUpdateDownloadProgress
import com.wdtt.plus.ClientNetworkDiagnosticsReport
import com.wdtt.plus.canRequestApkInstall
import com.wdtt.plus.collectClientNetworkDiagnostics
import com.wdtt.plus.downloadUpdateApk
import com.wdtt.plus.fetchLatestReleaseInfo
import com.wdtt.plus.installUpdateApk
@@ -123,6 +138,7 @@ import com.wdtt.plus.resolveAppUpdateCandidate
import com.wdtt.plus.selectUpdateApkAsset
import com.wdtt.plus.deviceCheckActionIntent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -132,6 +148,7 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.UUID
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.min
@@ -142,7 +159,7 @@ private const val IssuesUrl = "https://github.com/Ivan4537/WDTT-Plus/issues/new/
private const val DeveloperProfileUrl = "https://github.com/Ivan4537"
private const val RepositoryUrl = "https://github.com/Ivan4537/WDTT-Plus"
private const val ChangelogUrl = "$RepositoryUrl/blob/main/CHANGELOG.md"
private const val DonateUrl = "https://yoomoney.ru/to/410012216336438"
private const val ProjectDonateFallbackUrl = "https://yoomoney.ru/to/410012216336438"
private const val OriginalDonateUrl = "https://yoomoney.ru/to/4100119505530465/"
private val DonateActionButtonColor = Color(0xFF00AEA5)
@@ -221,7 +238,9 @@ private fun openDeviceCheckAction(context: Context, action: DeviceCheckAction) {
fun InfoTab(
actionsExpandedState: MutableState<Boolean> = rememberSaveable { mutableStateOf(true) },
projectExpandedState: MutableState<Boolean> = rememberSaveable { mutableStateOf(true) },
scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) },
projectSupportDialogRequest: Int = 0,
onProjectSupportDialogRequestConsumed: () -> Unit = {},
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
@@ -239,11 +258,22 @@ fun InfoTab(
var updateDownloadBusy by remember { mutableStateOf(false) }
var pendingUpdateApkPath by rememberSaveable { mutableStateOf<String?>(null) }
var showHelpDialog by remember { mutableStateOf(false) }
var showQuestionDialog by remember { mutableStateOf(false) }
var showSupportDialog by remember { mutableStateOf(false) }
var pendingActionForm by remember { mutableStateOf<RemoteUiAction?>(null) }
var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) }
var questionAction by remember { mutableStateOf<RemoteUiAction?>(null) }
var questionActionLoading by remember { mutableStateOf(false) }
var isCheckingDevice by remember { mutableStateOf(false) }
var deviceCheckReport by remember { mutableStateOf<com.wdtt.plus.DeviceCompatibilityReport?>(null) }
var actionsExpanded by actionsExpandedState
var projectExpanded by projectExpandedState
LaunchedEffect(projectSupportDialogRequest) {
if (projectSupportDialogRequest > 0) {
showSupportDialog = true
onProjectSupportDialogRequestConsumed()
}
}
val updateLatestVersion by settingsStore.updateLatestVersion.collectAsStateWithLifecycle(initialValue = "")
val updateLastError by settingsStore.updateLastError.collectAsStateWithLifecycle(initialValue = "")
val updateStatus = remember(isCheckingUpdates, updateLatestVersion, updateLastError, currentVersion) {
@@ -276,6 +306,15 @@ fun InfoTab(
}
}
LaunchedEffect(Unit) {
actionCatalog = RemoteActionCatalogGateway.fetch()
}
LaunchedEffect(Unit) {
questionActionLoading = true
questionAction = RemoteActionCatalogGateway.fetchQuestionAction()
questionActionLoading = false
}
fun requestDownloadedUpdateInstall(apkFile: File) {
pendingUpdateApkPath = apkFile.absolutePath
if (!canRequestApkInstall(context)) {
@@ -317,6 +356,25 @@ fun InfoTab(
val diagnosticsSummary = withContext(Dispatchers.Default) {
buildSupportReportSummary(context.applicationContext, settingsStore)
}
val clientNetworkDiagnostics = try {
collectClientNetworkDiagnostics(context.applicationContext)
} catch (error: CancellationException) {
throw error
} catch (error: Throwable) {
ClientNetworkDiagnosticsReport(
summaryLines = listOf("Активная диагностика сети телефона: не выполнена"),
items = listOf(
com.wdtt.plus.DeviceCheckItem(
title = "Активная диагностика сети телефона",
status = "не выполнена",
details = error.message?.take(180) ?: error.javaClass.simpleName,
recommendation = "Повторите проверку устройства при активной сети.",
severity = com.wdtt.plus.DeviceCheckSeverity.Warning,
action = DeviceCheckAction.NetworkSettings
)
)
)
}
val report = withContext(Dispatchers.Default) {
DeviceCompatibility.check(
context = context.applicationContext,
@@ -325,9 +383,10 @@ fun InfoTab(
)
}
return report.copy(
summaryLines = diagnosticsSummary,
summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines,
items = listOf(versionItem) +
report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE }
report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE } +
clientNetworkDiagnostics.items
)
}
@@ -355,7 +414,9 @@ fun InfoTab(
InfoHeroCard(
currentVersion = currentVersion,
releaseDate = releaseDate,
onSupportClick = { showSupportDialog = true }
onSupportClick = {
showSupportDialog = true
}
)
ExpandableSectionCard(
@@ -384,8 +445,17 @@ fun InfoTab(
) {
WideActionTile(
title = "Поднять вопрос",
subtitle = "Выбрать шаблон GitHub issue",
onClick = { openUrlInBrowser(context, IssuesUrl) },
subtitle = "Выбрать подходящий способ обращения",
onClick = {
showQuestionDialog = true
if (questionAction == null && !questionActionLoading) {
scope.launch {
questionActionLoading = true
questionAction = RemoteActionCatalogGateway.fetchQuestionAction()
questionActionLoading = false
}
}
},
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_github),
@@ -672,12 +742,35 @@ fun InfoTab(
}
if (showHelpDialog) ImportantInfoDialog(onDismiss = { showHelpDialog = false })
if (showQuestionDialog) {
QuestionDestinationDialog(
remoteAction = questionAction,
remoteActionLoading = questionActionLoading,
onDismiss = { showQuestionDialog = false },
onGitHubClick = {
showQuestionDialog = false
openUrlInBrowser(context, IssuesUrl)
},
onRemoteActionClick = { action ->
showQuestionDialog = false
scope.launch {
if (!RemoteUiActionLauncher.open(context, action)) {
Toast.makeText(
context,
"Не удалось открыть страницу. Проверьте браузер.",
Toast.LENGTH_LONG,
).show()
}
}
},
)
}
deviceCheckReport?.let { report ->
DeviceCompatibilityDialog(
report = report,
title = "Проверка устройства",
subtitle = "Расширенная проверка не запускает VPN, но показывает совместимость устройства, настройки Android и статус подключения.",
note = "Кнопка «Скопировать отчёт» добавит в буфер версию приложения, Android, ABI, память, сеть, WebView, native-клиент и текущие настройки без секретных значений.",
subtitle = "Расширенная проверка не запускает VPN, но безопасно проверяет системный DNS, DNS-путь клиента и доступность узлов VK/OK.",
note = "Кнопка «Скопировать отчёт» повторит сетевые пробы и добавит их результат без VK-хешей, паролей, токенов и локальных IP-адресов телефона.",
onDismiss = { deviceCheckReport = null },
onCopy = {
scope.launch {
@@ -696,18 +789,189 @@ fun InfoTab(
)
}
if (showSupportDialog) {
SupportProjectDialog(
AdditionalActionsDialog(
onDismiss = { showSupportDialog = false },
onDonateModClick = { openUrlInBrowser(context, DonateUrl) },
onDonateOriginalClick = { openUrlInBrowser(context, OriginalDonateUrl) }
primaryAction = actionCatalog.at("about"),
secondaryAction = actionCatalog.at("tunnel"),
onActionClick = { action ->
if (action.form != null) {
showSupportDialog = false
pendingActionForm = action
} else {
showSupportDialog = false
scope.launch {
if (!RemoteUiActionLauncher.open(context, action)) {
Toast.makeText(
context,
"Не удалось открыть страницу. Проверьте браузер.",
Toast.LENGTH_LONG,
).show()
}
}
}
},
onProjectFallbackClick = {
showSupportDialog = false
openUrlInBrowser(context, ProjectDonateFallbackUrl)
},
onDonateOriginalClick = {
showSupportDialog = false
openUrlInBrowser(context, OriginalDonateUrl)
}
)
}
pendingActionForm?.form?.let { form ->
RemoteActionFormDialog(
form = form,
onDismiss = {
pendingActionForm = null
showSupportDialog = true
},
onComplete = {
pendingActionForm = null
showSupportDialog = true
},
onFallbackClick = {
openUrlInBrowser(context, ProjectDonateFallbackUrl)
pendingActionForm = null
showSupportDialog = true
},
)
}
}
@Composable
private fun SupportProjectDialog(
private fun QuestionDestinationDialog(
remoteAction: RemoteUiAction?,
remoteActionLoading: Boolean,
onDismiss: () -> Unit,
onDonateModClick: () -> Unit,
onGitHubClick: () -> Unit,
onRemoteActionClick: (RemoteUiAction) -> Unit,
) {
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
Box(
modifier = Modifier.fillMaxSize().padding(20.dp),
contentAlignment = Alignment.Center,
) {
Surface(
shape = RoundedCornerShape(28.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp,
shadowElevation = 18.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 560.dp),
) {
Column(
modifier = Modifier.fillMaxWidth().padding(20.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.primaryContainer,
) {
Box(
modifier = Modifier.size(42.dp),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.HelpOutline,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(21.dp),
)
}
}
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
Text(
"Поднять вопрос",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
)
Text(
"Выберите подходящий вариант обращения.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
FilledTonalIconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = null)
}
}
WideActionTile(
title = "Проблема в приложении",
subtitle = "Открыть шаблоны обращений GitHub",
onClick = onGitHubClick,
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_github),
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer,
)
},
)
remoteAction?.let { action ->
WideActionTile(
title = action.label,
subtitle = action.message,
onClick = { onRemoteActionClick(action) },
icon = {
Icon(
Icons.AutoMirrored.Filled.HelpOutline,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer,
)
},
)
}
if (remoteAction == null && remoteActionLoading) {
Surface(
shape = RoundedCornerShape(20.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.62f),
modifier = Modifier.fillMaxWidth(),
) {
Row(
modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
strokeWidth = 2.dp,
)
Text(
"Проверяем доступные способы помощи…",
style = MaterialTheme.typography.bodyMedium,
)
}
}
}
}
}
}
}
}
@Composable
private fun AdditionalActionsDialog(
onDismiss: () -> Unit,
primaryAction: RemoteUiAction?,
secondaryAction: RemoteUiAction?,
onActionClick: (RemoteUiAction) -> Unit,
onProjectFallbackClick: () -> Unit,
onDonateOriginalClick: () -> Unit
) {
Dialog(
@@ -766,15 +1030,35 @@ private fun SupportProjectDialog(
}
}
SupportDonateBlock(
title = "WDTT Plus",
body = "Поддержка этой версии помогает развивать доработки приложения, серверной части, Telegram-бота и удобство для пользователей.",
buttonText = "ЮMoney",
onClick = onDonateModClick,
emphasized = true
if (primaryAction?.form != null) {
ExternalSupportBlock(
title = primaryAction.title,
body = primaryAction.message,
buttonText = primaryAction.label,
onClick = { onActionClick(primaryAction) },
emphasized = true,
)
} else {
ExternalSupportBlock(
title = "WDTT Plus",
body = (
"Поддержка помогает развивать приложение, серверную "
+ "часть и Telegram-бота."
),
buttonText = "ЮMoney",
onClick = onProjectFallbackClick,
emphasized = true,
)
}
SupportDonateBlock(
secondaryAction?.let { action ->
RemoteInfoActionBlock(
action = action,
onClick = { onActionClick(action) },
)
}
ExternalSupportBlock(
title = "Автор оригинального приложения",
body = "Оригинальная основа проекта создана amurcanov. Можно отдельно поддержать автора исходного приложения.",
buttonText = "ЮMoney",
@@ -789,7 +1073,285 @@ private fun SupportProjectDialog(
}
@Composable
private fun SupportDonateBlock(
private fun RemoteActionFormDialog(
form: RemoteActionForm,
onDismiss: () -> Unit,
onComplete: () -> Unit,
onFallbackClick: () -> Unit,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var valueText by rememberSaveable(form.token) { mutableStateOf(form.initialValue) }
var requestId by rememberSaveable(form.token) { mutableStateOf(UUID.randomUUID().toString()) }
var busy by remember(form.token) { mutableStateOf(false) }
var errorMessage by remember(form.token) { mutableStateOf("") }
var fallbackAvailable by remember(form.token) { mutableStateOf(false) }
val numericValue = valueText.toLongOrNull()
val valueValid = numericValue != null && numericValue in form.minimum..form.maximum
fun selectValue(value: String) {
valueText = value
requestId = UUID.randomUUID().toString()
errorMessage = ""
fallbackAvailable = false
}
Dialog(
onDismissRequest = { if (!busy) onDismiss() },
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
Surface(
shape = RoundedCornerShape(28.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp,
shadowElevation = 18.dp,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.primaryContainer,
) {
Box(Modifier.size(42.dp), contentAlignment = Alignment.Center) {
Icon(
Icons.Default.Favorite,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(20.dp),
)
}
}
Text(
form.title,
modifier = Modifier.weight(1f),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
)
FilledTonalIconButton(
onClick = onDismiss,
enabled = !busy,
) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
Text(
form.message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 20.sp,
)
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
form.choices.chunked(2).forEach { rowChoices ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
rowChoices.forEach { choice ->
OutlinedButton(
onClick = { selectValue(choice.value) },
enabled = !busy,
modifier = Modifier.weight(1f),
colors = if (valueText == choice.value) {
ButtonDefaults.outlinedButtonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
)
} else {
ButtonDefaults.outlinedButtonColors()
},
) {
Text(choice.label, fontWeight = FontWeight.SemiBold)
}
}
if (rowChoices.size == 1) {
Spacer(Modifier.weight(1f))
}
}
}
}
OutlinedTextField(
value = valueText,
onValueChange = { raw ->
selectValue(raw.filter(Char::isDigit).take(form.maxCharacters))
},
enabled = !busy,
modifier = Modifier.fillMaxWidth(),
label = { Text(form.inputLabel) },
suffix = {
if (form.inputSuffix.isNotBlank()) {
Text(form.inputSuffix)
}
},
singleLine = true,
isError = valueText.isNotEmpty() && !valueValid,
supportingText = {
Text(
if (valueValid || valueText.isEmpty()) {
form.supportingText
} else {
form.invalidText
}
)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
shape = RoundedCornerShape(16.dp),
)
if (errorMessage.isNotBlank()) {
Surface(
color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.64f),
shape = RoundedCornerShape(14.dp),
) {
Text(
errorMessage,
modifier = Modifier.fillMaxWidth().padding(12.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer,
)
}
}
Button(
onClick = {
if (!valueValid) return@Button
busy = true
errorMessage = ""
fallbackAvailable = false
scope.launch {
runCatching {
RemoteActionCatalogGateway.execute(
form = form,
requestId = requestId,
value = valueText,
)
}.onSuccess { target ->
RemoteContinuationLauncher.launch(context, target)
onComplete()
}.onFailure { error ->
errorMessage = error.message ?: form.failureMessage
fallbackAvailable = true
}
busy = false
}
},
enabled = valueValid && !busy,
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(17.dp),
colors = ButtonDefaults.buttonColors(
containerColor = DonateActionButtonColor,
contentColor = Color.White,
),
) {
if (busy) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
strokeWidth = 2.dp,
color = Color.White,
)
Spacer(Modifier.width(9.dp))
Text(form.busyLabel, fontWeight = FontWeight.Bold)
} else {
Text(
form.submitLabel.replace("{value}", valueText),
fontWeight = FontWeight.Bold,
)
}
}
if (fallbackAvailable) {
OutlinedButton(
onClick = onFallbackClick,
enabled = !busy,
modifier = Modifier.fillMaxWidth().heightIn(min = 46.dp),
shape = RoundedCornerShape(16.dp),
) {
Text(form.fallbackLabel, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.width(6.dp))
Icon(
Icons.AutoMirrored.Filled.OpenInNew,
contentDescription = null,
modifier = Modifier.size(17.dp),
)
}
}
}
}
}
}
@Composable
private fun RemoteInfoActionBlock(
action: RemoteUiAction,
onClick: () -> Unit,
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f),
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
border = BorderStroke(
1.dp,
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)
)
) {
Column(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalArrangement = Arrangement.spacedBy(9.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(9.dp)
) {
Icon(Icons.Default.Cloud, contentDescription = null, modifier = Modifier.size(21.dp))
Text(
action.title,
modifier = Modifier.weight(1f),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold
)
}
Text(
action.message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.86f),
lineHeight = 18.sp
)
OutlinedButton(
onClick = onClick,
modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp),
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 7.dp)
) {
Text(action.label, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.width(6.dp))
Icon(
Icons.AutoMirrored.Filled.OpenInNew,
contentDescription = null,
modifier = Modifier.size(17.dp)
)
}
}
}
}
@Composable
private fun ExternalSupportBlock(
title: String,
body: String,
buttonText: String,
@@ -834,7 +1396,11 @@ private fun SupportDonateBlock(
onClick = onClick,
shape = RoundedCornerShape(18.dp),
colors = ButtonDefaults.buttonColors(
containerColor = if (emphasized) DonateActionButtonColor else MaterialTheme.colorScheme.primary,
containerColor = if (emphasized) {
DonateActionButtonColor
} else {
MaterialTheme.colorScheme.primary
},
contentColor = Color.White
),
modifier = Modifier
@@ -1428,6 +1994,11 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
.coerceAtMost(4)
val hasSecondaryHash = runCatching { settingsStore.secondaryVkHash.first().isNotBlank() }.getOrNull()
val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull()
val customVkCredentialsEnabled = runCatching { settingsStore.customVkCredentialsEnabled.first() }.getOrNull()
val customVkCredentialsComplete = runCatching { settingsStore.customVkCredentialsComplete.first() }.getOrNull()
val builtInVkClientCount = runCatching {
settingsStore.activeClientIds.first().split(',').count { it.trim().isNotEmpty() }
}.getOrNull()
val captchaMode = runCatching { settingsStore.captchaMode.first() }.getOrNull()
val fingerprint = runCatching { settingsStore.selectedFingerprint.first() }.getOrNull()
val linkMode = runCatching { settingsStore.wdttLinkMode.first() }.getOrNull()
@@ -1447,7 +2018,9 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
} else {
"не требуется"
}
val tunnelIssue = TunnelManager.connectionIssue.value?.title.orEmpty().ifBlank { "нет" }
val tunnelIssue = TunnelManager.connectionIssue.value?.let { issue ->
"${issue.title}: ${issue.action}"
}.orEmpty().ifBlank { "нет" }
return buildString {
appendLine("Версия приложения: ${BuildConfig.VERSION_NAME}")
@@ -1498,8 +2071,12 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
appendLine("Профиль: ${activeProfile ?: "недоступно"}")
appendLine("Потоки: ${workers ?: "недоступно"}")
appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}")
appendLine("VKCalls: ${vkCallsEnabled ?: "недоступно"}")
appendLine("Captcha mode: ${captchaMode ?: "недоступно"}")
appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}")
appendLine(
"Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " +
"заполнены=${customVkCredentialsComplete ?: "недоступно"}, встроенных=${builtInVkClientCount ?: "недоступно"}"
)
appendLine("Captcha mode (legacy): ${captchaMode ?: "недоступно"}")
appendLine("TLS fingerprint: ${fingerprint ?: "недоступно"}")
appendLine("Режим ссылки: ${linkMode ?: "недоступно"}")
appendLine("Роль интерфейса: ${interfaceRole?.ifBlank { "не выбрана" } ?: "недоступно"}")
@@ -0,0 +1,166 @@
package com.wdtt.plus.ui
import android.content.Context
import android.content.SharedPreferences
import com.wdtt.plus.SecureStringStore
internal data class StoredOutboundForms(
val forms: OutboundProfileForms,
val warpMtu: String,
)
/**
* Локальные черновики выходного IP относятся к конкретному VPN-профилю.
* Пароли и WireGuard-конфиг хранятся через Android Keystore.
*/
internal class OutboundFormsStore(context: Context) {
private val prefs =
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
private val secureStore = SecureStringStore(context.applicationContext)
init {
migrateLegacyValuesToProfileZero()
}
fun load(profileIndex: Int): StoredOutboundForms {
val profile = profileIndex.coerceIn(0, 2)
return StoredOutboundForms(
forms = OutboundProfileForms(
localProxyPort = string(profile, LOCAL_PROXY_PORT, "1080"),
localProxyLogin = string(profile, LOCAL_PROXY_LOGIN, ""),
localProxyPassword = secret(profile, LOCAL_PROXY_PASSWORD),
externalProxyKindName = string(profile, EXTERNAL_PROXY_KIND, "Socks5"),
externalProxyHost = string(profile, EXTERNAL_PROXY_HOST, ""),
externalProxyPort = string(profile, EXTERNAL_PROXY_PORT, "1080"),
externalProxyLogin = string(profile, EXTERNAL_PROXY_LOGIN, ""),
externalProxyPassword = secret(profile, EXTERNAL_PROXY_PASSWORD),
wireGuardExitHost = string(profile, WG_EXIT_HOST, ""),
wireGuardExitSshPort = string(profile, WG_EXIT_SSH_PORT, "22"),
wireGuardExitUser = string(profile, WG_EXIT_USER, "root"),
wireGuardExitPassword = secret(profile, WG_EXIT_PASSWORD),
wireGuardExitPort = string(profile, WG_EXIT_PORT, "51820"),
wireGuardExitDns = string(profile, WG_EXIT_DNS, "1.1.1.1,8.8.8.8"),
importedWireGuardConfig = secret(profile, IMPORTED_WG_CONFIG),
),
warpMtu = string(profile, WARP_MTU, "1280"),
)
}
fun save(profileIndex: Int, forms: OutboundProfileForms, warpMtu: String) {
val profile = profileIndex.coerceIn(0, 2)
val editor = prefs.edit()
.putString(key(profile, LOCAL_PROXY_PORT), forms.localProxyPort)
.putString(key(profile, LOCAL_PROXY_LOGIN), forms.localProxyLogin)
.putString(key(profile, EXTERNAL_PROXY_KIND), forms.externalProxyKindName)
.putString(key(profile, EXTERNAL_PROXY_HOST), forms.externalProxyHost)
.putString(key(profile, EXTERNAL_PROXY_PORT), forms.externalProxyPort)
.putString(key(profile, EXTERNAL_PROXY_LOGIN), forms.externalProxyLogin)
.putString(key(profile, WG_EXIT_HOST), forms.wireGuardExitHost)
.putString(key(profile, WG_EXIT_SSH_PORT), forms.wireGuardExitSshPort)
.putString(key(profile, WG_EXIT_USER), forms.wireGuardExitUser)
.putString(key(profile, WG_EXIT_PORT), forms.wireGuardExitPort)
.putString(key(profile, WG_EXIT_DNS), forms.wireGuardExitDns)
.putString(key(profile, WARP_MTU), warpMtu)
editor.putSecret(profile, LOCAL_PROXY_PASSWORD, forms.localProxyPassword)
editor.putSecret(profile, EXTERNAL_PROXY_PASSWORD, forms.externalProxyPassword)
editor.putSecret(profile, WG_EXIT_PASSWORD, forms.wireGuardExitPassword)
editor.putSecret(profile, IMPORTED_WG_CONFIG, forms.importedWireGuardConfig)
editor.apply()
}
private fun string(profile: Int, name: String, default: String): String =
prefs.getString(key(profile, name), default) ?: default
private fun secret(profile: Int, name: String): String {
val encryptedKey = encryptedKey(profile, name)
secureStore.decrypt(prefs.getString(encryptedKey, null))?.let { return it }
return prefs.getString(key(profile, name), "").orEmpty()
}
private fun SharedPreferences.Editor.putSecret(profile: Int, name: String, value: String) {
val plainKey = key(profile, name)
remove(plainKey)
if (value.isBlank()) {
remove(encryptedKey(profile, name))
} else {
putString(encryptedKey(profile, name), secureStore.encrypt(value))
}
}
private fun migrateLegacyValuesToProfileZero() {
val legacyNames = NON_SECRET_NAMES + SECRET_NAMES
if (legacyNames.none(prefs::contains)) return
val editor = prefs.edit()
NON_SECRET_NAMES.forEach { name ->
if (prefs.contains(name) && !prefs.contains(key(0, name))) {
editor.putString(key(0, name), prefs.getString(name, "").orEmpty())
}
editor.remove(name)
}
SECRET_NAMES.forEach { name ->
val legacyValue = prefs.getString(name, "").orEmpty()
if (
legacyValue.isNotBlank() &&
!prefs.contains(encryptedKey(0, name)) &&
!prefs.contains(key(0, name))
) {
editor.putString(encryptedKey(0, name), secureStore.encrypt(legacyValue))
}
editor.remove(name)
}
editor.apply()
}
companion object {
const val PREFS_NAME = "wdtt_outbound_forms"
private const val LOCAL_PROXY_PORT = "local_proxy_port"
private const val LOCAL_PROXY_LOGIN = "local_proxy_login"
private const val LOCAL_PROXY_PASSWORD = "local_proxy_password"
private const val EXTERNAL_PROXY_KIND = "external_proxy_kind"
private const val EXTERNAL_PROXY_HOST = "external_proxy_host"
private const val EXTERNAL_PROXY_PORT = "external_proxy_port"
private const val EXTERNAL_PROXY_LOGIN = "external_proxy_login"
private const val EXTERNAL_PROXY_PASSWORD = "external_proxy_password"
private const val WG_EXIT_HOST = "wg_exit_host"
private const val WG_EXIT_SSH_PORT = "wg_exit_ssh_port"
private const val WG_EXIT_USER = "wg_exit_user"
private const val WG_EXIT_PASSWORD = "wg_exit_password"
private const val WG_EXIT_PORT = "wg_exit_port"
private const val WG_EXIT_DNS = "wg_exit_dns"
private const val WARP_MTU = "warp_mtu"
private const val IMPORTED_WG_CONFIG = "imported_wg_config"
private val NON_SECRET_NAMES = listOf(
LOCAL_PROXY_PORT,
LOCAL_PROXY_LOGIN,
EXTERNAL_PROXY_KIND,
EXTERNAL_PROXY_HOST,
EXTERNAL_PROXY_PORT,
EXTERNAL_PROXY_LOGIN,
WG_EXIT_HOST,
WG_EXIT_SSH_PORT,
WG_EXIT_USER,
WG_EXIT_PORT,
WG_EXIT_DNS,
WARP_MTU,
)
private val SECRET_NAMES = listOf(
LOCAL_PROXY_PASSWORD,
EXTERNAL_PROXY_PASSWORD,
WG_EXIT_PASSWORD,
IMPORTED_WG_CONFIG,
)
internal fun key(profile: Int, name: String): String =
"profile_${profile.coerceIn(0, 2)}_$name"
internal fun encryptedKey(profile: Int, name: String): String =
"${key(profile, name)}_encrypted"
internal fun isSecretPlainKey(key: String): Boolean =
SECRET_NAMES.any { key.endsWith("_$it") || key == it }
}
}
@@ -0,0 +1,212 @@
package com.wdtt.plus.ui
/**
* Android-приложения сервисов, которые остаются доступными при ограничениях
* мобильного интернета, а также приложения, часто ограничивающие работу через VPN.
*
* Список пакетов и названий актуализирован по перечням Минцифры и карточкам
* приложений в российских магазинах. Поиск выполняется только среди уже
* установленных приложений, поэтому отсутствующие пакеты ни на что не влияют.
*/
internal val QuickExclusionExactPackages = setOf(
// Государственные и социальные сервисы
"ru.rostel",
"ru.gosuslugi.goskey",
"com.octopod.russianpost.client.android",
"ru.crptech.mark",
// Банки и платежи
"ru.sberbankmobile",
"ru.tinkoff.mb",
"ru.vtb24.mobilebanking.android",
"ru.alfabank.mobile.android",
"logo.com.mbanking",
"ru.mts.bank",
"ru.lewis.dbo",
"ru.gazprombank.android.mobilebank.app",
"ru.nspk.mirpay",
"ru.nspk.sbpay",
// Соцсети, связь и магазины приложений
"com.vkontakte.android",
"com.vk.im",
"com.vk.vkvideo",
"ru.vk.music",
"ru.ok.android",
"ru.oneme.app",
"ru.mail.mailapp",
"ru.mail.cloud",
"ru.vk.store",
// Маркетплейсы, объявления и работа
"ru.ozon.app.android",
"com.wildberries.ru",
"ru.beru.android",
"ru.megamarket",
"ru.sbermarket",
"ru.instamart",
"ru.samokat.android",
"com.avito.android",
"ru.domclick.mortgage",
"ru.hh.android",
// Яндекс
"ru.yandex.searchplugin",
"ru.yandex.yandexmaps",
"ru.yandex.music",
"ru.kinopoisk",
"com.yandex.browser",
"ru.yandex.taxi",
// Операторы связи
"ru.mts",
"ru.beeline.services",
"ru.tele2.mytele2",
"ru.megafon.mlk",
// Магазины, доставка и рестораны
"ru.vkusvill",
"com.icemobile.lenta.prod",
"ru.reksoft.okey",
"ru.myauchan.droid",
"www.metro.com",
"ru.tander.magnit",
"ru.pyaterochka.app.browser",
"ru.perekrestok.app",
"club.chizhik",
"com.logistic.sdek",
"ru.dodopizza.app",
"ru.burgerking",
"com.apegroup.mcdonaldsrussia",
// Транспорт, навигация и путешествия
"ru.dublgis.dgismobile",
"ru.rzd.pass",
"ru.tutu.tutu_emp",
"com.carshering",
"youdrive.today",
"com.belkacar",
"ru.aeroflot",
"com.taxsee.taxsee",
"ru.maximoff.max",
// Видео, музыка, новости и погода
"ru.rutube.app",
"ru.ivi.client",
"ru.more.play",
"ru.zen.android",
"gpm.tnt_premier",
"ru.mts.mtstv",
"ru.radioplayer",
"com.gismeteo.client",
)
internal val QuickExclusionKeywords = listOf(
"sber", "сбер",
"tinkoff", "t-bank", "tbank", "тинькофф", "т-банк", "тбанк",
"vtb", "втб",
"alfa", "alpha", "альфа",
"psbank", "промсвязьбанк", "псб",
"gazprombank", "газпромбанк",
"mir pay", "mirpay", "мир пэй",
"sbpay", "сбпэй",
"ozon", "озон",
"wildberries", "вайлдберриз",
"yandex", "яндекс",
"vkontakte", "вконтакте",
"rutube", "рутуб",
"gosuslugi", "госуслуг", "госключ",
"честный знак",
"dublgis", "2gis", "dgis", "дубльгис",
"avito", "авито",
"domclick", "домклик",
"headhunter", "hh.ru",
"mts", "мтс",
"beeline", "билайн",
"megafon", "мегафон",
"tele2", "теле2",
"mail.ru", "mailapp",
"ok.ru", "odnoklassniki", "одноклассники",
"kinopoisk", "кинопоиск",
"samokat", "самокат",
"megamarket", "мегамаркет", "sbermarket",
"kuper", "купер", "instamart",
"rostel", "ростел",
"почта россии", "russianpost",
"max: общение", "макс: общение", "oneme",
"vkusvill", "вкусвилл",
"lenta.prod", "лента – доставка", "лента - доставка",
"okeydostavka", "гипермаркеты и доставка",
"myauchan", "мой ашан",
"metro: продукты", "метро: продукты",
"tander.magnit", "магнит: акции",
"pyaterochka", "пятёрочка:", "пятерочка:",
"perekrestok", "перекрёсток доставка", "перекресток доставка",
"club.chizhik", "чижик - доставка", "чижик — доставка",
"cdek", "сдэк",
"dostavista", "достависта",
"dodopizza", "додо пицца",
"burgerking", "бургер кинг",
"mcdonaldsrussia", "вкусно — и точка", "вкусно - и точка",
"детский мир", "detmir",
"петрович", "petrovich",
"spar —", "spar -", "мой spar",
"дикси", "dixy",
"vprok", "впрок",
"5post", "fivepost",
"много лосося",
"rzd.pass", "ржд пассажирам",
"tutu", "туту:",
"carshering", "делимобиль",
"citydrive", "ситидрайв", "youdrive",
"belkacar", "белкаcar",
"aeroflot", "аэрофлот",
"pobeda", "победа",
"s7 airlines",
"деловые линии",
"гранд сервис экспресс",
"taxsee", "maxim — заказ такси", "maxim - заказ такси", "maximoff",
"gismeteo", "гисметео",
"ivi.client", "иви:",
"more.play", "okko:",
"zen.android", "дзен",
"tnt_premier", "premier —", "premier -",
"mtstv", "кион",
"radioplayer", "радиоплеер",
"medsi", "медси",
"мать и дитя",
"iomt.istok",
"сателлит online",
"м-лайн", "m-line",
"inme",
"yuwell anytime",
"follow anytime", "anytime follow",
"ican health", "ican reach",
"mq cgm",
"freestyle libre",
"medtrum",
"syai link",
"poctech cgm",
"hematonix",
"дианянь",
"lumipod", "glutec", "lumiflex",
"trueconf", "труконф",
"лизаалерт",
"рувики",
"добро.рф",
"цезарь сателлит",
"тензор",
"скб контур",
"эвотор",
"мп. инспектор",
"1с:",
"hrlink",
"кхл",
)
internal fun matchesQuickExclusionApp(name: String, packageName: String): Boolean {
val packageLower = packageName.lowercase()
if (packageLower in QuickExclusionExactPackages) return true
val haystack = "$packageLower ${name.lowercase()}"
return QuickExclusionKeywords.any(haystack::contains)
}
@@ -128,6 +128,8 @@ import com.wdtt.plus.ServerClientCreateRequest
import com.wdtt.plus.ServerClientInfo
import com.wdtt.plus.ServerTrafficPeriod
import com.wdtt.plus.TransferFiles
import com.wdtt.plus.WdttDocument
import com.wdtt.plus.VkJoinLink
import com.wdtt.plus.WDTTColors
import com.wdtt.plus.connectionLink
import kotlinx.coroutines.Dispatchers
@@ -163,6 +165,21 @@ private enum class ClientVkHashFilter { All, Present, Missing }
private enum class ClientsServerRefreshState { Unknown, Ready, Error }
private data class ClientQrData(
val title: String,
val bitmap: Bitmap,
val missingVkHashes: Boolean
)
private fun vkHashInputError(value: String): String? {
if (value.isBlank()) return null
return if (VkJoinLink.normalizeHashes(value) == null) {
"Проверьте VK-хеш: допустимы латинские буквы, цифры, _ и - либо ссылка VK-звонка."
} else {
null
}
}
internal fun serverClientsAccessIssue(
host: String,
hostValid: Boolean,
@@ -354,7 +371,7 @@ fun ServerClientsSection(
var changedPasswordClient by remember { mutableStateOf<ServerClientInfo?>(null) }
var pendingAction by remember { mutableStateOf<PendingClientAction?>(null) }
var expiryClient by remember { mutableStateOf<ServerClientInfo?>(null) }
var qrData by remember { mutableStateOf<Pair<String, Bitmap>?>(null) }
var qrData by remember { mutableStateOf<ClientQrData?>(null) }
var detailsClient by remember { mutableStateOf<ServerClientInfo?>(null) }
var showServerTools by rememberSaveable { mutableStateOf(false) }
var createdClient by remember { mutableStateOf<ServerClientInfo?>(null) }
@@ -814,10 +831,16 @@ fun ServerClientsSection(
scope.launch {
runCatching {
withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(context, "WDTT-Plus-${selectedClient.safeFileName()}.wdtt", link)
TransferFiles.writeTransferText(
context,
WdttDocument.fileName(
"WDTT-Plus-${selectedClient.safeFileName()}"
),
link
)
}
}.onSuccess {
shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus")
shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus")
}.onFailure {
Toast.makeText(context, it.message ?: "Не удалось создать файл.", Toast.LENGTH_LONG).show()
}
@@ -827,7 +850,13 @@ fun ServerClientsSection(
scope.launch {
runCatching {
withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) }
}.onSuccess { qrData = selectedClient.displayName() to it }
}.onSuccess {
qrData = ClientQrData(
title = selectedClient.displayName(),
bitmap = it,
missingVkHashes = selectedClient.vkHash.isBlank()
)
}
.onFailure { Toast.makeText(context, it.message ?: "Не удалось создать QR.", Toast.LENGTH_LONG).show() }
}
},
@@ -1039,7 +1068,13 @@ fun ServerClientsSection(
onQr = {
scope.launch {
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, transfer) } }
.onSuccess { qrData = "Перенос: ${client.displayName()}" to it }
.onSuccess {
qrData = ClientQrData(
title = "Перенос: ${client.displayName()}",
bitmap = it,
missingVkHashes = client.vkHash.isBlank()
)
}
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
}
},
@@ -1050,7 +1085,12 @@ fun ServerClientsSection(
TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt-client", transfer)
}
}.onSuccess {
shareUri(context, it, "application/vnd.wdtt.plus.client", "Передать клиента WDTT Plus")
shareUri(
context,
it,
WdttDocument.LEGACY_CLIENT_MIME_TYPE,
"Передать клиента WDTT Plus"
)
}.onFailure { status = "Ошибка: ${it.message ?: "файл клиента не создан"}" }
}
}
@@ -1119,7 +1159,8 @@ fun ServerClientsSection(
title = "Клиент создан",
password = client.password,
link = link,
noLinkText = "VK-хеш не задан. Пароль уже работает; ссылку, QR и файл можно создать после добавления хеша в «Подробнее».",
missingVkHashes = client.vkHash.isBlank(),
noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.",
onDismiss = { createdClient = null },
onCopyPassword = { copyText(context, "Пароль WDTT", client.password) },
onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } },
@@ -1128,7 +1169,9 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
.onSuccess { qrData = client.displayName() to it }
.onSuccess {
qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank())
}
.onFailure { Toast.makeText(context, it.message ?: "Не удалось создать QR.", Toast.LENGTH_LONG).show() }
}
}
@@ -1137,8 +1180,14 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching {
withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) }
}.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") }
withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(
context,
WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"),
value
)
}
}.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus") }
.onFailure { Toast.makeText(context, it.message ?: "Не удалось создать файл.", Toast.LENGTH_LONG).show() }
}
}
@@ -1157,7 +1206,8 @@ fun ServerClientsSection(
statusText = "Клиент импортирован и найден в списке.",
password = client.password,
link = link,
noLinkText = "VK-хеш не задан. Клиент добавлен; хеш можно указать в «Подробнее».",
missingVkHashes = client.vkHash.isBlank(),
noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.",
onDismiss = { importedClient = null },
onCopyPassword = { copyText(context, "Пароль импортированного клиента", client.password) },
onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } },
@@ -1166,7 +1216,9 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
.onSuccess { qrData = client.displayName() to it }
.onSuccess {
qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank())
}
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
}
}
@@ -1175,8 +1227,14 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching {
withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) }
}.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") }
withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(
context,
WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"),
value
)
}
}.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus") }
.onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" }
}
}
@@ -1194,7 +1252,8 @@ fun ServerClientsSection(
title = "Пароль изменён",
password = client.password,
link = link,
noLinkText = "VK-хеш не задан. Новый пароль уже работает; добавьте хеш в «Подробнее», чтобы сформировать ссылку.",
missingVkHashes = client.vkHash.isBlank(),
noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.",
onDismiss = { changedPasswordClient = null },
onCopyPassword = { copyText(context, "Новый пароль WDTT", client.password) },
onCopyLink = { link?.let { copyText(context, "Новая ссылка WDTT", it) } },
@@ -1203,7 +1262,9 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
.onSuccess { qrData = client.displayName() to it }
.onSuccess {
qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank())
}
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
}
}
@@ -1212,8 +1273,14 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching {
withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) }
}.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать новое подключение WDTT Plus") }
withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(
context,
WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"),
value
)
}
}.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать новое подключение WDTT Plus") }
.onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" }
}
}
@@ -1287,17 +1354,18 @@ fun ServerClientsSection(
}
}
qrData?.let { (title, bitmap) ->
qrData?.let { qr ->
ClientQrDialog(
title = title,
bitmap = bitmap,
title = qr.title,
bitmap = qr.bitmap,
missingVkHashes = qr.missingVkHashes,
onDismiss = { qrData = null },
onShare = {
scope.launch {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val fileName = "WDTT-Plus-QR-${title.safeQrFileName()}-$stamp.png"
val fileName = "WDTT-Plus-QR-${qr.title.safeQrFileName()}-$stamp.png"
runCatching {
withContext(Dispatchers.IO) { TransferFiles.writeQrPng(context, fileName, bitmap) }
withContext(Dispatchers.IO) { TransferFiles.writeQrPng(context, fileName, qr.bitmap) }
}.onSuccess { shareUri(context, it, "image/png", "Передать QR-код WDTT Plus") }
.onFailure { Toast.makeText(context, it.message ?: "Не удалось поделиться QR.", Toast.LENGTH_LONG).show() }
}
@@ -1305,8 +1373,11 @@ fun ServerClientsSection(
onSave = {
scope.launch {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val fileName = "WDTT-Plus-QR-${qr.title.safeQrFileName()}-$stamp.png"
runCatching {
withContext(Dispatchers.IO) { TransferFiles.saveQrToGallery(context, "WDTT-Plus-client-$stamp.png", bitmap) }
withContext(Dispatchers.IO) {
TransferFiles.saveQrToGallery(context, fileName, qr.bitmap)
}
}.onSuccess {
Toast.makeText(context, "QR-код сохранён.", Toast.LENGTH_SHORT).show()
}.onFailure {
@@ -1394,7 +1465,7 @@ private fun ServerClientCard(
)
if (client.vkHash.isBlank()) {
Text(
"VK-хеш не задан: быструю ссылку/QR создать нельзя, пока не обновить хеш.",
"VK-хеш не задан: доступ можно передать, но клиенту нужно добавить свой перед запуском.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
@@ -1684,6 +1755,7 @@ private fun AccessResultDialog(
statusText: String? = null,
password: String,
link: String?,
missingVkHashes: Boolean,
noLinkText: String,
onDismiss: () -> Unit,
onCopyPassword: () -> Unit,
@@ -1718,7 +1790,15 @@ private fun AccessResultDialog(
if (link == null) {
Text(noLinkText, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
} else {
Text("Ссылка содержит пароль и VK-хеш. Не публикуйте её.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
Text(
if (missingVkHashes) {
"VK-хеш не задан. Передать можно, но клиенту нужно добавить свой перед запуском."
} else {
"Ссылка содержит пароль и VK-хеш. Не публикуйте её."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
FlowRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
@@ -1754,6 +1834,7 @@ private fun ClientDetailsDialog(
var hash by rememberSaveable(client.password) { mutableStateOf(client.vkHash) }
var ports by rememberSaveable(client.password) { mutableStateOf(client.ports) }
val portsValid = ports.isPortsSpec()
val hashError = vkHashInputError(hash)
val link = remember(client, fallbackHost, publicHost, sourceProfileName) {
client.connectionLink(fallbackHost, publicHost, sourceProfileName)
}
@@ -1854,8 +1935,10 @@ private fun ClientDetailsDialog(
)
OutlinedTextField(
value = hash,
onValueChange = { hash = it },
onValueChange = { hash = it.take(4096) },
label = { Text("VK-хеш или ссылка") },
supportingText = { hashError?.let { Text(it) } },
isError = hashError != null,
minLines = 2,
modifier = Modifier.fillMaxWidth()
)
@@ -1903,7 +1986,10 @@ private fun ClientDetailsDialog(
},
confirmButton = {
if (step == ClientDetailsStep.Edit) {
Button(onClick = { onSave(label, hash, ports) }, enabled = !busy && portsValid) { Text("Сохранить") }
Button(
onClick = { onSave(label, hash, ports) },
enabled = !busy && portsValid && hashError == null
) { Text("Сохранить") }
}
}
)
@@ -1949,7 +2035,8 @@ private fun ServerToolsDialog(
ServerToolsStep.Overview -> {
Text("Состояние", fontWeight = FontWeight.Bold)
InfoLine("Клиенты", "${state.passwordCount}/${state.maxPasswords}")
InfoLine("Устройства", state.deviceCount.toString())
InfoLine("Устройства клиентов", state.deviceCount.toString())
InfoLine("Устройства владельца", state.ownerDeviceCount.toString())
InfoLine("Истёкшие", state.expiredCount.toString())
InfoLine("Забытые устройства", state.orphanDeviceCount.toString())
InfoLine(
@@ -2549,6 +2636,7 @@ private fun CreateClientWizardDialog(
var customPassword by rememberSaveable { mutableStateOf("") }
val effectivePorts = if (useDefaultPorts) defaultPorts else customPorts
val portsValid = effectivePorts.isPortsSpec()
val hashError = vkHashInputError(vkHash)
val passwordError = if (useAutoPassword || customPassword.isEmpty()) null else when {
ClientPasswordRules.validate(customPassword) != null -> ClientPasswordRules.validate(customPassword)
customPassword == mainPassword -> "Пароль клиента не должен совпадать с главным паролем."
@@ -2614,11 +2702,16 @@ private fun CreateClientWizardDialog(
}
ClientWizardStep.Hash -> {
Text("VK-хеш", fontWeight = FontWeight.Bold)
Text("Нужен для быстрой ссылки, QR и файла. Можно вставить сам хеш или ссылку приглашения.", style = MaterialTheme.typography.bodySmall)
Text(
"Лучше добавить перед передачей. Без хеша доступ тоже можно отправить, но клиенту придётся добавить свой.",
style = MaterialTheme.typography.bodySmall
)
OutlinedTextField(
value = vkHash,
onValueChange = { vkHash = it },
onValueChange = { vkHash = it.take(4096) },
label = { Text("Хеш или ссылка") },
supportingText = { hashError?.let { Text(it) } },
isError = hashError != null,
minLines = 2,
modifier = Modifier.fillMaxWidth()
)
@@ -2682,6 +2775,13 @@ private fun CreateClientWizardDialog(
Text("VK-хеш: ${if (vkHash.isBlank()) "не задан" else "задан"}")
Text("Порты: $effectivePorts")
Text("Пароль: ${if (useAutoPassword) "будет создан автоматически" else customPassword}")
if (vkHash.isBlank()) {
Text(
"Без VK-хеша клиент добавит свой перед запуском.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
}
Text(
"Новый доступ начнёт работать сразу, текущие подключения не прервутся.",
style = MaterialTheme.typography.bodySmall,
@@ -2696,6 +2796,7 @@ private fun CreateClientWizardDialog(
confirmButton = {
Button(
enabled = !busy &&
(step != ClientWizardStep.Hash || hashError == null) &&
(step != ClientWizardStep.Ports || portsValid) &&
(step != ClientWizardStep.Password || passwordValid),
onClick = {
@@ -2811,6 +2912,7 @@ private fun ExtendClientDialog(
private fun ClientQrDialog(
title: String,
bitmap: Bitmap,
missingVkHashes: Boolean,
onDismiss: () -> Unit,
onShare: () -> Unit,
onSave: () -> Unit
@@ -2837,7 +2939,15 @@ private fun ClientQrDialog(
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Image(bitmap = bitmap.asImageBitmap(), contentDescription = "QR-код WDTT Plus", modifier = Modifier.fillMaxWidth())
}
Text("QR содержит пароль и VK-хеш. Не публикуйте изображение.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
Text(
if (missingVkHashes) {
"VK-хеш не задан. Клиенту нужно добавить свой перед запуском."
} else {
"QR содержит пароль и VK-хеш. Не публикуйте изображение."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,35 @@
package com.wdtt.plus.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
internal fun StableSegmentedButtonIcon(selected: Boolean) {
Box(
modifier = Modifier.size(18.dp),
contentAlignment = Alignment.Center
) {
AnimatedVisibility(
visible = selected,
enter = fadeIn(tween(120)),
exit = fadeOut(tween(90))
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
}
}
}
@@ -64,6 +64,7 @@ import com.journeyapps.barcodescanner.ScanOptions
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TransferFiles
import com.wdtt.plus.WdttTransferCodec
import com.wdtt.plus.WdttDocument
import com.wdtt.plus.QrCaptureActivity
import com.wdtt.plus.vpnProfileDisplayName
import kotlinx.coroutines.Dispatchers
@@ -112,7 +113,7 @@ fun TransferCenterDialog(
onIncomingContent(text)
}
}
val fileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
val fileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) runCatchingUi {
val text = withContext(Dispatchers.IO) { TransferFiles.readText(context, uri) }
onIncomingContent(text)
@@ -129,6 +130,12 @@ fun TransferCenterDialog(
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Box(modifier = Modifier.fillMaxWidth()) {
Text(
"Получение/Передача",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
modifier = Modifier.align(androidx.compose.ui.Alignment.CenterStart),
)
IconButton(
onClick = onDismiss,
enabled = !busy,
@@ -137,7 +144,14 @@ fun TransferCenterDialog(
Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
}
}
Text("Получение VPN", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text("Получить профиль", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"Добавьте профиль через камеру, изображение или файл. "
+ "Если сервис выдал обновление, приложение применит его "
+ "к связанному профилю.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
FlowRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -154,11 +168,13 @@ fun TransferCenterDialog(
)
}
TransferButton("Галерея", Icons.Default.Image, busy) { galleryLauncher.launch("image/*") }
TransferButton("Файл", Icons.Default.FileOpen, busy) { fileLauncher.launch("*/*") }
TransferButton("Файл", Icons.Default.FileOpen, busy) {
fileLauncher.launch(WdttDocument.acceptedMimeTypes())
}
}
HorizontalDivider()
Text("Передача $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text("Передать $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"Ссылка содержит пароль подключения и VK-хеши. Передавайте её только тому, кому доверяете.",
style = MaterialTheme.typography.bodySmall,
@@ -185,9 +201,15 @@ fun TransferCenterDialog(
runCatchingUi {
val link = settingsStore.connectionLinkForProfile(activeProfile)
val uri = withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(context, "WDTT-Plus-${activeProfileLabel.safeTransferFileName()}.wdtt", link)
TransferFiles.writeTransferText(
context,
WdttDocument.fileName(
"WDTT-Plus-${activeProfileLabel.safeTransferFileName()}"
),
link
)
}
shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus")
shareUri(context, uri, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus")
}
}
}
@@ -253,7 +275,12 @@ fun TransferCenterDialog(
val uri = withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(context, "WDTT-Plus-admin-$stamp.wdtt-backup", encrypted)
}
shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать настройки WDTT Plus")
shareUri(
context,
uri,
WdttDocument.LEGACY_TRANSFER_MIME_TYPE,
"Передать настройки WDTT Plus"
)
}
}
}
@@ -279,9 +306,10 @@ fun TransferCenterDialog(
onSave = {
scope.launch {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val fileName = "WDTT-Plus-QR-${title.safeQrFileName()}-$stamp.png"
runCatching {
withContext(Dispatchers.IO) {
TransferFiles.saveQrToGallery(context, "WDTT-Plus-QR-$stamp.png", bitmap)
TransferFiles.saveQrToGallery(context, fileName, bitmap)
}
}.onSuccess {
Toast.makeText(context, "QR-код сохранён в галерею.", Toast.LENGTH_SHORT).show()
@@ -0,0 +1,940 @@
package com.wdtt.plus.ui
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.VpnKey
import androidx.compose.material.icons.filled.WarningAmber
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.plus.BUILT_IN_VK_CLIENT_IDS
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.isValidVkClientId
import com.wdtt.plus.normalizeVkClientId
import com.wdtt.plus.normalizeVkClientSecret
import java.security.MessageDigest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import kotlin.math.ceil
import kotlin.math.max
private const val VK_CLIENT_ID_PROBE_VERSION = 3
internal const val VK_CLIENT_ID_PROBE_COOLDOWN_MS = 10_000L
private const val VK_CLIENT_ID_PROBE_CHECKED_AT = "_checked_at"
private const val VK_ID_CABINET_URL = "https://id.vk.ru/about/business/go/"
internal enum class VkClientIdProbeStatus {
LegacyCompatible,
LegacyRejected,
CheckFailed
}
internal data class VkClientIdProbeCache(
val results: Map<String, VkClientIdProbeStatus>,
val checkedAt: Long
)
internal fun vkClientIdProbeCooldownRemainingMillis(now: Long, lastStartedAt: Long): Long {
if (lastStartedAt <= 0L) return 0L
val elapsed = (now - lastStartedAt).coerceAtLeast(0L)
return (VK_CLIENT_ID_PROBE_COOLDOWN_MS - elapsed).coerceAtLeast(0L)
}
internal fun vkClientIdAvailabilityMessage(
ids: List<String>,
results: Map<String, VkClientIdProbeStatus>
): String {
val cleanIds = ids.map(String::trim).filter(String::isNotEmpty).distinct()
val available = cleanIds.filter { results[it] == VkClientIdProbeStatus.LegacyCompatible }
val rejected = cleanIds.filter { results[it] == VkClientIdProbeStatus.LegacyRejected }
val failed = cleanIds.filter { results[it] == VkClientIdProbeStatus.CheckFailed }
return when {
cleanIds.size == 1 && available.isNotEmpty() ->
"Client ID ${cleanIds.first()} принимается резервным способом"
cleanIds.size == 1 && rejected.isNotEmpty() ->
"Client ID ${cleanIds.first()} не принимается резервным способом"
cleanIds.size == 1 ->
"Не удалось проверить Client ID ${cleanIds.first()}: сеть или временная ошибка VK"
rejected.isEmpty() && failed.isEmpty() -> "Все встроенные Client ID доступны для резервного способа"
else -> buildList {
if (available.isNotEmpty()) add("Доступны: ${available.joinToString(", ")}")
if (rejected.isNotEmpty()) add("Не принимаются: ${rejected.joinToString(", ")}")
if (failed.isNotEmpty()) add("Не удалось проверить: ${failed.joinToString(", ")}")
}.joinToString(". ", postfix = ".")
}
}
internal fun vkClientIdsForAutomaticProbe(
customCredentialsEnabled: Boolean,
customClientId: String,
customClientSecret: String
): List<String> = if (customCredentialsEnabled) {
customClientId.trim().takeIf(::isValidVkClientId)
?.takeIf { customClientSecret.trim().isNotEmpty() }
?.let(::listOf)
.orEmpty()
} else {
BUILT_IN_VK_CLIENT_IDS
}
private object VkClientIdProbeRateLimiter {
private var lastStartedAt = 0L
@Synchronized
fun acquire(now: Long, persistedCheckedAt: Long): Long {
val effectiveLastStartedAt = max(lastStartedAt, persistedCheckedAt)
val remaining = vkClientIdProbeCooldownRemainingMillis(now, effectiveLastStartedAt)
if (remaining == 0L) lastStartedAt = now
return remaining
}
}
@Composable
fun VkClientSettingsDialog(
settingsStore: SettingsStore,
activeClientIds: String,
onClientIdsChange: (String) -> Unit,
onDismiss: () -> Unit
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val configuration = LocalConfiguration.current
val enabledState by remember(settingsStore) {
settingsStore.customVkCredentialsEnabled.map { it as Boolean? }
}.collectAsStateWithLifecycle(initialValue = null)
val savedClientIdState by remember(settingsStore) {
settingsStore.customVkClientId.map { it as String? }
}.collectAsStateWithLifecycle(initialValue = null)
val savedClientSecretState by remember(settingsStore) {
settingsStore.customVkClientSecret.map { it as String? }
}.collectAsStateWithLifecycle(initialValue = null)
val checkResultsJsonState by remember(settingsStore) {
settingsStore.clientIdCheckResults.map { it as String? }
}.collectAsStateWithLifecycle(initialValue = null)
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
val enabled = enabledState == true
val savedClientId = savedClientIdState.orEmpty()
val savedClientSecret = savedClientSecretState.orEmpty()
val settingsReady = enabledState != null && savedClientIdState != null &&
savedClientSecretState != null && checkResultsJsonState != null
val probeCache = remember(checkResultsJsonState) {
parseVkClientIdCheckResults(checkResultsJsonState.orEmpty())
}
val checkResults = probeCache.results
val builtInSelection = remember(activeClientIds) {
activeClientIds.split(',').map { it.trim() }.filter { it.isNotEmpty() }
}
var clientIdInput by rememberSaveable { mutableStateOf("") }
var clientSecretInput by rememberSaveable { mutableStateOf("") }
var inputsInitialized by rememberSaveable { mutableStateOf(false) }
var secretFocused by remember { mutableStateOf(false) }
var checkingIds by remember { mutableStateOf<Set<String>>(emptySet()) }
var showHelp by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(settingsReady) {
if (settingsReady && !inputsInitialized) {
clientIdInput = savedClientId
clientSecretInput = savedClientSecret
inputsInitialized = true
}
}
val normalizedClientId = normalizeVkClientId(clientIdInput)
val normalizedClientSecret = normalizeVkClientSecret(clientSecretInput)
val customInputComplete = isValidVkClientId(normalizedClientId) && normalizedClientSecret.isNotBlank()
val hasUnsavedChanges = inputsInitialized && (
normalizedClientId != savedClientId || normalizedClientSecret != savedClientSecret
)
fun checkIds(ids: List<String>, manual: Boolean) {
val cleanIds = ids.map(String::trim).filter(::isValidVkClientId).distinct()
if (cleanIds.isEmpty()) return
if (checkingIds.isNotEmpty()) {
if (manual) Toast.makeText(context, "Проверка уже выполняется", Toast.LENGTH_SHORT).show()
return
}
val startedAt = System.currentTimeMillis()
val cooldownRemaining = VkClientIdProbeRateLimiter.acquire(startedAt, probeCache.checkedAt)
if (cooldownRemaining > 0L) {
if (manual) {
val seconds = ceil(cooldownRemaining / 1_000.0).toInt().coerceAtLeast(1)
Toast.makeText(
context,
"Повторная проверка будет доступна через $seconds с",
Toast.LENGTH_SHORT
).show()
}
return
}
checkingIds = cleanIds.toSet()
scope.launch {
try {
val checkedNow = withContext(Dispatchers.IO) {
buildMap {
cleanIds.forEach { id ->
put(id, checkVkClientId(id))
}
}
}
val freshResults = checkResults.toMutableMap().apply { putAll(checkedNow) }
settingsStore.saveClientIdCheckResults(
encodeVkClientIdCheckResults(freshResults, startedAt)
)
Toast.makeText(
context,
vkClientIdAvailabilityMessage(cleanIds, checkedNow),
Toast.LENGTH_LONG
).show()
} finally {
checkingIds = emptySet()
}
}
}
LaunchedEffect(settingsReady, enabled, savedClientId, savedClientSecret) {
if (settingsReady) {
checkIds(
vkClientIdsForAutomaticProbe(enabled, savedClientId, savedClientSecret),
manual = false
)
}
}
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.fillMaxHeight(0.9f)
.heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)),
shape = RoundedCornerShape(30.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp,
shadowElevation = 8.dp
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) {
Icon(Icons.Default.VpnKey, contentDescription = null, modifier = Modifier.size(25.dp))
}
}
Column(modifier = Modifier.weight(1f)) {
Text(
"Клиенты VK",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
"Настройка для текущего VPN-профиля",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
if (!settingsReady) {
Box(
modifier = Modifier.fillMaxWidth().height(180.dp),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
} else {
if (tunnelRunning) {
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.errorContainer
) {
Text(
"VPN сейчас работает. Чтобы изменить резервные Client ID, сначала выключите VPN. Проверка доступности остаётся доступной.",
modifier = Modifier.padding(14.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer,
fontWeight = FontWeight.SemiBold
)
}
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
) {
Row(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text("Собственные резервные реквизиты", fontWeight = FontWeight.SemiBold)
Text(
if (enabled) {
"После быстрого VKCalls сначала пробуется ваш Client ID."
} else {
"После быстрого VKCalls используются встроенные Client ID."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Switch(
checked = enabled,
enabled = !tunnelRunning,
onCheckedChange = { checked ->
scope.launch { settingsStore.saveCustomVkCredentialsEnabled(checked) }
}
)
}
}
if (enabled) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text("Резервные реквизиты приложения VK", fontWeight = FontWeight.Bold)
Text(
"Оба поля обязательны",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = { showHelp = true }) {
Icon(
Icons.AutoMirrored.Filled.HelpOutline,
contentDescription = "Как получить Client ID и secret"
)
}
}
OutlinedTextField(
value = clientIdInput,
onValueChange = { clientIdInput = normalizeVkClientId(it) },
modifier = Modifier.fillMaxWidth(),
label = { Text("Client ID") },
supportingText = { Text("ID приложения из кабинета VK ID") },
enabled = !tunnelRunning,
singleLine = true,
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = KeyboardType.Number
)
)
OutlinedTextField(
value = clientSecretInput,
onValueChange = { clientSecretInput = it.take(512) },
modifier = Modifier
.fillMaxWidth()
.onFocusChanged { secretFocused = it.isFocused },
label = { Text("Client secret") },
supportingText = {
Text("Защищённый ключ скрывается после выхода из поля")
},
enabled = !tunnelRunning,
singleLine = true,
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = KeyboardType.Password
),
visualTransformation = if (secretFocused) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
}
)
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.45f)
) {
Text(
"Защищённый ключ сохраняется в зашифрованном виде через Android Keystore и не добавляется в журналы.",
modifier = Modifier.padding(13.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer
)
}
if (hasUnsavedChanges) {
Text(
"Есть несохранённые изменения",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.tertiary,
fontWeight = FontWeight.SemiBold
)
}
Button(
onClick = {
scope.launch {
settingsStore.saveCustomVkCredentials(
normalizedClientId,
normalizedClientSecret
)
clientIdInput = normalizedClientId
clientSecretInput = normalizedClientSecret
Toast.makeText(context, "Реквизиты сохранены", Toast.LENGTH_SHORT).show()
}
},
enabled = !tunnelRunning && customInputComplete && hasUnsavedChanges,
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp)
) {
Text("Сохранить")
}
val customProbeResult = checkResults[normalizedClientId]
OutlinedButton(
onClick = { checkIds(listOf(normalizedClientId), manual = true) },
enabled = isValidVkClientId(normalizedClientId) && checkingIds.isEmpty(),
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp)
) {
Text(if (normalizedClientId in checkingIds) "Проверка…" else "Проверить Client ID")
}
if (customProbeResult != null && normalizedClientId !in checkingIds) {
val statusColor = when (customProbeResult) {
VkClientIdProbeStatus.LegacyCompatible -> MaterialTheme.colorScheme.primaryContainer
VkClientIdProbeStatus.LegacyRejected -> MaterialTheme.colorScheme.errorContainer
VkClientIdProbeStatus.CheckFailed -> MaterialTheme.colorScheme.tertiaryContainer
}
val statusContentColor = when (customProbeResult) {
VkClientIdProbeStatus.LegacyCompatible -> MaterialTheme.colorScheme.onPrimaryContainer
VkClientIdProbeStatus.LegacyRejected -> MaterialTheme.colorScheme.onErrorContainer
VkClientIdProbeStatus.CheckFailed -> MaterialTheme.colorScheme.onTertiaryContainer
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = statusColor
) {
Row(
modifier = Modifier.fillMaxWidth().padding(13.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Icon(
imageVector = when (customProbeResult) {
VkClientIdProbeStatus.LegacyCompatible -> Icons.Default.CheckCircle
VkClientIdProbeStatus.LegacyRejected -> Icons.Default.Cancel
VkClientIdProbeStatus.CheckFailed -> Icons.Default.WarningAmber
},
contentDescription = null,
tint = statusContentColor
)
Text(
text = when (customProbeResult) {
VkClientIdProbeStatus.LegacyCompatible ->
"Client ID принимается резервным способом"
VkClientIdProbeStatus.LegacyRejected ->
"Client ID не принимается резервным способом"
VkClientIdProbeStatus.CheckFailed ->
"Проверку выполнить не удалось: сеть или временная ошибка VK"
},
style = MaterialTheme.typography.bodySmall,
color = statusContentColor,
fontWeight = FontWeight.SemiBold
)
}
}
}
Text(
"Сохранённый собственный Client ID проверяется автоматически при входе. Это второй вариант после VKCalls. Такая проверка подтверждает только приём ID старым способом VK; получение TURN-данных окончательно проверяется при подключении.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Text("Встроенный резерв", fontWeight = FontWeight.Bold)
Text(
if (enabled) {
"Используется, если VKCalls и собственные реквизиты не сработали. Встроенный ID можно проверить нажатием на строку."
} else {
"Используется, если VKCalls не сработал. Проверка запускается автоматически при входе; нажмите на строку для повтора."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
BUILT_IN_VK_CLIENT_IDS.forEach { id ->
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.42f),
onClick = { checkIds(listOf(id), manual = true) }
) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = id in builtInSelection,
enabled = !tunnelRunning,
onCheckedChange = { checked ->
val updated = if (checked) {
(builtInSelection + id).distinct()
} else {
builtInSelection - id
}
if (updated.isNotEmpty()) {
onClientIdsChange(updated.joinToString(","))
} else {
Toast.makeText(
context,
"Нельзя отключить все Client ID: без них программа перестанет работать",
Toast.LENGTH_LONG
).show()
}
}
)
Column(modifier = Modifier.weight(1f)) {
Text(id, fontWeight = FontWeight.SemiBold)
Text(
if (id in builtInSelection) "Выбран для резерва" else "Отключён",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Box(
modifier = Modifier.size(36.dp),
contentAlignment = Alignment.Center
) {
when {
id in checkingIds -> CircularProgressIndicator(
modifier = Modifier.size(22.dp),
strokeWidth = 2.5.dp
)
checkResults[id] == VkClientIdProbeStatus.LegacyCompatible -> Icon(
Icons.Default.CheckCircle,
contentDescription = "Client ID доступен для резервного способа",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
checkResults[id] == VkClientIdProbeStatus.LegacyRejected -> Icon(
Icons.Default.Cancel,
contentDescription = "Client ID недоступен для резервного способа",
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(24.dp)
)
checkResults[id] == VkClientIdProbeStatus.CheckFailed -> Icon(
Icons.Default.WarningAmber,
contentDescription = "Не удалось проверить Client ID",
tint = MaterialTheme.colorScheme.tertiary,
modifier = Modifier.size(24.dp)
)
else -> Text(
"—",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f))
Text(
if (enabled) {
"Порядок подключения: быстрый VKCalls без капчи → собственные реквизиты → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически."
} else {
"Порядок подключения: быстрый VKCalls без капчи → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
if (showHelp) {
VkClientCredentialsHelpDialog(onDismiss = { showHelp = false })
}
}
@Composable
private fun VkClientCredentialsHelpDialog(onDismiss: () -> Unit) {
val context = LocalContext.current
val clipboard = LocalClipboardManager.current
val configuration = LocalConfiguration.current
val packageName = context.packageName
val signingSha1 = remember(context) { appSigningSha1(context) }
fun copy(value: String, message: String) {
clipboard.setText(AnnotatedString(value))
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.fillMaxHeight(0.9f)
.heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)),
shape = RoundedCornerShape(30.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 10.dp,
shadowElevation = 10.dp
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
"Резервные реквизиты VK",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
"Резервный провайдер через кабинет VK ID",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.65f)
) {
Text(
"Собственные реквизиты относятся только к резервному legacy-провайдеру. Для основного быстрого VKCalls они не нужны. Понадобятся ID приложения и Защищённый ключ из одного приложения VK; сервисный ключ доступа не подходит.",
modifier = Modifier.padding(14.dp),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer
)
}
HelpStep(
number = 1,
title = "Откройте кабинет VK ID",
text = "Войдите в аккаунт владельца приложения, откройте раздел «Мои приложения» и нажмите «Добавить приложение»."
)
Button(
onClick = {
runCatching {
context.startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse(VK_ID_CABINET_URL)))
}
},
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp)
) {
Text("Открыть кабинет VK ID")
}
HelpStep(
number = 2,
title = "Создайте Android-приложение",
text = "Укажите понятное название, выберите платформу Android, затем заполните имя пакета и SHA-1 подписи установленного APK."
)
CopyValueCard(
label = "Название пакета",
value = packageName,
onCopy = { copy(packageName, "Название пакета скопировано") }
)
CopyValueCard(
label = "SHA-1 подписи этого APK",
value = signingSha1.ifBlank { "Не удалось определить" },
onCopy = signingSha1.takeIf(String::isNotBlank)?.let { sha1 ->
{ copy(sha1, "SHA-1 скопирован") }
}
)
HelpStep(
number = 3,
title = "Скопируйте реквизиты",
text = "После создания откройте карточку приложения → «Приложение» → «Информация о приложении». Поле «ID приложения» вставьте как Client ID, а поле «Защищённый ключ» — как Client secret."
)
HelpStep(
number = 4,
title = "Сохраните и проверьте",
text = "Вернитесь в WDTT Plus, заполните оба поля, нажмите «Сохранить», затем «Проверить Client ID». Для полного доступа к ключам VK может попросить подтвердить профиль бизнеса."
)
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.55f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.25f))
) {
Column(
modifier = Modifier.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
Text("Важно", fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onErrorContainer)
Text(
"Не публикуйте Защищённый ключ, не отправляйте его в чат и не добавляйте в GitHub. Новое приложение VK ID может не иметь прав старой TURN-цепочки: статус проверки показывает распознавание legacy OAuth, а окончательный результат виден только при реальном подключении. При неудаче приложение продолжит через встроенный резерв.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
Button(
onClick = onDismiss,
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp)
) {
Text("Понятно")
}
}
}
}
}
}
@Composable
private fun HelpStep(number: Int, title: String, text: String) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.Top
) {
Surface(shape = CircleShape, color = MaterialTheme.colorScheme.secondaryContainer) {
Box(modifier = Modifier.size(30.dp), contentAlignment = Alignment.Center) {
Text(number.toString(), fontWeight = FontWeight.Bold)
}
}
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(title, fontWeight = FontWeight.Bold)
Text(
text,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 18.sp
)
}
}
}
@Composable
private fun CopyValueCard(label: String, value: String, onCopy: (() -> Unit)?) {
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f)
) {
Row(
modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 4.dp, top = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(value, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium)
}
IconButton(onClick = { onCopy?.invoke() }, enabled = onCopy != null) {
Icon(Icons.Default.ContentCopy, contentDescription = "Копировать")
}
}
}
}
internal fun parseVkClientIdCheckResults(raw: String): VkClientIdProbeCache = runCatching {
val json = JSONObject(raw)
if (json.optInt("_probe_version") != VK_CLIENT_ID_PROBE_VERSION) {
return@runCatching VkClientIdProbeCache(emptyMap(), 0L)
}
val results = buildMap {
val keys = json.keys()
while (keys.hasNext()) {
val key = keys.next()
if (key != "_probe_version" && key != VK_CLIENT_ID_PROBE_CHECKED_AT) {
runCatching { VkClientIdProbeStatus.valueOf(json.optString(key)) }
.getOrNull()
?.let { put(key, it) }
}
}
}
VkClientIdProbeCache(
results = results,
checkedAt = json.optLong(VK_CLIENT_ID_PROBE_CHECKED_AT, 0L).coerceAtLeast(0L)
)
}.getOrDefault(VkClientIdProbeCache(emptyMap(), 0L))
private fun encodeVkClientIdCheckResults(
results: Map<String, VkClientIdProbeStatus>,
checkedAt: Long
): String =
JSONObject().apply {
put("_probe_version", VK_CLIENT_ID_PROBE_VERSION)
put(VK_CLIENT_ID_PROBE_CHECKED_AT, checkedAt.coerceAtLeast(0L))
results.forEach { (id, result) -> put(id, result.name) }
}.toString()
internal val vkLegacyOAuthProbeEndpoints = listOf(
"https://oauth.vk.ru/authorize",
"https://oauth.vk.com/authorize"
)
private fun checkVkClientId(appId: String): VkClientIdProbeStatus {
val cleanAppId = appId.trim()
if (!isValidVkClientId(cleanAppId)) return VkClientIdProbeStatus.LegacyRejected
var legacyRejected = false
for (endpoint in vkLegacyOAuthProbeEndpoints) {
var connection: java.net.HttpURLConnection? = null
try {
val url = java.net.URL(
"$endpoint?client_id=$cleanAppId&display=mobile&response_type=token"
)
connection = url.openConnection() as java.net.HttpURLConnection
connection.requestMethod = "GET"
connection.connectTimeout = 5_000
connection.readTimeout = 5_000
val responseCode = connection.responseCode
if (isVkLegacyClientIdProbeSuccessful(responseCode, connection.contentType.orEmpty())) {
return VkClientIdProbeStatus.LegacyCompatible
}
if (isVkLegacyClientIdProbeRejected(responseCode)) {
legacyRejected = true
}
} catch (_: Exception) {
// Try the compatibility domain below.
} finally {
connection?.disconnect()
}
}
return if (legacyRejected) {
VkClientIdProbeStatus.LegacyRejected
} else {
VkClientIdProbeStatus.CheckFailed
}
}
internal fun isVkLegacyClientIdProbeSuccessful(statusCode: Int, contentType: String): Boolean =
statusCode in 200..299 && contentType.startsWith("text/html", ignoreCase = true)
internal fun isVkLegacyClientIdProbeRejected(statusCode: Int): Boolean =
statusCode in 400..499 && statusCode != 408 && statusCode != 429
@Suppress("DEPRECATION")
private fun appSigningSha1(context: Context): String = runCatching {
val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNING_CERTIFICATES)
} else {
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES)
}
val signature = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val signingInfo = packageInfo.signingInfo ?: return@runCatching ""
if (signingInfo.hasMultipleSigners()) {
signingInfo.apkContentsSigners.firstOrNull()
} else {
signingInfo.signingCertificateHistory.firstOrNull()
}
} else {
packageInfo.signatures?.firstOrNull()
} ?: return@runCatching ""
MessageDigest.getInstance("SHA-1")
.digest(signature.toByteArray())
.joinToString(":") { byte -> "%02X".format(byte) }
}.getOrDefault("")
@@ -3,6 +3,7 @@ package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -90,6 +91,44 @@ class AppUpdateTest {
)
}
@Test
fun updateAssetRequiresOfficialUrlSizeAndDigest() {
val safe = AppReleaseAsset(
name = "WDTT-Plus-v12-universal-release.apk",
downloadUrl = (
"https://github.com/Ivan4537/WDTT-Plus/releases/download/" +
"v12/WDTT-Plus-v12-universal-release.apk"
),
sizeBytes = 42L,
digest = "sha256:${"a".repeat(64)}",
)
val release = AppReleaseInfo(
versionTag = "v12",
releaseUrl = "https://github.com/Ivan4537/WDTT-Plus/releases/tag/v12",
source = RemoteVersionSource.Release,
assets = listOf(safe),
)
assertEquals(safe, selectUpdateApkAsset(release))
assertNull(
selectUpdateApkAsset(
release.copy(assets = listOf(safe.copy(digest = ""))),
),
)
assertFalse(
isTrustedUpdateDownloadUrl(
"https://github.com/other/project/releases/download/v12/app.apk",
initialRequest = true,
),
)
assertTrue(
isTrustedUpdateDownloadUrl(
"https://release-assets.githubusercontent.com/opaque",
initialRequest = false,
),
)
}
private fun releaseWithHashes(vararg hashes: String): AppReleaseInfo {
return AppReleaseInfo(
versionTag = "v7",
@@ -0,0 +1,20 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Test
class BoundedInputTest {
@Test
fun `bounded reader stops before accepting an oversized response`() {
assertEquals(
"данные",
"данные".byteInputStream().readUtf8TextLimited(32),
)
runCatching {
"x".repeat(33).byteInputStream().readUtf8TextLimited(32)
}.onSuccess {
throw AssertionError("Oversized response must be rejected")
}
}
}
@@ -0,0 +1,132 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class ClientNetworkDiagnosticsTest {
@Test
fun vkDiagnosticsTreatModernVkCallsHostsAsPrimaryAndLegacyHostsAsReserve() {
assertTrue("api.vk.me" in primaryVkDiagnosticHosts)
assertTrue("calls.okcdn.ru" in primaryVkDiagnosticHosts)
assertTrue("vk.ru" in reserveVkDiagnosticHosts)
assertTrue("login.vk.ru" in reserveVkDiagnosticHosts)
assertTrue("api.vk.ru" in reserveVkDiagnosticHosts)
assertTrue("id.vk.ru" in reserveVkDiagnosticHosts)
assertTrue("static.vk.ru" in reserveVkDiagnosticHosts)
assertTrue("vk.com" in reserveVkDiagnosticHosts)
assertTrue(primaryVkDiagnosticHosts.intersect(reserveVkDiagnosticHosts).isEmpty())
assertEquals("api.vk.me", clientDnsProbeHost)
}
@Test
fun clientDnsPath_usesSystemFallbackWithoutReportingFailure() {
val result = assessClientDnsPath(emptySet(), systemPrimaryApiWorks = true)
assertEquals("прямой DNS недоступен, используется системный DNS", result.status)
assertEquals(DeviceCheckSeverity.Info, result.severity)
assertEquals(null, result.action)
}
@Test
fun clientDnsPath_acceptsSecondaryUdpRoute() {
val result = assessClientDnsPath(setOf("77.88.8.1 UDP"), systemPrimaryApiWorks = false)
assertEquals("резервный UDP DNS доступен", result.status)
assertEquals(DeviceCheckSeverity.Info, result.severity)
assertEquals(null, result.action)
}
@Test
fun clientDnsPath_prefersSecondaryUdpOverPrimaryTcp() {
val result = assessClientDnsPath(
setOf("77.88.8.8 TCP", "77.88.8.1 UDP"),
systemPrimaryApiWorks = true
)
assertEquals("резервный UDP DNS доступен", result.status)
assertEquals(DeviceCheckSeverity.Info, result.severity)
}
@Test
fun clientDnsPath_acceptsTcpFallback() {
val result = assessClientDnsPath(setOf("77.88.8.8 TCP"), systemPrimaryApiWorks = false)
assertEquals("UDP DNS недоступен, TCP отвечает", result.status)
assertEquals(DeviceCheckSeverity.Info, result.severity)
assertEquals(null, result.action)
}
@Test
fun clientDnsPath_keepsPrimaryDirectRouteAheadOfSystemDns() {
val result = assessClientDnsPath(setOf("77.88.8.8 UDP"), systemPrimaryApiWorks = true)
assertEquals("основной UDP DNS доступен", result.status)
assertEquals(DeviceCheckSeverity.Ok, result.severity)
assertEquals(null, result.action)
}
@Test
fun clientDnsPath_reportsFailureOnlyWhenEveryRouteIsUnavailable() {
val result = assessClientDnsPath(emptySet(), systemPrimaryApiWorks = false)
assertEquals("DNS до VK недоступен", result.status)
assertEquals(DeviceCheckSeverity.Error, result.severity)
assertEquals(DeviceCheckAction.NetworkSettings, result.action)
}
@Test
fun dnsQuery_containsExpectedHeaderNameAndARecordType() {
val query = buildDnsQuery(clientDnsProbeHost, 0x1234)
assertEquals(0x12, query[0].toInt() and 0xff)
assertEquals(0x34, query[1].toInt() and 0xff)
assertEquals(1, unsignedShort(query, 4))
assertTrue(query.copyOfRange(12, query.size).containsSubsequence(byteArrayOf(3, 'a'.code.toByte(), 'p'.code.toByte(), 'i'.code.toByte())))
assertEquals(1, unsignedShort(query, query.size - 4))
assertEquals(1, unsignedShort(query, query.size - 2))
}
@Test
fun dnsResponse_parsesAnswerCountAndFlags() {
val response = byteArrayOf(
0x12, 0x34,
0x83.toByte(), 0x80.toByte(),
0x00, 0x01,
0x00, 0x02,
0x00, 0x00,
0x00, 0x00
)
val status = parseDnsResponse(response, 0x1234)
assertEquals(0, status.responseCode)
assertEquals(2, status.answerCount)
assertTrue(status.truncated)
}
@Test(expected = IllegalArgumentException::class)
fun dnsResponse_rejectsDifferentTransaction() {
parseDnsResponse(
byteArrayOf(
0x55, 0x66,
0x81.toByte(), 0x80.toByte(),
0x00, 0x01,
0x00, 0x01,
0x00, 0x00,
0x00, 0x00
),
0x1234
)
}
private fun unsignedShort(bytes: ByteArray, offset: Int): Int =
((bytes[offset].toInt() and 0xff) shl 8) or (bytes[offset + 1].toInt() and 0xff)
private fun ByteArray.containsSubsequence(expected: ByteArray): Boolean {
if (expected.isEmpty() || expected.size > size) return false
return indices.any { start ->
start + expected.size <= size && expected.indices.all { index -> this[start + index] == expected[index] }
}
}
}
@@ -27,6 +27,20 @@ class ClientTransferCodecTest {
assertFalse(encoded.contains("host"))
}
@Test
fun clientTransfer_roundTripsWithoutVkHashes() {
val source = ClientTransferPayload(
password = "ABCDEFGHJKLMNPQR",
label = "Без хеша",
vkHash = "",
expiresAt = 0,
deactivated = false,
createdAt = 12345
)
assertEquals(source, ClientTransferCodec.decode(ClientTransferCodec.encode(source)))
}
@Test(expected = IllegalArgumentException::class)
fun clientTransfer_rejectsUnsafePassword() {
ClientTransferCodec.decode(
@@ -0,0 +1,52 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class DeviceIdentityTest {
@Test
fun existingIdentityIsPreservedForActiveInstallations() {
val existing = "android-11111111-2222-3333-4444-555555555555"
val resolved = DeviceIdentity.resolve(
existing = existing,
platformId = "abcdef0123456789",
generatedId = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
)
assertEquals(existing, resolved)
}
@Test
fun freshInstallationUsesStablePlatformIdentity() {
val resolved = DeviceIdentity.resolve(
existing = null,
platformId = "abcdef0123456789",
generatedId = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
)
assertEquals("abcdef0123456789", resolved)
}
@Test
fun missingPlatformIdentityUsesValidGeneratedFallback() {
val fallback = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
val resolved = DeviceIdentity.resolve(
existing = "broken",
platformId = null,
generatedId = fallback,
)
assertEquals(fallback, resolved)
}
@Test
fun knownSharedLegacyAndroidIdentityIsRejected() {
assertFalse(DeviceIdentity.valid("9774d56d682e549c"))
assertFalse(DeviceIdentity.valid("unknown"))
assertTrue(DeviceIdentity.valid("abcdef0123456789"))
}
}
@@ -3,9 +3,19 @@ package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class LogSeverityTest {
@Test
fun wrapHandshakeRetryMessage_doesNotBlameThePassword() {
assertEquals(
"[WRAP] Отдельные каналы не ответили, выполняется повтор",
WRAP_HANDSHAKE_RETRY_MESSAGE
)
assertFalse(WRAP_HANDSHAKE_RETRY_MESSAGE.contains("парол", ignoreCase = true))
}
@Test
fun repeatedTurnWorkerFailures_useOneRecoverableWarningKey() {
val first = classifyRecoverableWorkerRetry(
@@ -40,4 +50,11 @@ class LogSeverityTest {
assertFalse(warning.isError)
}
@Test
fun serverExpiredDenialIsRecognizedBeforeLocalizedProtocolMessage() {
assertTrue(isExpiredAccessAuthFailure("FATAL_AUTH: DENIED:expired"))
assertTrue(isExpiredAccessAuthFailure("FATAL_AUTH: срок действия пароля истёк"))
assertFalse(isExpiredAccessAuthFailure("FATAL_AUTH: неверный пароль подключения"))
}
}
@@ -0,0 +1,175 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class RemoteActionCatalogTest {
@Test
fun parse_acceptsOnlyKnownPlacementsAndExactTargets() {
val catalog = RemoteActionCatalogGateway.parse(
"""
{
"version": 1,
"actions": {
"tunnel": {
"title": "Дополнительное действие",
"message": "Продолжить во внешнем сервисе",
"label": "Открыть",
"confirmation_title": "Подтверждение",
"confirmation_message": "Первый абзац.\n\nВторой абзац.",
"confirmation_label": "Продолжить",
"progress_label": "Открываю…",
"preparing_message": "Подготавливаю...",
"stopping_message": "Останавливаю...",
"opening_message": "Открываю...",
"success_message": "Открыто.",
"cancelled_message": "Отменено.",
"failure_message": "Не удалось.",
"compact_message": "Короткий текст.",
"compact_label": "Короткая кнопка",
"compact_link_text": "Короткий",
"compact_button_visible": false,
"cancel_label": "Остановить",
"form": {
"token": "opaque.form.token_1234567890",
"submit_url": "https://example.org/actions/execute",
"title": "Введите значение",
"message": "Выберите готовое значение или укажите своё.",
"choices": [
{"label": "Первое", "value": "opaque-choice-1"},
{"label": "Второе", "value": "opaque-choice-2"}
],
"input_label": "Значение",
"input_suffix": "",
"initial_value": "7",
"minimum": 2,
"maximum": 19,
"max_characters": 2,
"supporting_text": "Допустимый диапазон",
"invalid_text": "Проверьте значение",
"submit_label": "Продолжить — {value}",
"busy_label": "Подготавливаем…",
"failure_message": "Не удалось продолжить.",
"fallback_label": "Открыть страницу"
},
"url": "https://example.org/start?opaque=1",
"fallback": "https://example.org/fallback",
"handler": "org.example.client",
"alternate_handlers": [
"org.example.client.web",
"org.example.client.x"
]
},
"unknown": {
"title": "Неизвестное место",
"message": "Не должно попасть в каталог",
"label": "Открыть",
"url": "https://example.org/ignored"
}
}
}
""".trimIndent()
)
val action = catalog.at("tunnel")!!
assertEquals("Дополнительное действие", action.title)
assertEquals("https://example.org/start?opaque=1", action.target.primaryUrl)
assertEquals("https://example.org/fallback", action.target.fallbackUrl)
assertEquals("org.example.client", action.target.preferredHandler)
assertEquals(
listOf("org.example.client.web", "org.example.client.x"),
action.target.alternateHandlers,
)
assertEquals(
listOf(
"org.example.client",
"org.example.client.web",
"org.example.client.x",
),
action.target.handlerPackages(),
)
assertEquals("Подтверждение", action.confirmationTitle)
assertEquals("Первый абзац.\n\nВторой абзац.", action.confirmationMessage)
assertEquals("Продолжить", action.confirmationLabel)
assertEquals("Открываю…", action.progressLabel)
assertEquals("Подготавливаю...", action.preparingMessage)
assertEquals("Останавливаю...", action.stoppingMessage)
assertEquals("Открываю...", action.openingMessage)
assertEquals("Открыто.", action.successMessage)
assertEquals("Отменено.", action.cancelledMessage)
assertEquals("Не удалось.", action.failureMessage)
assertEquals("Короткий текст.", action.compactMessage)
assertEquals("Короткая кнопка", action.compactLabel)
assertEquals("Короткий", action.compactLinkText)
assertEquals(false, action.compactButtonVisible)
assertEquals("Остановить", action.cancelLabel)
assertEquals("Введите значение", action.form?.title)
assertEquals("opaque-choice-2", action.form?.choices?.get(1)?.value)
assertEquals(2L, action.form?.minimum)
assertEquals(19L, action.form?.maximum)
assertNull(catalog.at("unknown"))
}
@Test
fun parse_rejectsUnsafeOrMalformedActions() {
val catalog = RemoteActionCatalogGateway.parse(
"""
{
"version": 1,
"actions": {
"tunnel": {
"title": "Опасная ссылка",
"message": "Неподдерживаемая схема",
"label": "Открыть",
"url": "custom://private-contract"
},
"profile": {
"title": "Неверный обработчик",
"message": "Имя пакета не прошло проверку",
"label": "Открыть",
"url": "https://example.org/start",
"handler": "not a package"
},
"about": {
"title": "Неверные резервные обработчики",
"message": "Имя пакета не прошло проверку",
"label": "Открыть",
"url": "https://example.org/start",
"alternate_handlers": ["also not a package"]
}
}
}
""".trimIndent()
)
assertTrue(catalog.actions.isEmpty())
}
@Test
fun parse_rejectsUnknownProtocolVersion() {
val catalog = RemoteActionCatalogGateway.parse(
"""{"version":2,"actions":{}}"""
)
assertTrue(catalog.actions.isEmpty())
}
@Test
fun parseExecutionTarget_acceptsOnlyExactHttpsTargets() {
val target = RemoteActionCatalogGateway.parseExecutionTarget(
"""
{
"version": 1,
"url": "https://actions.example.org/opaque",
"fallback": "https://example.org/fallback",
"handler": ""
}
""".trimIndent()
)
assertEquals("https://actions.example.org/opaque", target.primaryUrl)
assertEquals("https://example.org/fallback", target.fallbackUrl)
}
}
@@ -8,6 +8,24 @@ import org.junit.Test
import org.json.JSONObject
class TransferCodecTest {
@Test
fun connectionLinkCarriesOptionalProfileWorkerPolicy() {
val link = WdttTransferCodec.buildConnectionLink(
WdttLinkParts(
host = "vpn.example.org",
dtlsPort = 56000,
wgPort = 56001,
localPort = 9000,
password = "secret",
hashes = "1234567890abcdef",
maxWorkers = 9
)
)
assertEquals(9, WdttDeepLink.parse(link)?.maxWorkers)
assertEquals(0, WdttDeepLink.parse(link.replace("&max_workers=9", ""))?.maxWorkers)
}
@Test
fun modernConnectionLink_roundTripsSpecialCharacters() {
val original = WdttLinkParts(
@@ -112,6 +130,14 @@ class TransferCodecTest {
assertEquals("", validation.parts?.profileName)
}
@Test
fun invalidConnectionLink_helpShowsModernAndLegacyFormats() {
val message = WdttDeepLink.validate("not-a-link").userMessage()
assertTrue(message.contains("Новый: wdtt://connect?v=1"))
assertTrue(message.contains("Старый: wdtt://адрес:"))
}
@Test
fun onlyRenamedProfileIsPreparedForTransfer() {
assertEquals("", vpnProfileTransferName(0, listOf("", "", "")))
@@ -166,6 +192,44 @@ class TransferCodecTest {
assertEquals("Мой сервер", WdttDeepLink.parse(link.orEmpty())?.profileName)
}
@Test
fun serverClientLink_withoutVkHashesCanBeSharedAndImportedAsPartialAccess() {
val link = buildServerConnectionLink(
password = "ABCDEFGHJKLMNPQR",
hashes = "",
ports = "56000,56001,9000",
fallbackHost = "vpn.example.org",
publicHost = "",
profileName = "Доступ без хеша"
)
assertNotNull(link)
assertTrue(link.orEmpty().contains("hashes="))
assertFalse(WdttDeepLink.validate(link.orEmpty()).canStartVpn)
val partial = WdttDeepLink.parse(link.orEmpty(), allowMissingHashes = true)
assertNotNull(partial)
assertEquals("", partial?.hashes)
assertEquals("Доступ без хеша", partial?.profileName)
assertFalse(partial?.hasNonStandardPorts() ?: true)
}
@Test
fun importedLinkEnablesCustomPortsOnlyWhenAtLeastOnePortDiffers() {
val standard = WdttLinkParts(
host = "vpn.example.org",
dtlsPort = 56000,
wgPort = 56001,
localPort = 9000,
password = "ABCDEFGHJKLMNPQR",
hashes = "hash"
)
assertFalse(standard.hasNonStandardPorts())
assertTrue(standard.copy(dtlsPort = 57000).hasNonStandardPorts())
assertTrue(standard.copy(wgPort = 57001).hasNonStandardPorts())
assertTrue(standard.copy(localPort = 9100).hasNonStandardPorts())
}
@Test
fun linkCanBeExtractedFromSharedText() {
val value = "Подключение: wdtt://vpn.example.org:56000:56001:9000:secret:1234567890abcdef\nНе передавайте посторонним"
@@ -185,6 +249,38 @@ class TransferCodecTest {
assertFalse(WdttDeepLink.validate(link).canStartVpn)
}
@Test
fun connectionLinkWithoutHashes_canBeStoredButCannotStartVpn() {
val link = WdttTransferCodec.buildConnectionLink(
WdttLinkParts("vpn.example.org", 56000, 56001, 9000, "secret", "")
)
assertFalse(WdttDeepLink.validate(link).canStartVpn)
assertNotNull(WdttDeepLink.parse(link, allowMissingHashes = true))
assertTrue(
WdttDeepLink.validate(link, allowMissingHashes = true)
.userMessage()
.contains("Добавьте свой VK-хеш")
)
}
@Test
fun ordinaryLongWordsAreNeverParsedAsVkHashes() {
val link = WdttTransferCodec.buildConnectionLink(
WdttLinkParts(
"vpn.example.org",
56000,
56001,
9000,
"secret",
"пользовательский,переподключаются",
)
)
assertFalse(WdttDeepLink.validate(link).canStartVpn)
assertEquals(null, WdttDeepLink.parse(link, allowMissingHashes = true))
}
@Test
fun malformedModernLink_isNotParsed() {
val validation = WdttDeepLink.validate("wdtt://connect?v=1&host=vpn.example.org")
@@ -0,0 +1,23 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Test
class TrustedWifiLogTest {
@Test
fun `repeated trusted wifi event updates one counter`() {
TunnelManager.isLoggingEnabled = true
TunnelManager.clearLogs()
try {
TunnelManager.noteTrustedWifiEvent("resume_wait_network", "Ждём рабочую сеть.")
TunnelManager.noteTrustedWifiEvent("resume_wait_network", "Ждём рабочую сеть.")
val entries = TunnelManager.logs.value.filter { it.key == "trusted_wifi_resume_wait_network" }
assertEquals(1, entries.size)
assertEquals(2, entries.single().count)
assertEquals(LogSeverity.Info, entries.single().severity)
} finally {
TunnelManager.clearLogs()
}
}
}
@@ -123,4 +123,68 @@ class TrustedWifiTest {
)
)
}
@Test
fun `trusted wifi resume retries keep cpu awake only during fast recovery window`() {
assertEquals(
TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true),
trustedWifiResumeRetryPlan(0)
)
assertEquals(
TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true),
trustedWifiResumeRetryPlan(11)
)
assertEquals(
TrustedWifiResumeRetryPlan(delayMs = 30_000L, keepCpuAwake = false),
trustedWifiResumeRetryPlan(12)
)
}
@Test
fun `lost trusted wifi is not reused as validated resume network`() {
val networks = TrustedWifiValidatedNetworkTracker<String>()
networks.update(network = "home", validated = true, wifi = true)
assertTrue(networks.hasUsableNetwork())
networks.forgetWifi()
assertFalse(networks.hasUsableNetwork())
networks.update(network = "cellular", validated = true, wifi = false)
assertTrue(networks.hasUsableNetwork())
networks.lost("cellular")
assertFalse(networks.hasUsableNetwork())
}
@Test
fun `trusted wifi loss preserves an already validated cellular network`() {
val networks = TrustedWifiValidatedNetworkTracker<String>()
networks.update(network = "home", validated = true, wifi = true)
networks.update(network = "cellular", validated = true, wifi = false)
networks.forgetWifi()
assertTrue(networks.hasUsableNetwork())
}
@Test
fun `internet capability without validation is not enough to resume`() {
val networks = TrustedWifiValidatedNetworkTracker<String>()
networks.update(network = "cellular", validated = false, wifi = false)
assertFalse(networks.hasUsableNetwork())
networks.update(network = "cellular", validated = true, wifi = false)
assertTrue(networks.hasUsableNetwork())
}
@Test
fun `losing trusted wifi does not discard a newly validated untrusted wifi`() {
val networks = TrustedWifiValidatedNetworkTracker<String>()
networks.update(network = "home", validated = true, wifi = true)
networks.update(network = "office", validated = true, wifi = true)
networks.lost("home")
assertTrue(networks.hasUsableNetwork())
}
}
@@ -0,0 +1,168 @@
package com.wdtt.plus
import com.wdtt.plus.ui.hasTunnelConnectionSource
import com.wdtt.plus.ui.isSelectedCompactConnectionReady
import com.wdtt.plus.ui.resolveConnectionInputMethod
import com.wdtt.plus.ui.usesCompactTunnelInterface
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class TunnelProfilePresentationTest {
@Test
fun `user role uses compact tunnel interface`() {
assertTrue(usesCompactTunnelInterface("user"))
assertFalse(usesCompactTunnelInterface("admin"))
}
@Test
fun `empty profiles use role specific default method`() {
assertEquals("link", resolveConnectionInputMethod("", false, false, true))
assertEquals("manual", resolveConnectionInputMethod("", false, false, false))
assertEquals("manual", resolveConnectionInputMethod("", false, true, true))
assertEquals("link", resolveConnectionInputMethod("link", false, true, false))
}
@Test
fun `legacy profiles without saved method keep their configured source`() {
assertEquals("link", resolveConnectionInputMethod("", true, false, false))
assertEquals("link", resolveConnectionInputMethod("", true, true, true))
assertEquals("manual", resolveConnectionInputMethod("", false, true, false))
assertTrue(
isSelectedCompactConnectionReady(
selectedMethod = "link",
savedMethod = "",
storedLinkMode = true,
linkPresent = true,
linkValid = true,
manualValid = false,
)
)
assertTrue(
isSelectedCompactConnectionReady(
selectedMethod = "manual",
savedMethod = "",
storedLinkMode = false,
linkPresent = false,
linkValid = false,
manualValid = true,
)
)
}
@Test
fun `manual and link profiles detect their own connection source`() {
assertTrue(hasTunnelConnectionSource(false, false, "vpn.example", "secret"))
assertFalse(hasTunnelConnectionSource(false, false, "vpn.example", ""))
assertTrue(hasTunnelConnectionSource(true, true, "", ""))
assertTrue(hasTunnelConnectionSource(true, false, "vpn.example", "secret"))
}
@Test
fun `selected connection method must match configured method`() {
assertTrue(
isSelectedCompactConnectionReady(
selectedMethod = "manual",
savedMethod = "manual",
storedLinkMode = false,
linkPresent = false,
linkValid = false,
manualValid = true,
)
)
assertFalse(
isSelectedCompactConnectionReady(
selectedMethod = "link",
savedMethod = "manual",
storedLinkMode = false,
linkPresent = false,
linkValid = false,
manualValid = true,
)
)
assertTrue(
isSelectedCompactConnectionReady(
selectedMethod = "link",
savedMethod = "link",
storedLinkMode = false,
linkPresent = false,
linkValid = false,
manualValid = true,
)
)
assertFalse(
isSelectedCompactConnectionReady(
selectedMethod = "manual",
savedMethod = "link",
storedLinkMode = false,
linkPresent = false,
linkValid = false,
manualValid = true,
)
)
}
@Test
fun `incomplete selected method is not ready`() {
assertFalse(
isSelectedCompactConnectionReady(
selectedMethod = "manual",
savedMethod = "manual",
storedLinkMode = false,
linkPresent = false,
linkValid = false,
manualValid = false,
)
)
assertFalse(
isSelectedCompactConnectionReady(
selectedMethod = "link",
savedMethod = "",
storedLinkMode = true,
linkPresent = true,
linkValid = false,
manualValid = true,
)
)
}
@Test
fun `running tunnel keeps launch profile after selection changes`() {
assertEquals(
0,
displayedTunnelProfile(
selectedProfile = 2,
activeTunnelProfile = 0,
running = true,
trustedWifiWaiting = false,
)
)
}
@Test
fun `trusted wifi waiting keeps tunnel profile`() {
assertEquals(
1,
displayedTunnelProfile(
selectedProfile = 2,
activeTunnelProfile = 1,
running = false,
trustedWifiWaiting = true,
)
)
}
@Test
fun `disconnected interface follows selected profile`() {
assertEquals(
2,
displayedTunnelProfile(
selectedProfile = 2,
activeTunnelProfile = 0,
running = false,
trustedWifiWaiting = false,
)
)
}
}
@@ -0,0 +1,90 @@
package com.wdtt.plus
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class TunnelProfileRuntimeUpdateTest {
@Test
fun activeRunningProfileRequestsRuntimeUpdate() {
assertTrue(
shouldRequestTunnelProfileRuntimeUpdate(
updatedProfile = 1,
activeTunnelProfile = 1,
tunnelRunning = true,
trustedWifiWaiting = false,
)
)
}
@Test
fun inactiveProfileDoesNotTouchRunningTunnel() {
assertFalse(
shouldRequestTunnelProfileRuntimeUpdate(
updatedProfile = 2,
activeTunnelProfile = 1,
tunnelRunning = true,
trustedWifiWaiting = false,
)
)
}
@Test
fun stoppedProfileDoesNotStartVpn() {
assertFalse(
shouldRequestTunnelProfileRuntimeUpdate(
updatedProfile = 1,
activeTunnelProfile = 1,
tunnelRunning = false,
trustedWifiWaiting = false,
)
)
}
@Test
fun trustedWifiWaitingProfileKeepsUpdatedConfigurationForResume() {
assertTrue(
shouldRequestTunnelProfileRuntimeUpdate(
updatedProfile = 1,
activeTunnelProfile = 1,
tunnelRunning = false,
trustedWifiWaiting = true,
)
)
}
@Test
fun changedConnectionParametersRequireRuntimeReplacement() {
val current = params(peer = "old.example:56000")
val updated = current.copy(peer = "new.example:56000")
assertTrue(tunnelProfileRuntimeConfigurationChanged(current, updated))
}
@Test
fun unchangedConnectionParametersDoNotRestartTransport() {
val current = params(peer = "same.example:56000")
assertFalse(tunnelProfileRuntimeConfigurationChanged(current, current.copy()))
}
@Test
fun anotherProfileCannotReplaceActiveRuntimeConfiguration() {
val current = params(peer = "old.example:56000", profileIndex = 0)
val updated = current.copy(peer = "new.example:56000", profileIndex = 1)
assertFalse(tunnelProfileRuntimeConfigurationChanged(current, updated))
}
private fun params(
peer: String,
profileIndex: Int = 0,
) = TunnelParams(
peer = peer,
vkHashes = "hash",
workersPerHash = 9,
port = 9000,
connectionPassword = "password",
profileIndex = profileIndex,
)
}
@@ -0,0 +1,34 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Test
class TunnelRecoveryPolicyTest {
@Test
fun firstRecoveryIsTransportOnly() {
assertEquals(
NetworkRecoveryAction.SoftRestart,
stableNetworkRecoveryAction(completedAttempts = 0),
)
}
@Test
fun failedTransportRecoveryRecreatesVpnOnce() {
assertEquals(
NetworkRecoveryAction.RecreateVpn,
stableNetworkRecoveryAction(completedAttempts = 1),
)
}
@Test
fun failedVpnRecreationStopsFailOpen() {
assertEquals(
NetworkRecoveryAction.StopVpn,
stableNetworkRecoveryAction(completedAttempts = 2),
)
assertEquals(
NetworkRecoveryAction.StopVpn,
stableNetworkRecoveryAction(completedAttempts = 3),
)
}
}
@@ -0,0 +1,47 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Test
class TunnelStartConfigTest {
@Test
fun `tile and widgets stop both active and trusted wifi waiting tunnel`() {
assertEquals(
TunnelToggleAction.STOP,
tunnelToggleAction(
running = true,
trustedWifiWaiting = false,
vpnPermissionRequired = false,
)
)
assertEquals(
TunnelToggleAction.STOP,
tunnelToggleAction(
running = false,
trustedWifiWaiting = true,
vpnPermissionRequired = false,
)
)
}
@Test
fun `tile and widgets request permission before start`() {
assertEquals(
TunnelToggleAction.REQUEST_VPN_PERMISSION,
tunnelToggleAction(
running = false,
trustedWifiWaiting = false,
vpnPermissionRequired = true,
)
)
assertEquals(
TunnelToggleAction.START,
tunnelToggleAction(
running = false,
trustedWifiWaiting = false,
vpnPermissionRequired = false,
)
)
}
}
@@ -0,0 +1,27 @@
package com.wdtt.plus
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class TunnelStartRequestGateTest {
@Test
fun `stop invalidates a delayed start`() {
val gate = TunnelStartRequestGate()
val request = gate.next()
gate.invalidate()
assertFalse(gate.isCurrent(request))
}
@Test
fun `only the latest profile request may finish`() {
val gate = TunnelStartRequestGate()
val first = gate.next()
val second = gate.next()
assertFalse(gate.isCurrent(first))
assertTrue(gate.isCurrent(second))
}
}
@@ -0,0 +1,15 @@
package com.wdtt.plus
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class TunnelStopCoordinatorTest {
@Test
fun `only completed stop outcomes allow a destructive follow-up action`() {
assertTrue(TunnelStopResult.ALREADY_STOPPED.succeeded)
assertTrue(TunnelStopResult.STOPPED.succeeded)
assertFalse(TunnelStopResult.TIMED_OUT.succeeded)
assertFalse(TunnelStopResult.FAILED.succeeded)
}
}
@@ -0,0 +1,20 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Test
class TunnelWorkerPolicyTest {
@Test
fun profilePolicyCapsOnlyTheProfileThatCarriesIt() {
assertEquals(9, normalizeTunnelWorkerCount(1, profileMaxWorkers = 9))
assertEquals(9, normalizeTunnelWorkerCount(27, profileMaxWorkers = 9))
assertEquals(18, normalizeTunnelWorkerCount(27, profileMaxWorkers = 18))
}
@Test
fun profileWithoutPolicyRetainsFullPowerRange() {
assertEquals(18, normalizeTunnelWorkerCount(16))
assertEquals(108, normalizeTunnelWorkerCount(108))
assertEquals(108, normalizeTunnelWorkerCount(500))
}
}
@@ -0,0 +1,42 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class VkClientCredentialsTest {
@Test
fun `client id normalization keeps digits only`() {
assertEquals("123456", normalizeVkClientId(" 12-ab34 56 "))
assertTrue(isValidVkClientId("123456"))
assertFalse(isValidVkClientId("123-456"))
}
@Test
fun `disabled custom mode never blocks built in credentials`() {
assertNull(customVkCredentialsError(CustomVkClientCredentials(enabled = false)))
}
@Test
fun `enabled custom mode requires both values`() {
assertEquals(
"Укажите числовой Client ID приложения VK.",
customVkCredentialsError(CustomVkClientCredentials(enabled = true))
)
assertEquals(
"Укажите защищённый ключ (Client secret) приложения VK.",
customVkCredentialsError(CustomVkClientCredentials(enabled = true, clientId = "123456"))
)
assertNull(
customVkCredentialsError(
CustomVkClientCredentials(
enabled = true,
clientId = "123456",
clientSecret = "test-only-secret"
)
)
)
}
}
@@ -0,0 +1,55 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class VkJoinLinkTest {
@Test
fun extractsHashFromCurrentVkRuLink() {
assertEquals(
"current_hash_1234567890",
VkJoinLink.extractHash(
"https://vk.ru/call/join/current_hash_1234567890?from=share#fragment"
)
)
}
@Test
fun keepsVkComLinksAsCompatibilityInput() {
assertEquals(
"legacy_hash_1234567890",
VkJoinLink.extractHash(
"https://vk.com/call/join/legacy_hash_1234567890?from=share"
)
)
}
@Test
fun keepsRawHashInputSupported() {
assertEquals(
"raw_hash_1234567890",
VkJoinLink.extractHash("raw_hash_1234567890")
)
}
@Test
fun acceptsOnlyOpaqueAsciiHashValues() {
assertTrue(VkJoinLink.isValidHash("3XariaxnHDP9eTiWVFukTMO6ZjCw7c0QQS_J3gYiiaM"))
assertTrue(VkJoinLink.isValidHash("short"))
assertFalse(VkJoinLink.isValidHash("пользовательский"))
assertFalse(VkJoinLink.isValidHash("переподключаются"))
assertEquals("", VkJoinLink.extractValidHash("https://vk.ru/call/join/пользовательский"))
}
@Test
fun validatesCharactersWithoutGuessingVkHashLength() {
assertTrue(VkJoinLink.isValidInput("a"))
assertTrue(VkJoinLink.isValidInput("https://vk.ru/call/join/a?from=share"))
assertFalse(VkJoinLink.isValidInput("хеш"))
assertFalse(VkJoinLink.isValidInput("bad/path"))
assertFalse(VkJoinLink.isValidInput("https://vk.ru/not-a-call/a"))
assertEquals("a,b_C-2", VkJoinLink.normalizeHashes("a, b_C-2"))
}
}
@@ -0,0 +1,32 @@
package com.wdtt.plus
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class WdttDocumentTest {
@Test
fun `profile file name always has one wdtt extension`() {
assertEquals("WDTT-Plus-profile.wdtt", WdttDocument.fileName("WDTT-Plus-profile"))
assertEquals("WDTT-Plus-profile.wdtt", WdttDocument.fileName("WDTT-Plus-profile.wdtt"))
}
@Test
fun `picker accepts current mime and compatible legacy document types`() {
assertArrayEquals(
arrayOf(
"application/vnd.wdtt.plus",
"application/vnd.wdtt.plus.transfer",
"application/vnd.wdtt.plus.client",
"application/json",
"application/octet-stream",
"text/plain",
),
WdttDocument.acceptedMimeTypes(),
)
assertTrue(WdttDocument.isAcceptedMimeType("application/vnd.wdtt.plus"))
assertTrue(WdttDocument.isAcceptedMimeType("application/octet-stream"))
assertTrue(WdttDocument.isAcceptedMimeType("text/plain; charset=utf-8"))
}
}
@@ -0,0 +1,72 @@
package com.wdtt.plus
import com.wireguard.config.Config
import com.wireguard.crypto.Key
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayInputStream
class WireGuardRuntimeConfigTest {
private val privateKey = Key.fromBytes(ByteArray(32) { index -> (index + 1).toByte() })
.toBase64()
private val publicKey = Key.fromBytes(ByteArray(32) { index -> (index + 33).toByte() })
.toBase64()
@Test
fun unchangedConfigurationKeepsRunningVpnInterface() {
val current = config(endpointPort = 9000)
val updated = config(endpointPort = 9000)
assertTrue(
shouldReuseRunningWireGuard(
tunnelUp = true,
currentConfigFingerprint = wireGuardConfigFingerprint(current),
updatedConfig = updated,
)
)
}
@Test
fun changedConfigurationReplacesVpnInterface() {
assertFalse(
shouldReuseRunningWireGuard(
tunnelUp = true,
currentConfigFingerprint = wireGuardConfigFingerprint(
config(endpointPort = 9000)
),
updatedConfig = config(endpointPort = 9001),
)
)
}
@Test
fun stoppedVpnInterfaceIsNeverReused() {
val config = config(endpointPort = 9000)
assertFalse(
shouldReuseRunningWireGuard(
tunnelUp = false,
currentConfigFingerprint = wireGuardConfigFingerprint(config),
updatedConfig = config,
)
)
}
private fun config(endpointPort: Int): Config {
val text = """
[Interface]
PrivateKey = $privateKey
Address = 10.0.0.2/32
DNS = 1.1.1.1
MTU = 1280
[Peer]
PublicKey = $publicKey
AllowedIPs = 0.0.0.0/0
Endpoint = 127.0.0.1:$endpointPort
PersistentKeepalive = 25
""".trimIndent()
return Config.parse(ByteArrayInputStream(text.toByteArray()))
}
}
@@ -0,0 +1,96 @@
package com.wdtt.plus.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ExceptionsTabBehaviorTest {
@Test
fun `header stays collapsed while app list can still scroll to its first item`() {
assertEquals(
-240f,
collapsingHeaderOffsetAfterScroll(
currentOffsetPx = -240f,
headerHeightPx = 240f,
deltaPx = 80f,
allowExpand = false,
),
)
}
@Test
fun `header expands after app list reaches its first item`() {
assertEquals(
-160f,
collapsingHeaderOffsetAfterScroll(
currentOffsetPx = -240f,
headerHeightPx = 240f,
deltaPx = 80f,
allowExpand = true,
),
)
}
@Test
fun `header gesture clamps expansion and collapse to measured height`() {
assertEquals(
0f,
collapsingHeaderOffsetAfterScroll(-40f, 240f, 100f, allowExpand = true),
)
assertEquals(
-240f,
collapsingHeaderOffsetAfterScroll(-200f, 240f, -100f, allowExpand = true),
)
}
@Test
fun `quick exclusions recognize current whitelist app packages`() {
val packages = listOf(
"ru.oneme.app",
"ru.gosuslugi.goskey",
"com.octopod.russianpost.client.android",
"ru.nspk.mirpay",
"ru.nspk.sbpay",
"logo.com.mbanking",
"ru.rzd.pass",
"ru.tutu.tutu_emp",
"ru.vkusvill",
"com.icemobile.lenta.prod",
"ru.reksoft.okey",
"ru.myauchan.droid",
"www.metro.com",
"ru.tander.magnit",
"ru.pyaterochka.app.browser",
"ru.perekrestok.app",
"club.chizhik",
"com.logistic.sdek",
"ru.dodopizza.app",
"ru.burgerking",
"com.apegroup.mcdonaldsrussia",
"com.carshering",
"youdrive.today",
"ru.ivi.client",
"ru.more.play",
"ru.zen.android",
"gpm.tnt_premier",
"ru.mts.mtstv",
"ru.radioplayer",
)
packages.forEach { packageName ->
assertTrue(
"Expected $packageName to be a quick exclusion",
matchesQuickExclusionApp(name = "Неизвестное название", packageName = packageName),
)
}
}
@Test
fun `quick exclusions match store label aliases without selecting unrelated apps`() {
assertTrue(matchesQuickExclusionApp("МАКС: общение, звонки, сервисы", "store.variant"))
assertTrue(matchesQuickExclusionApp("Вкусно — и точка", "store.variant"))
assertTrue(matchesQuickExclusionApp("Сателлит Online", "store.variant"))
assertFalse(matchesQuickExclusionApp("Калькулятор", "com.example.calculator"))
}
}
@@ -0,0 +1,35 @@
package com.wdtt.plus.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class OutboundFormsStoreTest {
@Test
fun keys_areScopedToVpnProfile() {
assertEquals(
"profile_0_external_proxy_host",
OutboundFormsStore.key(0, "external_proxy_host")
)
assertEquals(
"profile_2_external_proxy_host",
OutboundFormsStore.key(2, "external_proxy_host")
)
assertEquals(
"profile_2_external_proxy_host",
OutboundFormsStore.key(99, "external_proxy_host")
)
}
@Test
fun secretKeys_haveSeparateEncryptedStorageName() {
assertEquals(
"profile_1_imported_wg_config_encrypted",
OutboundFormsStore.encryptedKey(1, "imported_wg_config")
)
assertTrue(OutboundFormsStore.isSecretPlainKey("profile_1_wg_exit_password"))
assertTrue(OutboundFormsStore.isSecretPlainKey("local_proxy_password"))
assertFalse(OutboundFormsStore.isSecretPlainKey("profile_1_external_proxy_host"))
}
}
@@ -0,0 +1,249 @@
package com.wdtt.plus.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class OutboundProfileComparisonTest {
@Test
fun unusedGeneratedDefaults_doNotLookLikeServerChanges() {
val server = snapshot(
localProxyPort = "1080",
localProxyLogin = "old-generated-login",
localProxyPassword = "old-generated-password",
externalProxyKindName = "",
externalProxyPort = "",
wireGuardExitSshPort = "",
wireGuardExitUser = "",
wireGuardExitPort = "",
wireGuardExitDns = ""
)
val local = forms(
localProxyLogin = "new-generated-login",
localProxyPassword = "new-generated-password"
)
assertFalse(outboundProfilesDiffer(server, local))
}
@Test
fun configuredValues_areComparedAfterStorageNormalization() {
val server = snapshot(
mode = "wireguard_vps",
wireGuardPresent = true,
wireGuardExitHost = "exit.example.org",
wireGuardExitSshPort = "22",
wireGuardExitUser = "root",
wireGuardExitPassword = "secret",
wireGuardExitPort = "51820",
wireGuardExitDns = "1.1.1.1,8.8.8.8"
)
val local = forms(
wireGuardExitHost = " exit.example.org ",
wireGuardExitSshPort = "port 22",
wireGuardExitUser = "root",
wireGuardExitPassword = "secret",
wireGuardExitPort = "51820 ",
wireGuardExitDns = "9.9.9.9"
)
// DNS WireGuard-выхода намеренно не сравнивается: DNS клиентов задаётся
// в основных настройках WDTT и не применяется этим режимом.
assertFalse(outboundProfilesDiffer(server, local))
}
@Test
fun configuredProxyChange_isReported() {
val server = snapshot(
externalProxyPresent = true,
externalProxyKindName = "Socks5",
externalProxyHost = "old.example.org",
externalProxyPort = "1080"
)
val local = forms(externalProxyHost = "new.example.org")
assertTrue(outboundProfilesDiffer(server, local))
}
@Test
fun orphanedWarpInterface_isAttributedOnlyToWarpAndCanBeDisabledThere() {
val server = snapshot(
mode = "direct",
wireGuardPresent = true,
wireGuardActive = true,
warpPresent = true
)
assertEquals(
OutboundModeIndicator(OutboundModeVisualState.Error, "не отключён"),
outboundModeIndicator(server, OutboundDialog.FreeWarp)
)
assertEquals(
OutboundModeVisualState.Off,
outboundModeIndicator(server, OutboundDialog.WireGuardVps).state
)
assertEquals(
OutboundModeVisualState.Off,
outboundModeIndicator(server, OutboundDialog.ImportedWireGuard).state
)
assertTrue(canDisableOutboundDialog(server, OutboundDialog.FreeWarp))
assertFalse(canDisableOutboundDialog(server, OutboundDialog.WireGuardVps))
assertFalse(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard))
assertTrue(canReturnDirect(server))
}
@Test
fun ownerMarker_winsOverUnrelatedWarpRegistration() {
val server = snapshot(
mode = "direct",
wireGuardPresent = true,
wireGuardActive = true,
warpPresent = true,
wireGuardOwnerMode = "imported_wg"
)
assertEquals(
OutboundModeVisualState.Error,
outboundModeIndicator(server, OutboundDialog.ImportedWireGuard).state
)
assertEquals(
OutboundModeVisualState.Warning,
outboundModeIndicator(server, OutboundDialog.FreeWarp).state
)
assertTrue(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard))
assertFalse(canDisableOutboundDialog(server, OutboundDialog.FreeWarp))
}
@Test
fun partialExternalProxy_isNotReportedAsActiveAndCanBeCleaned() {
val server = snapshot(
mode = "external_proxy",
externalProxyPresent = true,
externalProxyServiceActive = true,
externalProxyRouteActive = false
)
assertEquals(
OutboundModeIndicator(OutboundModeVisualState.Error, "запущен частично"),
outboundModeIndicator(server, OutboundDialog.ExternalProxy)
)
assertTrue(canDisableOutboundDialog(server, OutboundDialog.ExternalProxy))
assertTrue(canReturnDirect(server))
}
@Test
fun recordedInactiveWireGuardMode_canStillBeDisabledFromItsDialog() {
val server = snapshot(
mode = "imported_wg",
wireGuardPresent = true,
wireGuardActive = false
)
assertTrue(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard))
assertTrue(canReturnDirect(server))
}
@Test
fun proxyCredentials_rejectAmbiguousValuesAndEscapeConfig() {
assertEquals(
"Логин внешнего прокси не должен содержать двоеточие.",
externalProxyCredentialsIssue("user:name", "password")
)
assertTrue(localProxyCredentialsIssue("user", "short") != null)
assertEquals("""a\\b\"c""", escapeRedsocksQuotedValue("""a\b"c"""))
}
private fun forms(
localProxyPort: String = "1080",
localProxyLogin: String = "generated-login",
localProxyPassword: String = "generated-password",
externalProxyKindName: String = "Socks5",
externalProxyHost: String = "",
externalProxyPort: String = "1080",
externalProxyLogin: String = "",
externalProxyPassword: String = "",
wireGuardExitHost: String = "",
wireGuardExitSshPort: String = "22",
wireGuardExitUser: String = "root",
wireGuardExitPassword: String = "",
wireGuardExitPort: String = "51820",
wireGuardExitDns: String = "1.1.1.1,8.8.8.8",
importedWireGuardConfig: String = ""
) = OutboundProfileForms(
localProxyPort = localProxyPort,
localProxyLogin = localProxyLogin,
localProxyPassword = localProxyPassword,
externalProxyKindName = externalProxyKindName,
externalProxyHost = externalProxyHost,
externalProxyPort = externalProxyPort,
externalProxyLogin = externalProxyLogin,
externalProxyPassword = externalProxyPassword,
wireGuardExitHost = wireGuardExitHost,
wireGuardExitSshPort = wireGuardExitSshPort,
wireGuardExitUser = wireGuardExitUser,
wireGuardExitPassword = wireGuardExitPassword,
wireGuardExitPort = wireGuardExitPort,
wireGuardExitDns = wireGuardExitDns,
importedWireGuardConfig = importedWireGuardConfig
)
private fun snapshot(
mode: String = "direct",
localProxyPresent: Boolean = false,
localProxyPort: String = "",
localProxyLogin: String = "",
localProxyPassword: String = "",
externalProxyPresent: Boolean = false,
externalProxyKindName: String = "",
externalProxyHost: String = "",
externalProxyPort: String = "",
externalProxyLogin: String = "",
externalProxyPassword: String = "",
wireGuardPresent: Boolean = false,
wireGuardActive: Boolean = false,
wireGuardExitHost: String = "",
wireGuardExitSshPort: String = "",
wireGuardExitUser: String = "",
wireGuardExitPassword: String = "",
wireGuardExitPort: String = "",
wireGuardExitDns: String = "",
importedWireGuardConfig: String = "",
warpPresent: Boolean = false,
externalProxyServiceActive: Boolean = false,
externalProxyRouteActive: Boolean = false,
wireGuardOwnerMode: String = ""
) = OutboundServerSnapshot(
mode = mode,
detail = "",
updatedAt = "",
hasProfile = true,
localProxyPresent = localProxyPresent,
localProxyActive = false,
localProxyPort = localProxyPort,
localProxyLogin = localProxyLogin,
localProxyPassword = localProxyPassword,
externalProxyPresent = externalProxyPresent,
externalProxyActive = false,
externalProxyKindName = externalProxyKindName,
externalProxyHost = externalProxyHost,
externalProxyPort = externalProxyPort,
externalProxyLogin = externalProxyLogin,
externalProxyPassword = externalProxyPassword,
wireGuardPresent = wireGuardPresent,
wireGuardActive = wireGuardActive,
wireGuardExitHost = wireGuardExitHost,
wireGuardExitSshPort = wireGuardExitSshPort,
wireGuardExitUser = wireGuardExitUser,
wireGuardExitPassword = wireGuardExitPassword,
wireGuardExitPort = wireGuardExitPort,
wireGuardExitDns = wireGuardExitDns,
warpPresent = warpPresent,
warpMtu = "",
importedWireGuardConfig = importedWireGuardConfig,
checkedAtMillis = 0L,
externalProxyServiceActive = externalProxyServiceActive,
externalProxyRouteActive = externalProxyRouteActive,
wireGuardOwnerMode = wireGuardOwnerMode
)
}
@@ -51,6 +51,8 @@ class OutboundWireGuardTest {
fun freeWarpScript_hasSafeUpdateChecksAndValidShellSyntax() {
val script = buildFreeWarpInstallScript(1392)
assertTrue(WGCF_VERSION == "2.2.32")
assertTrue(THREEPROXY_VERSION == "0.9.7")
assertTrue("WARP_MTU=1392" in script)
assertTrue("checksums.txt" in script)
assertTrue("sha256sum" in script)
@@ -60,9 +62,60 @@ class OutboundWireGuardTest {
assertTrue("WARP_ENDPOINT_CANDIDATES" in script)
assertTrue("engage.cloudflareclient.com:2408" in script)
assertTrue("rollback after WARP check error" in script)
assertTrue("trap wdtt_wg_up_cleanup 0" in script)
assertTrue("rollback after WireGuard service start error" in script)
assertTrue("WDTT_ERROR=wireguard_exit_service_inactive" in script)
assertTrue("ip link delete \"${'$'}WDTT_WG_IFACE\"" in script)
assertShellSyntax(script)
}
@Test
fun directExitScript_forceCleansPartiallyStartedWireGuard() {
val script = disableOutboundExitScript()
assertTrue("wdtt_clear_external_out" in script)
assertTrue("ip link delete \"${'$'}WDTT_WG_IFACE\"" in script)
assertTrue("WDTT_ERROR=direct_cleanup_failed" in script)
assertTrue("wdtt_write_mode \"direct\"" in script)
assertShellSyntax(script)
}
@Test
fun outboundCleanupScripts_areScopedAndHaveValidShellSyntax() {
val localStop = stopLocalProxyScript()
val localRemove = removeLocalProxyScript()
val external = deleteExternalProxyScript()
val imported = deleteImportedWireGuardExitScript()
val currentVps = deleteWireGuardVpsCurrentScript()
val foreignVps = deleteWireGuardVpsForeignScript()
assertTrue("systemctl disable --now wdtt-3proxy" in localStop)
assertTrue("local_proxy_service_still_active" in localStop)
assertTrue("LOCAL_PROXY_PASSWORD_B64" in localRemove)
assertTrue("local_proxy_remove_failed" in localRemove)
assertTrue("wdtt_clear_proxy_out" in external)
assertTrue("EXTERNAL_PROXY_PASSWORD_B64" in external)
assertTrue("external_proxy_remove_failed" in external)
assertTrue("OWNS_ACTIVE" in imported)
assertTrue("wdtt_clear_wireguard_out" in imported)
assertTrue("IMPORTED_WG_CONFIG_B64" in imported)
assertTrue("wireguard_vps_current_remove_failed" in currentVps)
assertTrue("WDTT_EXIT_FOREIGN" in foreignVps)
assertTrue("foreign_wireguard_not_owned" in foreignVps)
assertShellSyntax(localStop)
assertShellSyntax(localRemove)
assertShellSyntax(external)
assertShellSyntax(imported)
assertShellSyntax(currentVps)
assertShellSyntax(foreignVps)
}
@Test
fun protocolErrorMarker_isNotCopiedRawToUserLog() {
assertFalse(shouldWriteRemoteErrorToUserLog("WDTT_ERROR=local_proxy_check_failed"))
assertTrue(shouldWriteRemoteErrorToUserLog("FAIL: служба не запустилась"))
}
@Test
fun serverDiagnosticsScript_hasPortableChecksAndValidShellSyntax() {
val script = serverDiagnosticsScript()
@@ -79,12 +132,25 @@ class OutboundWireGuardTest {
assertTrue("systemctl" in script)
assertTrue("iptables" in script)
assertTrue("nft" in script)
assertTrue("VK / TURN-зависимости" in script)
assertTrue("VK/OK с VPS (справочно)" in script)
assertTrue("не влияет на основной VK-вход" in script)
assertTrue("login.vk.ru" in script)
assertTrue("api.vk.me" in script)
assertTrue("api.vk.ru" in script)
assertTrue("calls.okcdn.ru" in script)
assertTrue("Получение VK-токенов и решение капчи выполняются на телефоне" in script)
assertFalse("обязательным узлам VK в зоне .ru" in script)
assertTrue("api.telegram.org" in script)
assertTrue("Бесплатный WARP" in script)
assertTrue("engage.cloudflareclient.com" in script)
assertTrue("wdtt_diag_wg_exit_probe" in script)
assertTrue("Cloudflare подтвердил warp=" in script)
assertTrue("WG_POLICY_RULE_ACTIVE" in script)
assertTrue("WG_DEFAULT_ROUTE_ACTIVE" in script)
assertTrue("WG_NAT_ACTIVE" in script)
assertTrue("WireGuard-выход запущен не полностью" in script)
assertTrue("FIREWALL_SEVERITY=\"ERROR\"" in script)
assertTrue("NAT прямого выхода отсутствует" in script)
assertTrue("WDTT_EXPECTED_DTLS_PORT" in script)
assertTrue("wdtt_diag_udp_probe" in script)
assertTrue("/dev/net/tun" in script)
@@ -93,6 +159,42 @@ class OutboundWireGuardTest {
assertShellSyntax(script, shell = "sh")
}
@Test
fun externalProxyTransparentCheck_doesNotCaptureRootXrayTraffic() {
val script = outboundShellPrelude()
assertTrue("WDTT_PROXY_TEST_SOURCE=\"${'$'}test_source\"" in script)
assertTrue("iptables -t nat -I OUTPUT -s \"${'$'}test_source\" -p tcp -j WDTT_PROXY_TEST" in script)
assertTrue("curl --interface \"${'$'}test_source\"" in script)
assertFalse("iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST" in script)
assertShellSyntax(script)
}
@Test
fun outboundSnapshot_preservesExplicitlySavedEmptyFields() {
val script = outboundSnapshotScript()
assertTrue("wdtt_profile_has_key" in script)
assertTrue("if wdtt_profile_has_key LOCAL_PROXY_LOGIN_B64" in script)
assertTrue("if wdtt_profile_has_key EXTERNAL_PROXY_HOST_B64" in script)
assertTrue("if wdtt_profile_has_key WG_VPS_DNS_B64" in script)
assertTrue("! wdtt_profile_has_key IMPORTED_WG_CONFIG_B64" in script)
assertTrue("WDTT_LOCAL_PROXY_SERVICE_ENABLED" in script)
assertTrue("WDTT_EXTERNAL_PROXY_SERVICE_ENABLED" in script)
assertTrue("WDTT_WG_SERVICE_ENABLED" in script)
assertShellSyntax(script)
}
@Test
fun detailedOutboundStatus_reportsRoutesAndAutostart() {
val script = outboundStatusScript()
assertTrue("Автозапуск внешнего TCP-прокси" in script)
assertTrue("Правило маршрутизации подсети WDTT" in script)
assertTrue("NAT WireGuard-выхода" in script)
assertShellSyntax(script)
}
@Test(expected = IllegalArgumentException::class)
fun freeWarpScript_rejectsUnsafeMtu() {
buildFreeWarpInstallScript(1600)
@@ -2,8 +2,11 @@ package com.wdtt.plus.ui
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Base64
class ServerMigrationTest {
@Test
@@ -11,6 +14,64 @@ class ServerMigrationTest {
validatePasswordsDbStructure(database("client-a", "Телефон"))
}
@Test
fun backupValidation_acceptsTrafficImportHistory() {
val db = database("client-a", "Телефон")
validatePasswordsDbStructure(db)
}
@Test(expected = IllegalArgumentException::class)
fun backupValidation_rejectsMalformedTrafficImportHistory() {
val db = database("client-a", "Телефон")
db.getJSONObject("passwords").getJSONObject("client-a")
.put("traffic_imports", JSONArray())
validatePasswordsDbStructure(db)
}
@Test
fun preserveValidation_recoversEmptyMainPasswordFromCurrentSecrets() {
val db = database("client-a", "Телефон").put("main_password", "")
val needsRecovery = validatePasswordsDbForPreserving(db, "new-owner-password")
assertTrue(needsRecovery)
assertTrue(db.optString("main_password").isEmpty())
assertTrue(db.getJSONObject("passwords").has("client-a"))
}
@Test
fun preserveValidation_recoversMissingMainPasswordFromCurrentSecrets() {
val db = database("client-a", "Телефон").apply { remove("main_password") }
assertTrue(validatePasswordsDbForPreserving(db, "new-owner-password"))
assertTrue(!db.has("main_password"))
}
@Test
fun preserveValidation_keepsValidMainPassword() {
val db = database("client-a", "Телефон")
assertTrue(!validatePasswordsDbForPreserving(db, "new-owner-password"))
assertTrue(db.optString("main_password") == "owner-password")
}
@Test(expected = IllegalArgumentException::class)
fun preserveValidation_rejectsRecoveryWithoutCurrentMainPassword() {
val db = database("client-a", "Телефон").put("main_password", "")
validatePasswordsDbForPreserving(db, "")
}
@Test(expected = IllegalArgumentException::class)
fun preserveValidation_stillRejectsMalformedClientDataDuringRecovery() {
val db = database("client-a", "Телефон").put("main_password", "")
db.getJSONObject("passwords").getJSONObject("client-a").put("expires_at", -1L)
validatePasswordsDbForPreserving(db, "new-owner-password")
}
@Test(expected = IllegalArgumentException::class)
fun backupValidation_rejectsInvalidOwnerProfile() {
val db = database("client-a", "Телефон")
@@ -28,6 +89,19 @@ class ServerMigrationTest {
validateImportedServerState(source.toString(), null, after.toString(), replace = true)
}
@Test(expected = IllegalArgumentException::class)
fun replaceImport_detectsChangedTrafficImportHistory() {
val source = database("client-a", "Телефон")
val after = JSONObject(source.toString())
after.getJSONObject("passwords")
.getJSONObject("client-a")
.getJSONObject("traffic_imports")
.getJSONObject("move-1")
.put("down_bytes", 999L)
validateImportedServerState(source.toString(), null, after.toString(), replace = true)
}
@Test
fun mergeImport_preservesTargetAndAddsMissingClient() {
val before = database("target-client", "Существующий")
@@ -79,10 +153,120 @@ class ServerMigrationTest {
assertTrue(target.getJSONObject("devices").getJSONObject("used-device").getString("ip") == "10.66.66.3")
}
@Test
fun replaceAdaptsOwnerAndClientPortsToTarget() {
val source = database("client-a", "Телефон")
val prepared = JSONObject(
prepareServerDatabaseForTarget(
sourceJson = source.toString(),
currentDbJson = null,
merge = false,
portsSpec = "56100,56101,9100",
dnsValue = "9.9.9.9",
publicHost = "new.example.org"
)
)
assertEquals(
"56100,56101,9100",
prepared.getJSONObject("passwords").getJSONObject("client-a").getString("ports")
)
assertEquals("56100,56101,9100", prepared.getJSONObject("admin_profile").getString("ports"))
assertEquals(9100, prepared.getJSONObject("admin_profile").getInt("listen_port"))
assertEquals("new.example.org", prepared.getString("public_ip"))
}
@Test
fun mergeIntoEmptyServerKeepsWholeSourceDatabase() {
val source = database("client-a", "Телефон")
.put("admin_down_bytes", 12_345L)
.put("admin_up_bytes", 54_321L)
val prepared = JSONObject(
prepareServerDatabaseForTarget(
sourceJson = source.toString(),
currentDbJson = null,
merge = true,
portsSpec = "56100,56101,9100",
dnsValue = "9.9.9.9",
publicHost = "new.example.org"
)
)
assertEquals(12_345L, prepared.getLong("admin_down_bytes"))
assertEquals(54_321L, prepared.getLong("admin_up_bytes"))
assertTrue(prepared.getJSONObject("admin_profile").has("workers_per_hash"))
assertTrue(prepared.getJSONObject("passwords").has("client-a"))
}
@Test
fun versionTwoBackupRoundTripVerifiesIntegrity() {
val source = database("client-a", "Телефон")
val keys = List(4) { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }.joinToString("\n")
val encoded = backupToJson(
parseBackup(
passwordsJson = source.toString(),
wgKeysDat = keys,
createdAt = "27.07.2026 12:00",
sourceHost = "old.example.org"
)
)
val decoded = parseBackupFile(encoded)
assertEquals(2, decoded.formatVersion)
assertTrue(decoded.integrityVerified)
assertTrue(decoded.hasWgKeys)
assertEquals(source.toString(), decoded.passwordsJson)
}
@Test(expected = IllegalArgumentException::class)
fun versionTwoBackupRejectsChangedDatabase() {
val source = database("client-a", "Телефон")
val encoded = JSONObject(
backupToJson(
parseBackup(
passwordsJson = source.toString(),
wgKeysDat = null,
createdAt = "27.07.2026 12:00",
sourceHost = "old.example.org"
)
)
)
val changed = JSONObject(source.toString()).put("dns", "8.8.8.8").toString()
encoded.put(
"passwords_json_b64",
Base64.getEncoder().encodeToString(changed.toByteArray())
)
parseBackupFile(encoded.toString())
}
@Test
fun versionOneBackupRemainsCompatible() {
val source = database("client-a", "Телефон")
val legacy = JSONObject()
.put("format", "wdtt-server-backup")
.put("version", 1)
.put("created_at", "05.07.2026 10:00")
.put("source_host", "old.example.org")
.put(
"passwords_json_b64",
Base64.getEncoder().encodeToString(source.toString().toByteArray())
)
val decoded = parseBackupFile(legacy.toString())
assertEquals(1, decoded.formatVersion)
assertFalse(decoded.integrityVerified)
assertEquals(source.toString(), decoded.passwordsJson)
}
private fun database(password: String, label: String): JSONObject {
val entry = JSONObject()
.put("device_id", "")
.put("expires_at", 0L)
.put("expires_at", 2_000_000_000L)
.put("down_bytes", 1024L)
.put("up_bytes", 2048L)
.put("label", label)
@@ -94,6 +278,13 @@ class ServerMigrationTest {
.put("down_bytes", 1024L)
.put("up_bytes", 2048L)
))
.put("traffic_imports", JSONObject().put(
"move-1",
JSONObject()
.put("down_bytes", 100L)
.put("up_bytes", 200L)
.put("applied_at", 1_700_000_000L)
))
.put("bind_history", JSONArray())
return JSONObject()
.put("main_password", "owner-password")
@@ -0,0 +1,102 @@
package com.wdtt.plus.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class VkClientIdProbeTest {
@Test
fun legacyProbePrefersVkRuAndKeepsVkComAsCompatibilityFallback() {
assertEquals("https://oauth.vk.ru/authorize", vkLegacyOAuthProbeEndpoints.first())
assertEquals("https://oauth.vk.com/authorize", vkLegacyOAuthProbeEndpoints.last())
}
@Test
fun acceptsLegacyOauthLoginPage() {
assertTrue(isVkLegacyClientIdProbeSuccessful(200, "text/html; charset=utf-8"))
}
@Test
fun rejectsJsonErrorsAndHttpFailures() {
assertFalse(isVkLegacyClientIdProbeSuccessful(401, "application/json; charset=utf-8"))
assertFalse(isVkLegacyClientIdProbeSuccessful(200, "application/json"))
assertFalse(isVkLegacyClientIdProbeSuccessful(503, "text/html"))
assertTrue(isVkLegacyClientIdProbeRejected(401))
assertFalse(isVkLegacyClientIdProbeRejected(429))
assertFalse(isVkLegacyClientIdProbeRejected(503))
}
@Test
fun cachedProbeResultsKeepStatusAndTimestampSeparate() {
val cache = parseVkClientIdCheckResults(
"""{"_probe_version":3,"_checked_at":123456,"6287487":"LegacyCompatible","8202606":"LegacyRejected"}"""
)
assertEquals(123456L, cache.checkedAt)
assertEquals(
mapOf(
"6287487" to VkClientIdProbeStatus.LegacyCompatible,
"8202606" to VkClientIdProbeStatus.LegacyRejected
),
cache.results
)
}
@Test
fun probeCooldownBlocksRapidRepeatedChecks() {
assertEquals(10_000L, vkClientIdProbeCooldownRemainingMillis(now = 20_000L, lastStartedAt = 20_000L))
assertEquals(1L, vkClientIdProbeCooldownRemainingMillis(now = 29_999L, lastStartedAt = 20_000L))
assertEquals(0L, vkClientIdProbeCooldownRemainingMillis(now = 30_000L, lastStartedAt = 20_000L))
}
@Test
fun availabilitySummaryExplainsAllProbeCombinations() {
val ids = listOf("6287487", "8202606")
assertEquals(
"Все встроенные Client ID доступны для резервного способа",
vkClientIdAvailabilityMessage(
ids,
mapOf(
"6287487" to VkClientIdProbeStatus.LegacyCompatible,
"8202606" to VkClientIdProbeStatus.LegacyCompatible
)
)
)
assertEquals(
"Доступны: 6287487. Не принимаются: 8202606.",
vkClientIdAvailabilityMessage(
ids,
mapOf(
"6287487" to VkClientIdProbeStatus.LegacyCompatible,
"8202606" to VkClientIdProbeStatus.LegacyRejected
)
)
)
assertEquals(
"Не удалось проверить: 6287487, 8202606.",
vkClientIdAvailabilityMessage(
ids,
mapOf(
"6287487" to VkClientIdProbeStatus.CheckFailed,
"8202606" to VkClientIdProbeStatus.CheckFailed
)
)
)
}
@Test
fun automaticProbeUsesOnlyCredentialsForSelectedMode() {
assertEquals(
listOf("6287487", "8202606"),
vkClientIdsForAutomaticProbe(false, "123456", "secret")
)
assertEquals(
listOf("123456"),
vkClientIdsForAutomaticProbe(true, "123456", "secret")
)
assertTrue(vkClientIdsForAutomaticProbe(true, "123456", "").isEmpty())
assertTrue(vkClientIdsForAutomaticProbe(true, "invalid", "secret").isEmpty())
}
}
@@ -0,0 +1,74 @@
package com.wdtt.plus.ui
import org.junit.Assert.assertEquals
import org.junit.Test
class VkHashBulkPasteTest {
@Test
fun parseBulkVkHashesAcceptsCommaSeparatedHashes() {
assertEquals(
listOf("hash000000000001", "hash000000000002", "hash000000000003", "hash000000000004"),
parseBulkVkHashes("hash000000000001,hash000000000002,hash000000000003,hash000000000004")
)
}
@Test
fun parseBulkVkHashesAcceptsEncodedSpacesAndSeparators() {
assertEquals(
listOf("hash000000000001", "hash000000000002", "hash000000000003", "hash000000000004"),
parseBulkVkHashes("hash000000000001%20hash000000000002%2Chash000000000003%0Ahash000000000004")
)
}
@Test
fun parseBulkVkHashesExtractsJoinLinksAndDropsDuplicates() {
assertEquals(
listOf("hash000000000001", "hash000000000002"),
parseBulkVkHashes(
"https://vk.com/call/join/hash000000000001 " +
"https://vk.ru/call/join/hash000000000002 " +
"hash000000000001"
)
)
}
@Test
fun parseBulkVkHashesRejectsOrdinaryLongWords() {
assertEquals(
emptyList<String>(),
parseBulkVkHashes("пользовательский переподключаются")
)
}
@Test
fun mergeBulkVkHashesFillsOnlyEmptySlotsWithoutOverwritingExisting() {
val result = mergeBulkVkHashes(
existingSlots = listOf("", "oldHash0000000002", "oldHash0000000003", ""),
incomingHashes = listOf("newHash0000000001", "oldHash0000000002", "newHash0000000004"),
mode = BulkVkHashPasteMode.FillEmpty
)
assertEquals(
listOf("newHash0000000001", "oldHash0000000002", "oldHash0000000003", "newHash0000000004"),
result.slots
)
assertEquals(2, result.insertedCount)
assertEquals(1, result.skippedCount)
}
@Test
fun mergeBulkVkHashesReplacesAllSlotsWhenRequested() {
val result = mergeBulkVkHashes(
existingSlots = listOf("", "oldHash0000000002", "oldHash0000000003", ""),
incomingHashes = listOf("newHash0000000001", "newHash0000000002", "newHash0000000003", "newHash0000000004"),
mode = BulkVkHashPasteMode.ReplaceAll
)
assertEquals(
listOf("newHash0000000001", "newHash0000000002", "newHash0000000003", "newHash0000000004"),
result.slots
)
assertEquals(4, result.insertedCount)
assertEquals(0, result.skippedCount)
}
}
+219 -67
View File
@@ -12,8 +12,12 @@ import (
"strconv"
"strings"
"time"
)
"golang.zx2c4.com/wireguard/device"
const (
botThreeProxyVersion = "0.9.7"
botThreeProxySourceURL = "https://github.com/3proxy/3proxy/archive/refs/tags/0.9.7.tar.gz"
botThreeProxySourceSHA256 = "efe862ef8b7c0ddf7b1c45d6b5d72f0b7cd0a3c54447419c7f1bd2239a06fc30"
)
func defaultPortsSpec() string {
@@ -141,7 +145,7 @@ func normalizePasswordLabel(input string) string {
}
func createBotClient(
wgDev *device.Device,
wgDev wgDevice,
requestedPassword string,
days int,
expiresAt int64,
@@ -226,7 +230,7 @@ func createBotClient(
return password, entry, nil
}
func changeBotClientPassword(wgDev *device.Device, oldPassword, requested string) (string, error) {
func changeBotClientPassword(wgDev wgDevice, oldPassword, requested string) (string, error) {
newPassword, err := normalizeClientPassword(requested)
if err != nil {
return "", err
@@ -246,7 +250,7 @@ func changeBotClientPassword(wgDev *device.Device, oldPassword, requested string
if _, exists := db.Passwords[newPassword]; exists {
return "", errors.New("клиент с таким паролем уже существует")
}
if !entry.IsDeactivated && !isPasswordExpired(entry) {
if !entry.IsDeactivated && !isPasswordPurgeable(entry) {
if err := serverWrapKeys.AddPassword(newPassword); err != nil {
return "", fmt.Errorf("не удалось добавить новый WRAP-ключ: %w", err)
}
@@ -430,8 +434,14 @@ func botScriptErrorText(err error, output string) string {
return "Не удалось собрать 3proxy: на сервере нет компилятора gcc/cc, и пакетный менеджер не смог его поставить."
case "3proxy_source_no_openssl_headers":
return "Не удалось собрать 3proxy: на сервере нет OpenSSL-заголовков. Нужен пакет libssl-dev, openssl-devel, libopenssl-devel или openssl-dev в зависимости от Linux-дистрибутива."
case "3proxy_source_no_pcre2_headers":
return "Не удалось собрать актуальный 3proxy: на сервере нет заголовков PCRE2. Нужен пакет libpcre2-dev или pcre2-devel."
case "3proxy_source_no_sha256sum":
return "Не удалось безопасно проверить архив 3proxy: на сервере нет sha256sum."
case "3proxy_source_download_failed":
return "Не удалось скачать исходники 3proxy с GitHub. Проверьте, открывается ли github.com с сервера и не блокирует ли сеть исходящие HTTPS-подключения."
return "Не удалось скачать закреплённый выпуск 3proxy с GitHub. Проверьте, открывается ли github.com с сервера и не блокирует ли сеть исходящие HTTPS-подключения."
case "3proxy_source_checksum_failed":
return "Контрольная сумма архива 3proxy не совпала с закреплённым выпуском. Архив не был распакован или запущен."
case "3proxy_source_unpack_failed":
return "Архив 3proxy скачался, но сервер не смог его распаковать. Возможен битый архив, нехватка места или проблема с tar/gzip."
case "3proxy_source_build_failed":
@@ -441,7 +451,7 @@ func botScriptErrorText(err error, output string) string {
case "3proxy_source_install_failed":
return "3proxy собрался, но сервер не дал записать файл в /usr/local/bin. Проверьте root-права пользователя и sudo."
case "3proxy_install_failed":
return "Не удалось установить 3proxy: пакет не найден в репозиториях сервера, а сборка из исходников не дала готовый файл. Повторите установку: теперь бот покажет конкретный шаг, на котором она сорвалась."
return "Не удалось установить закреплённый выпуск 3proxy из проверенных исходников. Повторите установку: бот покажет конкретный шаг, на котором она сорвалась."
case "systemd_required":
return "Для прокси на этом сервере нужна systemd-служба. На сервере не найден systemctl, поэтому бот не может безопасно запустить 3proxy как сервис."
case "curl_not_installed":
@@ -450,10 +460,16 @@ func botScriptErrorText(err error, output string) string {
return "Внешний прокси не ответил. Проверьте тип, адрес, порт, логин и пароль."
case "external_proxy_service_inactive":
return "Служба перенаправления через внешний прокси не запустилась. Бот откатил правила и вернул прямой выход, чтобы интернет через VPN не остался сломанным."
case "external_proxy_route_install_failed":
return "Служба внешнего прокси запустилась, но постоянное правило маршрутизации WDTT не применилось. Режим отключён."
case "external_proxy_test_rule_failed":
return "Сервер не разрешил создать временное правило для проверки пути WDTT через внешний прокси. Режим не считается проверенным."
case "external_proxy_apply_failed":
return botTextWithRemoteTail("Внешний прокси отвечает напрямую, но путь WDTT через redsocks не заработал. Бот откатил правила и вернул прямой выход, чтобы VPN-интернет не пропал.", output)
case "iptables_required":
return "На сервере не найдены правила межсетевого экрана iptables. Без них нельзя направить подключения WDTT через прокси."
case "direct_cleanup_failed":
return "Сервер не подтвердил полную остановку прежнего WireGuard/прокси-выхода. Выполните диагностику перед включением другого режима."
case "local_proxy_check_failed":
return "Проверка не устанавливает прокси: она подключается к уже запущенному SOCKS5 на 127.0.0.1 с сохранёнными логином и паролем. Подключение не удалось. Создайте или обновите прокси."
case "local_proxy_config_not_found":
@@ -464,6 +480,8 @@ func botScriptErrorText(err error, output string) string {
return "Служба wdtt-3proxy не запущена. Создайте или обновите прокси на сервере."
case "local_proxy_service_still_active":
return "Команда остановки выполнена, но служба wdtt-3proxy всё ещё запущена. Проверьте права пользователя SSH или остановите службу вручную."
case "local_proxy_firewall_failed":
return "Прокси запустился, но сервер не смог открыть его порты в firewall. Служба остановлена."
case "redsocks_not_installed":
return "Не удалось установить компонент перенаправления через внешний прокси. Проверьте доступ сервера к интернету и пакетному менеджеру."
case "wdtt_iface_not_found":
@@ -500,7 +518,10 @@ func isFriendlyBotScriptError(err error) bool {
"3proxy_source_no_make",
"3proxy_source_no_compiler",
"3proxy_source_no_openssl_headers",
"3proxy_source_no_pcre2_headers",
"3proxy_source_no_sha256sum",
"3proxy_source_download_failed",
"3proxy_source_checksum_failed",
"3proxy_source_unpack_failed",
"3proxy_source_build_failed",
"3proxy_source_binary_missing",
@@ -510,13 +531,17 @@ func isFriendlyBotScriptError(err error) bool {
"curl_not_installed",
"external_proxy_check_failed",
"external_proxy_service_inactive",
"external_proxy_route_install_failed",
"external_proxy_test_rule_failed",
"external_proxy_apply_failed",
"iptables_required",
"direct_cleanup_failed",
"local_proxy_check_failed",
"local_proxy_config_not_found",
"local_proxy_credentials_missing",
"local_proxy_service_inactive",
"local_proxy_service_still_active",
"local_proxy_firewall_failed",
"redsocks_not_installed",
"wdtt_iface_not_found",
"wdtt_test_source_missing",
@@ -612,16 +637,19 @@ wdtt_clear_external_out() {
systemctl disable --now wdtt-warp-watchdog.timer 2>/dev/null || true
systemctl disable --now wdtt-wg-exit.service 2>/dev/null || true
if command -v iptables >/dev/null 2>&1; then
iptables -t nat -D PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null || true
while iptables -t nat -D PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null; do :; done
iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true
iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true
iptables -t nat -D POSTROUTING -s "$WDTT_SUBNET" -o "$WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null || true
while iptables -t nat -D POSTROUTING -s "$WDTT_SUBNET" -o "$WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null; do :; done
fi
ip rule del from "$WDTT_SUBNET" table "$WDTT_TABLE" priority 100 2>/dev/null || true
while ip rule del from "$WDTT_SUBNET" table "$WDTT_TABLE" priority 100 2>/dev/null; do :; done
ip route flush table "$WDTT_TABLE" 2>/dev/null || true
systemctl disable --now wdtt-redsocks 2>/dev/null || systemctl stop wdtt-redsocks 2>/dev/null || true
wdtt_kill_redsocks_listener
wg-quick down "$WDTT_WG_IFACE" 2>/dev/null || true
if ! wg-quick down "$WDTT_WG_IFACE" 2>/dev/null; then
ip link delete "$WDTT_WG_IFACE" 2>/dev/null || true
fi
rm -f /etc/wdtt-plus/wg-exit/owner
}
wdtt_kill_redsocks_listener() {
rm -f /run/wdtt-redsocks.pid 2>/dev/null || true
@@ -646,24 +674,32 @@ wdtt_proxy_reserved_returns() {
[ -n "$proxy_ip" ] && iptables -t nat -A "$chain" -d "$proxy_ip" -j RETURN 2>/dev/null || true
}
wdtt_cleanup_proxy_test() {
cleanup_test_source="${WDTT_PROXY_TEST_SOURCE:-}"
[ -n "$cleanup_test_source" ] && iptables -t nat -D OUTPUT -s "$cleanup_test_source" -p tcp -j WDTT_PROXY_TEST 2>/dev/null || true
# Удаляем также правило старых версий, если предыдущая проверка была прервана.
iptables -t nat -D OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST 2>/dev/null || true
iptables -t nat -F WDTT_PROXY_TEST 2>/dev/null || true
iptables -t nat -X WDTT_PROXY_TEST 2>/dev/null || true
WDTT_PROXY_TEST_SOURCE=""
}
wdtt_test_redsocks_path() {
proxy_ip="$1"
systemctl is-active --quiet wdtt-redsocks || { echo WDTT_ERROR=external_proxy_service_inactive; return 1; }
command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; return 1; }
test_source="$(wdtt_test_source)"
[ -n "$test_source" ] || { echo WDTT_ERROR=wdtt_iface_not_found; return 1; }
wdtt_cleanup_proxy_test
WDTT_PROXY_TEST_SOURCE="$test_source"
iptables -t nat -N WDTT_PROXY_TEST 2>/dev/null || true
iptables -t nat -F WDTT_PROXY_TEST
wdtt_proxy_reserved_returns WDTT_PROXY_TEST "$proxy_ip"
iptables -t nat -A WDTT_PROXY_TEST -p tcp -j REDIRECT --to-ports 12345
if ! iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST 2>/dev/null; then
if ! iptables -t nat -I OUTPUT -s "$test_source" -p tcp -j WDTT_PROXY_TEST 2>/dev/null; then
wdtt_cleanup_proxy_test
return 0
echo WDTT_ERROR=external_proxy_test_rule_failed
return 1
fi
test_ip="$(curl -4fsS --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/tmp/wdtt-redsocks-test.err || true)"
test_ip="$(curl --interface "$test_source" -4fsS --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/tmp/wdtt-redsocks-test.err || true)"
wdtt_cleanup_proxy_test
[ -n "$test_ip" ] || { echo WDTT_ERROR=external_proxy_apply_failed; tail -n 20 /var/log/wdtt-redsocks.log 2>/dev/null || true; cat /tmp/wdtt-redsocks-test.err 2>/dev/null || true; return 1; }
echo "Проверка пути через внешний прокси успешна. IP через прокси: $test_ip"
@@ -711,17 +747,35 @@ echo "Подсеть клиентов WDTT: $WDTT_SUBNET"
echo "Интерфейс клиентов: $WDTT_IFACE"
echo "Внешний IP самого сервера: $SERVER_IP"
if systemctl is-active wdtt-3proxy >/dev/null 2>&1; then echo "Прокси на этом сервере: служба запущена"; else echo "Прокси на этом сервере: служба остановлена"; fi
EXTERNAL_ACTIVE=0
if systemctl is-active wdtt-redsocks >/dev/null 2>&1; then EXTERNAL_ACTIVE=1; echo "Внешний прокси для WDTT: включён"; else echo "Внешний прокси для WDTT: выключен"; fi
WG_ACTIVE=0
if systemctl is-enabled wdtt-3proxy >/dev/null 2>&1; then echo "Автозапуск прокси на этом сервере: включён"; else echo "Автозапуск прокси на этом сервере: выключен"; fi
EXTERNAL_SERVICE=0
if systemctl is-active wdtt-redsocks >/dev/null 2>&1; then EXTERNAL_SERVICE=1; echo "Служба внешнего прокси: запущена"; else echo "Служба внешнего прокси: остановлена"; fi
if systemctl is-enabled wdtt-redsocks >/dev/null 2>&1; then echo "Автозапуск внешнего прокси: включён"; else echo "Автозапуск внешнего прокси: выключен"; fi
EXTERNAL_ROUTE=0
if command -v iptables >/dev/null 2>&1 &&
iptables -t nat -C PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null; then
EXTERNAL_ROUTE=1
echo "Маршрут TCP-трафика WDTT через внешний прокси: применён"
else
echo "Маршрут TCP-трафика WDTT через внешний прокси: отсутствует"
fi
WG_INTERFACE=0
if command -v wg >/dev/null 2>&1 && wg show "$WDTT_WG_IFACE" >/dev/null 2>&1; then
WG_ACTIVE=1
WG_INTERFACE=1
echo "WireGuard $WDTT_WG_IFACE:"
wg show "$WDTT_WG_IFACE" | sed -E 's/(private key: ).*/\1(скрыт)/'
else
echo "WireGuard $WDTT_WG_IFACE: не запущен"
fi
if [ "$EXTERNAL_ACTIVE" = 1 ] && [ "$WG_ACTIVE" = 1 ]; then
if systemctl is-active wdtt-wg-exit.service >/dev/null 2>&1; then echo "Служба WireGuard-выхода: запущена"; else echo "Служба WireGuard-выхода: остановлена"; fi
if systemctl is-enabled wdtt-wg-exit.service >/dev/null 2>&1; then echo "Автозапуск WireGuard-выхода: включён"; else echo "Автозапуск WireGuard-выхода: выключен"; fi
WG_ROUTE=0
ip rule show 2>/dev/null | grep -Eq "from [^ ]+ lookup $WDTT_TABLE([[:space:]]|$)|from [^ ]+ lookup wdtt-exit([[:space:]]|$)" && WG_ROUTE=1
ip route show table "$WDTT_TABLE" 2>/dev/null | grep -Eq "^default([[:space:]].*)? dev $WDTT_WG_IFACE([[:space:]]|$)" && WG_ROUTE=1
if command -v iptables >/dev/null 2>&1; then
iptables -t nat -S POSTROUTING 2>/dev/null | grep -q -- "-o $WDTT_WG_IFACE .*--comment WDTT_EXIT .*MASQUERADE" && WG_ROUTE=1
fi
if [ "$EXTERNAL_ROUTE" = 1 ] && { [ "$WG_INTERFACE" = 1 ] || [ "$WG_ROUTE" = 1 ]; }; then
echo "Внимание: одновременно активны внешний TCP-прокси и WireGuard-выход. Верните прямой выход или выполните диагностику перед новым переключением."
fi
if [ "$MODE" = "warp_free" ]; then
@@ -789,6 +843,17 @@ tail -n 20 /var/log/wdtt-redsocks.log 2>/dev/null || echo "Лог redsocks пу
func outboundDisableScript() string {
return outboundBotPrelude() + `
wdtt_clear_external_out
CLEANUP_LEFT=0
(command -v wg >/dev/null 2>&1 && wg show "$WDTT_WG_IFACE" >/dev/null 2>&1) && CLEANUP_LEFT=1
systemctl is-active --quiet wdtt-wg-exit.service 2>/dev/null && CLEANUP_LEFT=1
systemctl is-active --quiet wdtt-redsocks.service 2>/dev/null && CLEANUP_LEFT=1
ip rule show 2>/dev/null | grep -Eq "from [^ ]+ lookup $WDTT_TABLE([[:space:]]|$)|from [^ ]+ lookup wdtt-exit([[:space:]]|$)" && CLEANUP_LEFT=1
ip route show table "$WDTT_TABLE" 2>/dev/null | grep -Eq "^default([[:space:]].*)? dev $WDTT_WG_IFACE([[:space:]]|$)" && CLEANUP_LEFT=1
if command -v iptables >/dev/null 2>&1; then
iptables -t nat -S PREROUTING 2>/dev/null | grep -q -- "-i $WDTT_IFACE .* -j WDTT_PROXY_OUT" && CLEANUP_LEFT=1
iptables -t nat -S POSTROUTING 2>/dev/null | grep -q -- "-o $WDTT_WG_IFACE .*--comment WDTT_EXIT .*MASQUERADE" && CLEANUP_LEFT=1
fi
[ "$CLEANUP_LEFT" = 0 ] || { echo WDTT_ERROR=direct_cleanup_failed; exit 3; }
wdtt_write_mode "direct" "прямой выход через текущий сервер"
echo "Внешний прокси или WireGuard-выход отключён. WDTT-пользователи снова идут напрямую через текущий сервер."
`
@@ -900,6 +965,9 @@ HTTP_PORT=%d
ADMIN_PORT=%d
PROXY_LOGIN=%s
PROXY_PASSWORD=%s
THREEPROXY_VERSION=%s
THREEPROXY_SOURCE_URL=%s
THREEPROXY_SOURCE_SHA256=%s
install_pkg() {
if command -v apt-get >/dev/null 2>&1; then
apt-get update -y >/dev/null 2>&1 || true
@@ -920,17 +988,17 @@ install_pkg() {
}
install_3proxy_build_deps() {
if command -v apt-get >/dev/null 2>&1; then
install_pkg curl ca-certificates tar gzip make gcc libc6-dev libssl-dev
install_pkg curl ca-certificates tar gzip make gcc coreutils libc6-dev libssl-dev libpcre2-dev
elif command -v dnf >/dev/null 2>&1; then
install_pkg curl ca-certificates tar gzip make gcc glibc-devel openssl-devel
install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel openssl-devel pcre2-devel
elif command -v yum >/dev/null 2>&1; then
install_pkg curl ca-certificates tar gzip make gcc glibc-devel openssl-devel
install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel openssl-devel pcre2-devel
elif command -v zypper >/dev/null 2>&1; then
install_pkg curl ca-certificates tar gzip make gcc glibc-devel libopenssl-devel
install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel libopenssl-devel pcre2-devel
elif command -v apk >/dev/null 2>&1; then
install_pkg curl ca-certificates tar gzip make gcc musl-dev linux-headers openssl-dev
install_pkg curl ca-certificates tar gzip make gcc coreutils musl-dev linux-headers openssl-dev pcre2-dev
elif command -v pacman >/dev/null 2>&1; then
install_pkg curl ca-certificates tar gzip make gcc glibc openssl
install_pkg curl ca-certificates tar gzip make gcc coreutils glibc openssl pcre2
else
return 1
fi
@@ -944,24 +1012,30 @@ install_3proxy_from_source() {
command -v tar >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_tar; exit 2; }
command -v gzip >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_gzip; exit 2; }
command -v make >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_make; exit 2; }
command -v sha256sum >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_sha256sum; exit 2; }
(command -v gcc >/dev/null 2>&1 || command -v cc >/dev/null 2>&1) || { echo WDTT_ERROR=3proxy_source_no_compiler; exit 2; }
[ -f /usr/include/openssl/evp.h ] || [ -f /usr/local/include/openssl/evp.h ] || { echo WDTT_ERROR=3proxy_source_no_openssl_headers; exit 2; }
[ -f /usr/include/pcre2.h ] || [ -f /usr/local/include/pcre2.h ] || { echo WDTT_ERROR=3proxy_source_no_pcre2_headers; exit 2; }
cd "$TMP_DIR"
curl -fsSL -o 3proxy.tar.gz https://github.com/3proxy/3proxy/archive/refs/heads/master.tar.gz || { echo WDTT_ERROR=3proxy_source_download_failed; exit 2; }
curl -fsSL --retry 2 --connect-timeout 12 --max-time 180 -o 3proxy.tar.gz "$THREEPROXY_SOURCE_URL" || { echo WDTT_ERROR=3proxy_source_download_failed; exit 2; }
ACTUAL_SOURCE_SHA256="$(sha256sum 3proxy.tar.gz | awk '{print $1}')"
[ "$ACTUAL_SOURCE_SHA256" = "$THREEPROXY_SOURCE_SHA256" ] || { echo WDTT_ERROR=3proxy_source_checksum_failed; exit 2; }
tar -xzf 3proxy.tar.gz || { echo WDTT_ERROR=3proxy_source_unpack_failed; exit 2; }
cd 3proxy-*
cd "3proxy-$THREEPROXY_VERSION"
ln -sf Makefile.Linux Makefile
make >/tmp/wdtt-3proxy-build.log 2>&1 || { echo WDTT_ERROR=3proxy_source_build_failed; tail -n 20 /tmp/wdtt-3proxy-build.log; exit 2; }
BUILT_BIN="$(find . -type f -name 3proxy -perm -111 | head -n1)"
[ -n "$BUILT_BIN" ] || { echo WDTT_ERROR=3proxy_source_binary_missing; exit 2; }
install -m 755 "$BUILT_BIN" /usr/local/bin/3proxy || { echo WDTT_ERROR=3proxy_source_install_failed; exit 2; }
printf '%%s\n' "$THREEPROXY_VERSION" >/etc/wdtt/3proxy-version
chmod 600 /etc/wdtt/3proxy-version
}
command -v systemctl >/dev/null 2>&1 || { echo WDTT_ERROR=systemd_required; exit 2; }
install_pkg curl ca-certificates || true
install_pkg 3proxy || true
THREEPROXY_BIN="$(command -v 3proxy || true)"
if [ -z "$THREEPROXY_BIN" ]; then
install_3proxy_from_source || true
INSTALLED_THREEPROXY_VERSION="$(cat /etc/wdtt/3proxy-version 2>/dev/null || true)"
if [ -z "$THREEPROXY_BIN" ] || [ "$INSTALLED_THREEPROXY_VERSION" != "$THREEPROXY_VERSION" ]; then
install_3proxy_from_source
THREEPROXY_BIN="$(command -v 3proxy || true)"
fi
[ -n "$THREEPROXY_BIN" ] || { echo WDTT_ERROR=3proxy_install_failed; exit 2; }
@@ -979,6 +1053,26 @@ proxy -p$HTTP_PORT -i0.0.0.0 -e0.0.0.0
admin -p$ADMIN_PORT -i0.0.0.0
EOF
chmod 600 /etc/wdtt/3proxy.cfg
mkdir -p /usr/local/lib/wdtt
cat >/usr/local/lib/wdtt/local-proxy-firewall <<EOF
#!/bin/sh
set -eu
action="\${1:-}"
cleanup() {
if command -v iptables >/dev/null 2>&1; then
iptables -S INPUT 2>/dev/null | grep 'WDTT_LOCAL_PROXY' | sed 's/^-A /iptables -D /' |
while read -r cmd; do \$cmd 2>/dev/null || true; done
fi
}
if [ "\$action" = down ]; then cleanup; exit 0; fi
[ "\$action" = up ] || exit 2
command -v iptables >/dev/null 2>&1 || exit 0
cleanup
iptables -I INPUT -p tcp --dport $PROXY_PORT -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT
iptables -I INPUT -p tcp --dport $HTTP_PORT -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT
iptables -I INPUT -p tcp --dport $ADMIN_PORT -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT
EOF
chmod 700 /usr/local/lib/wdtt/local-proxy-firewall
cat >/etc/systemd/system/wdtt-3proxy.service <<EOF
[Unit]
Description=WDTT Plus authenticated proxy
@@ -988,6 +1082,8 @@ Wants=network-online.target
[Service]
Type=forking
ExecStart=$THREEPROXY_BIN /etc/wdtt/3proxy.cfg
ExecStartPost=/usr/local/lib/wdtt/local-proxy-firewall up
ExecStopPost=/usr/local/lib/wdtt/local-proxy-firewall down
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
@@ -995,13 +1091,16 @@ Restart=on-failure
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now wdtt-3proxy >/dev/null
systemctl is-active --quiet wdtt-3proxy || { echo WDTT_ERROR=local_proxy_service_inactive; exit 3; }
if command -v iptables >/dev/null 2>&1; then
iptables -C INPUT -p tcp --dport "$PROXY_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "$PROXY_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT
iptables -C INPUT -p tcp --dport "$HTTP_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "$HTTP_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT
iptables -C INPUT -p tcp --dport "$ADMIN_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "$ADMIN_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT
if ! systemctl enable wdtt-3proxy >/dev/null ||
! systemctl restart wdtt-3proxy >/dev/null ||
! systemctl is-active --quiet wdtt-3proxy; then
systemctl stop wdtt-3proxy 2>/dev/null || true
echo WDTT_ERROR=local_proxy_service_inactive
exit 3
fi
/usr/local/lib/wdtt/local-proxy-firewall up || { echo WDTT_ERROR=local_proxy_firewall_failed; systemctl stop wdtt-3proxy 2>/dev/null || true; exit 3; }
TEST_IP="$(curl --proxy-user "$PROXY_LOGIN:$PROXY_PASSWORD" --socks5-hostname "127.0.0.1:$PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)"
[ -n "$TEST_IP" ] || { systemctl stop wdtt-3proxy 2>/dev/null || true; echo WDTT_ERROR=local_proxy_check_failed; exit 3; }
SERVER_IP="$(curl -4fsS --max-time 8 https://api.ipify.org 2>/dev/null || hostname -I | awk '{print $1}')"
cat >/etc/wdtt/local-proxy.json <<EOF
{
@@ -1017,11 +1116,11 @@ cat >/etc/wdtt/local-proxy.json <<EOF
EOF
chmod 600 /etc/wdtt/local-proxy.json
echo "Прокси на этом сервере включён и проверен."
echo "SOCKS5: socks5://$PROXY_LOGIN:$PROXY_PASSWORD@$SERVER_IP:$PROXY_PORT"
echo "HTTP: http://$PROXY_LOGIN:$PROXY_PASSWORD@$SERVER_IP:$HTTP_PORT"
echo "SOCKS5: socks5://$PROXY_LOGIN:********@$SERVER_IP:$PROXY_PORT"
echo "HTTP: http://$PROXY_LOGIN:********@$SERVER_IP:$HTTP_PORT"
echo "Веб-страница 3proxy: http://$SERVER_IP:$ADMIN_PORT/"
echo "Логин и пароль одинаковые для SOCKS5, HTTP и веб-страницы 3proxy."
`, outboundBotPrelude(), port, httpPort, adminPort, botShellQuote(login), botShellQuote(password))
echo "Логин и пароль одинаковые для SOCKS5, HTTP и веб-страницы 3proxy. Чтобы загрузить сохранённый пароль, используйте в Android-приложении «Деплой → Выходной IP и прокси → Загрузить настройки»."
`, outboundBotPrelude(), port, httpPort, adminPort, botShellQuote(login), botShellQuote(password), botShellQuote(botThreeProxyVersion), botShellQuote(botThreeProxySourceURL), botShellQuote(botThreeProxySourceSHA256))
}
func localProxyCheckScript() string {
@@ -1035,7 +1134,7 @@ command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; exit 2;
if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files wdtt-3proxy.service >/dev/null 2>&1; then
systemctl is-active --quiet wdtt-3proxy || { echo WDTT_ERROR=local_proxy_service_inactive; exit 3; }
fi
IP="$(curl --socks5-hostname "$PROXY_LOGIN:$PROXY_PASSWORD@127.0.0.1:$PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)"
IP="$(curl --proxy-user "$PROXY_LOGIN:$PROXY_PASSWORD" --socks5-hostname "127.0.0.1:$PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)"
[ -n "$IP" ] || { echo WDTT_ERROR=local_proxy_check_failed; exit 3; }
echo "Проверка успешна: SOCKS5 на 127.0.0.1:$PROXY_PORT отвечает с сохранёнными логином и паролем. Выходной IP: $IP"
`
@@ -1054,7 +1153,7 @@ echo "Прокси на этом сервере остановлен. Настр
}
return `
systemctl disable --now wdtt-3proxy 2>/dev/null || true
rm -f /etc/systemd/system/wdtt-3proxy.service /etc/wdtt/3proxy.cfg /etc/wdtt/local-proxy.json
rm -f /etc/systemd/system/wdtt-3proxy.service /etc/wdtt/3proxy.cfg /etc/wdtt/local-proxy.json /usr/local/lib/wdtt/local-proxy-firewall
systemctl daemon-reload 2>/dev/null || true
if command -v iptables >/dev/null 2>&1; then
iptables -S INPUT 2>/dev/null | grep WDTT_LOCAL_PROXY | sed 's/^-A /iptables -D /' | while read -r cmd; do $cmd 2>/dev/null || true; done
@@ -1106,7 +1205,27 @@ func parseExternalProxyInput(input string) (kind, host string, port int, login,
err = errors.New("если прокси с авторизацией, укажите и логин, и пароль; если без авторизации — используйте `- -`")
return
}
if len(login) > 80 || len(password) > 120 {
err = errors.New("логин должен быть не длиннее 80 символов, пароль — не длиннее 120")
return
}
if strings.Contains(login, ":") {
err = errors.New("логин внешнего прокси не должен содержать двоеточие")
return
}
if strings.ContainsAny(login+password, `\"`) {
err = errors.New("в логине и пароле через бот нельзя использовать кавычку или обратную косую черту; задайте такие данные из приложения")
return
}
if strings.IndexFunc(login+password, func(r rune) bool { return r < 32 || r == 127 }) >= 0 {
err = errors.New("логин или пароль содержит недопустимые управляющие символы")
return
}
return
}
func escapeRedsocksValue(value string) string {
return strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(value)
}
func proxyKindLabel(kind string) string {
@@ -1125,18 +1244,20 @@ func externalProxyCheckScript(kind, host string, port int, login, password strin
if kind == "socks5" {
scheme = "socks5h"
}
auth := ""
if login != "" {
auth = login + ":" + password + "@"
}
proxyURI := fmt.Sprintf("%s://%s%s:%d", scheme, auth, host, port)
proxyURI := fmt.Sprintf("%s://%s:%d", scheme, host, port)
return fmt.Sprintf(`
command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; exit 2; }
PROXY_URI=%s
IP="$(curl --proxy "$PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)"
PROXY_LOGIN=%s
PROXY_PASSWORD=%s
if [ -n "$PROXY_LOGIN" ]; then
IP="$(curl --proxy "$PROXY_URI" --proxy-user "$PROXY_LOGIN:$PROXY_PASSWORD" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)"
else
IP="$(curl --proxy "$PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)"
fi
[ -n "$IP" ] || { echo WDTT_ERROR=external_proxy_check_failed; exit 3; }
echo "Проверка успешна: %s отвечает, сервер смог открыть проверочный сайт через него. IP через прокси: $IP"
`, botShellQuote(proxyURI), proxyKindLabel(kind))
`, botShellQuote(proxyURI), botShellQuote(login), botShellQuote(password), proxyKindLabel(kind))
}
func externalProxyEnableScript(kind, host string, port int, login, password string) string {
@@ -1151,6 +1272,8 @@ PROXY_HOST=%s
PROXY_PORT=%d
PROXY_LOGIN=%s
PROXY_PASSWORD=%s
PROXY_LOGIN_CONFIG=%s
PROXY_PASSWORD_CONFIG=%s
wdtt_install_redsocks_tools || true
REDSOCKS_BIN="$(command -v redsocks || true)"
[ -n "$REDSOCKS_BIN" ] || { echo WDTT_ERROR=redsocks_not_installed; exit 2; }
@@ -1175,22 +1298,48 @@ redsocks {
type = $REDSOCKS_TYPE;
EOF
if [ -n "$PROXY_LOGIN" ]; then
printf ' login = "%%s";\n' "$PROXY_LOGIN" >>/etc/wdtt/redsocks.conf
printf ' password = "%%s";\n' "$PROXY_PASSWORD" >>/etc/wdtt/redsocks.conf
printf ' login = "%%s";\n' "$PROXY_LOGIN_CONFIG" >>/etc/wdtt/redsocks.conf
printf ' password = "%%s";\n' "$PROXY_PASSWORD_CONFIG" >>/etc/wdtt/redsocks.conf
fi
cat >>/etc/wdtt/redsocks.conf <<EOF
}
EOF
chmod 600 /etc/wdtt/redsocks.conf
mkdir -p /usr/local/lib/wdtt
cat >/usr/local/lib/wdtt/redsocks-routes <<EOF
#!/bin/sh
set -eu
action="\${1:-}"
WDTT_IFACE=wdtt0
PROXY_IP=$PROXY_IP
cleanup() {
while iptables -t nat -D PREROUTING -i "\$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null; do :; done
iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true
iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true
}
if [ "\$action" = down ]; then cleanup; exit 0; fi
[ "\$action" = up ] || exit 2
cleanup
iptables -t nat -N WDTT_PROXY_OUT
for net in 0.0.0.0/8 10.0.0.0/8 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 224.0.0.0/4 240.0.0.0/4; do
iptables -t nat -A WDTT_PROXY_OUT -d "\$net" -j RETURN
done
[ -n "\$PROXY_IP" ] && iptables -t nat -A WDTT_PROXY_OUT -d "\$PROXY_IP" -j RETURN
iptables -t nat -A WDTT_PROXY_OUT -p tcp -j REDIRECT --to-ports 12345
iptables -t nat -A PREROUTING -i "\$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT
EOF
chmod 700 /usr/local/lib/wdtt/redsocks-routes
cat >/etc/systemd/system/wdtt-redsocks.service <<EOF
[Unit]
Description=WDTT Plus external proxy redirector
After=network-online.target
After=network-online.target wdtt.service
Wants=network-online.target
[Service]
Type=forking
ExecStart=$REDSOCKS_BIN -c /etc/wdtt/redsocks.conf -p /run/wdtt-redsocks.pid
ExecStartPost=/usr/local/lib/wdtt/redsocks-routes up
ExecStopPost=/usr/local/lib/wdtt/redsocks-routes down
PIDFile=/run/wdtt-redsocks.pid
Restart=on-failure
@@ -1198,13 +1347,16 @@ Restart=on-failure
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now wdtt-redsocks >/dev/null
systemctl is-active --quiet wdtt-redsocks || { echo WDTT_ERROR=external_proxy_service_inactive; journalctl -u wdtt-redsocks -n 30 --no-pager 2>/dev/null || true; exit 3; }
iptables -t nat -N WDTT_PROXY_OUT 2>/dev/null || true
iptables -t nat -F WDTT_PROXY_OUT
wdtt_proxy_reserved_returns WDTT_PROXY_OUT "$PROXY_IP"
iptables -t nat -A WDTT_PROXY_OUT -p tcp -j REDIRECT --to-ports 12345
iptables -t nat -C PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null || iptables -t nat -A PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT
if ! systemctl enable wdtt-redsocks >/dev/null ||
! systemctl restart wdtt-redsocks >/dev/null ||
! systemctl is-active --quiet wdtt-redsocks; then
journalctl -u wdtt-redsocks -n 30 --no-pager 2>/dev/null || true
wdtt_clear_external_out
wdtt_write_mode "direct" "rollback after external proxy service error"
echo WDTT_ERROR=external_proxy_service_inactive
exit 3
fi
/usr/local/lib/wdtt/redsocks-routes up || { echo WDTT_ERROR=external_proxy_route_install_failed; wdtt_clear_external_out; exit 3; }
if ! wdtt_test_redsocks_path "$PROXY_IP"; then
wdtt_clear_external_out
wdtt_write_mode "direct" "rollback after external proxy error"
@@ -1213,7 +1365,7 @@ fi
wdtt_write_mode "external_proxy" "$PROXY_KIND://$PROXY_HOST:$PROXY_PORT"
echo "Внешний прокси включён для обычных TCP-подключений WDTT-пользователей. Голосовой UDP-трафик через него не перенаправляется."
echo "Прокси: $PROXY_KIND://$PROXY_HOST:$PROXY_PORT"
`, outboundBotPrelude(), botShellQuote(kind), botShellQuote(redsocksType), botShellQuote(host), port, botShellQuote(login), botShellQuote(password))
`, outboundBotPrelude(), botShellQuote(kind), botShellQuote(redsocksType), botShellQuote(host), port, botShellQuote(login), botShellQuote(password), botShellQuote(escapeRedsocksValue(login)), botShellQuote(escapeRedsocksValue(password)))
}
func sendFreeWarpMenu(token string, adminID int64, messageID int) int {
@@ -2108,7 +2260,7 @@ func showEditExpiryMenu(token string, adminID int64, messageID int, pass string)
)
}
func startNewPasswordFlow(token string, adminID int64, wgDev *device.Device, waitingForDays *bool, messageID int) int {
func startNewPasswordFlow(token string, adminID int64, wgDev wgDevice, waitingForDays *bool, messageID int) int {
dbMutex.Lock()
if cleanupExpiredPasswordsLocked(wgDev) > 0 {
saveDB()
@@ -2125,7 +2277,7 @@ func startNewPasswordFlow(token string, adminID int64, wgDev *device.Device, wai
return showNewPasswordDaysMenu(token, adminID, messageID)
}
func botLoop(token string, adminIDstr string, wgDev *device.Device) {
func botLoop(token string, adminIDstr string, wgDev wgDevice) {
if token == "" || adminIDstr == "" {
return
}
@@ -2578,9 +2730,9 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
entry, exists := db.Passwords[pass]
if exists && entry != nil {
if days == 0 {
entry.ExpiresAt = 0
setPasswordExpiryPreservingRetention(entry, 0)
} else {
entry.ExpiresAt = time.Now().Add(time.Duration(days) * 24 * time.Hour).Unix()
setPasswordExpiryPreservingRetention(entry, time.Now().Add(time.Duration(days)*24*time.Hour).Unix())
}
saveDB()
}
@@ -2787,7 +2939,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
} else if data == "out_local_install" {
login := "wdtt" + strings.ToLower(generatePassword()[:8])
password := generatePassword()
promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "🧦 Создаю или обновляю SOCKS5/HTTP-прокси на этом сервере. Если пакета 3proxy нет, попробую собрать его из исходников...", nil)
promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "🧦 Создаю или обновляю SOCKS5/HTTP-прокси на этом сервере из проверенного выпуска 3proxy...", nil)
out, err := runBotScript(localProxyInstallScript(login, password, 1080), 5*time.Minute)
promptMessageID = sendBotScriptResult(token, adminID, promptMessageID, "Прокси на сервере готов", out, err, "out_local")
} else if data == "out_local_check" {
@@ -3449,9 +3601,9 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
continue
}
if days == 0 {
entry.ExpiresAt = 0
setPasswordExpiryPreservingRetention(entry, 0)
} else {
entry.ExpiresAt = time.Now().Add(time.Duration(days) * 24 * time.Hour).Unix()
setPasswordExpiryPreservingRetention(entry, time.Now().Add(time.Duration(days)*24*time.Hour).Unix())
}
saveDB()
dbMutex.Unlock()
@@ -3581,7 +3733,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
}
}
func sendPasswordList(token string, adminID int64, wgDev *device.Device, messageID int) int {
func sendPasswordList(token string, adminID int64, wgDev wgDevice, messageID int) int {
dbMutex.Lock()
defer dbMutex.Unlock()
+110
View File
@@ -0,0 +1,110 @@
package main
import (
"os"
"os/exec"
"strings"
"testing"
)
func TestExternalProxyTransparentCheckDoesNotCaptureRootXrayTraffic(t *testing.T) {
script := outboundBotPrelude()
for _, expected := range []string{
`WDTT_PROXY_TEST_SOURCE="$test_source"`,
`iptables -t nat -I OUTPUT -s "$test_source" -p tcp -j WDTT_PROXY_TEST`,
`curl --interface "$test_source"`,
} {
if !strings.Contains(script, expected) {
t.Fatalf("outbound script does not contain %q", expected)
}
}
legacyInsertion := `iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST`
if strings.Contains(script, legacyInsertion) {
t.Fatalf("outbound script still captures every root TCP connection")
}
}
func TestOutboundBotScriptsHaveValidBashSyntax(t *testing.T) {
scripts := map[string]string{
"local proxy install": localProxyInstallScript("wdttuser", "safePassword123", 1080),
"local proxy check": localProxyCheckScript(),
"external proxy": externalProxyEnableScript("socks5", "proxy.example.com", 1080, "user", "password"),
"direct exit": outboundDisableScript(),
"status": outboundStatusScript(),
}
for name, script := range scripts {
t.Run(name, func(t *testing.T) {
assertBashSyntax(t, script)
})
}
}
func TestLocalProxyUsesPinnedVerifiedReleaseAndPersistentFirewall(t *testing.T) {
script := localProxyInstallScript("wdttuser", "safePassword123", 1080)
for _, expected := range []string{
`THREEPROXY_VERSION='0.9.7'`,
botThreeProxySourceSHA256,
"sha256sum 3proxy.tar.gz",
"local-proxy-firewall",
"ExecStartPost=/usr/local/lib/wdtt/local-proxy-firewall up",
`--proxy-user "$PROXY_LOGIN:$PROXY_PASSWORD"`,
} {
if !strings.Contains(script, expected) {
t.Fatalf("local proxy script does not contain %q", expected)
}
}
if strings.Contains(script, "master.tar.gz") {
t.Fatal("local proxy script still downloads mutable master.tar.gz")
}
if strings.Contains(script, `echo "SOCKS5: socks5://$PROXY_LOGIN:$PROXY_PASSWORD@`) {
t.Fatal("local proxy result exposes the generated password")
}
}
func TestExternalProxyUsesPersistentRoutesAndSeparateCredentials(t *testing.T) {
script := externalProxyEnableScript("socks5", "proxy.example.com", 1080, "user", "password")
for _, expected := range []string{
"redsocks-routes",
"ExecStartPost=/usr/local/lib/wdtt/redsocks-routes up",
"ExecStopPost=/usr/local/lib/wdtt/redsocks-routes down",
"WDTT_ERROR=external_proxy_route_install_failed",
} {
if !strings.Contains(script, expected) {
t.Fatalf("external proxy script does not contain %q", expected)
}
}
}
func TestExternalProxyInputRejectsAmbiguousCredentials(t *testing.T) {
if _, _, _, _, _, err := parseExternalProxyInput("socks5 proxy.example.com 1080 user:name password"); err == nil {
t.Fatal("login with colon must be rejected")
}
if _, _, _, _, _, err := parseExternalProxyInput(`socks5 proxy.example.com 1080 user pass\"word`); err == nil {
t.Fatal("credentials requiring config escaping must be entered from the app")
}
}
func assertBashSyntax(t *testing.T, script string) {
t.Helper()
file, err := os.CreateTemp("", "wdtt-outbound-*.sh")
if err != nil {
t.Fatal(err)
}
name := file.Name()
defer os.Remove(name)
if _, err := file.WriteString(script); err != nil {
file.Close()
t.Fatal(err)
}
if err := file.Close(); err != nil {
t.Fatal(err)
}
output, err := exec.Command("bash", "-n", name).CombinedOutput()
if err != nil {
t.Fatalf("bash -n failed: %v\n%s", err, output)
}
}
-17
View File
@@ -1,17 +0,0 @@
# WDTT Plus icon pack
Основная иконка — готовый PNG-арт, не VectorDrawable.
## Файлы
- `docs/icon-sources/wdtt_plus_icon.png` — исходник.
- `app/src/main/res/mipmap-*/ic_launcher.png` — legacy launcher.
- `app/src/main/res/mipmap-*/ic_launcher_round.png` — legacy round.
- `app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml` — adaptive icon.
- `app/src/main/res/drawable/ic_launcher_foreground.png` — PNG foreground.
- `app/src/main/res/drawable/ic_launcher_background.png` — dark background.
- `app/src/main/res/drawable/ic_launcher_monochrome.xml` — Android 13 themed icon.
- `app/src/main/res/drawable/ic_notification_icon.xml` — status bar notification icon.
- `app/src/main/res/drawable/ic_tile_logo.xml` — Quick Settings tile icon.
Полную 3D-иконку не перерисовывать через XML/SVG. VectorDrawable используется только для monochrome/notification/tile.
-78
View File
@@ -1,78 +0,0 @@
# Выходной IP и прокси
Модуль на вкладке **«Деплой»** управляет выходом только для WDTT-пользователей. Он не должен менять глобальный `default route` основного сервера: SSH, системные обновления, Docker, Telegram-бот и сам транспорт WDTT продолжают идти обычным маршрутом сервера.
## Общий принцип
WDTT-сервер поднимает клиентскую сеть `10.66.66.0/24` на интерфейсе `wdtt0`. Внешние режимы применяются только к этой подсети:
- внешний SOCKS5/HTTP использует `redsocks` и цепочку `WDTT_PROXY_OUT` в `iptables` только для `-i wdtt0`;
- WireGuard exit использует интерфейс `wg-wdtt-exit`, отдельную routing table `100` и `ip rule from 10.66.66.0/24 table 100`;
- возврат в direct очищает только правила WDTT Plus и не трогает остальные правила сервера.
Одновременно активен один внешний выход: `direct`, `external_proxy`, `wireguard_vps` или `imported_wg`.
## 1. Прокси на этом VPS
Кнопка **«Прокси на этом VPS»** ставит `3proxy`, создаёт `wdtt-3proxy.service` и включает SOCKS5/HTTP-прокси с логином и паролем. Это прокси для администратора или внешних клиентов, оно не меняет маршрут WDTT-пользователей само по себе.
Важно:
- open proxy не создаётся, авторизация обязательна;
- SOCKS5-порт задаётся в окне, HTTP-порт создаётся как `SOCKS5 + 1`;
- пароль не пишется в обычный Android-лог, в результате показывается URI с замаскированным паролем.
Проверка выполняется через:
```bash
curl --socks5-hostname LOGIN:PASSWORD@127.0.0.1:PORT https://api.ipify.org
```
## 2. Внешний SOCKS5/HTTP-прокси
Кнопка **«Внешний SOCKS5/HTTP»** ставит `redsocks`, поднимает редиректор на `0.0.0.0:12345` и перенаправляет TCP-трафик WDTT-пользователей через внешний прокси.
Ограничения:
- режим рассчитан в основном на TCP;
- UDP может не поддерживаться;
- качество, страна и репутация IP зависят от внешнего прокси;
- private/local ranges исключены из перенаправления.
Если ICMP-пинги проходят, а сайты не открываются, проверьте диагностику: для трафика из `PREROUTING` редиректор не должен слушать только `127.0.0.1:12345`.
Этот режим не меняет default route VPS.
## 3. Зарубежный VPS через WireGuard
Кнопка **«WG exit VPS»** подключается по SSH к foreign VPS, ставит WireGuard, создаёт туннель `wg-wdtt-exit` между текущим WDTT-сервером и foreign VPS, включает NAT на foreign VPS и policy routing на текущем сервере.
Это рекомендуемый полноценный режим для смены выходного IP WDTT-пользователей, потому что WireGuard переносит не только TCP.
## 4. Импорт WireGuard config
Кнопка **«Импорт WG config»** принимает готовый `.conf` файлом или текстом. Конфиг проверяется на обязательные поля:
- `[Interface] PrivateKey`
- `[Interface] Address`
- `[Peer] PublicKey`
- `[Peer] Endpoint`
- `[Peer] AllowedIPs`
`PreUp`, `PostUp`, `PreDown`, `PostDown` запрещены при импорте, чтобы чужой конфиг не мог поменять маршруты всего VPS. WDTT Plus добавляет `Table = off`, поднимает `wg-wdtt-exit` и маршрутизирует через него только WDTT-подсеть.
`AllowedIPs = 0.0.0.0/0` нормально для exit-node: благодаря `Table = off` и отдельному `ip rule` это не становится default route всего сервера.
## Диагностика и rollback
Кнопки **«Статус»** и **«Диагностика»** показывают:
- текущий outbound mode;
- WDTT client subnet;
- внешний IP самого сервера;
- состояние `3proxy`, `redsocks`, `wg-wdtt-exit`;
- `ip rule`;
- routing table `100`;
- WDTT-цепочки `iptables`.
Кнопка **«Вернуть direct»** останавливает `redsocks`, опускает `wg-wdtt-exit`, чистит policy routing и возвращает прямой выход через текущий VPS.
+129 -80
View File
@@ -9,7 +9,6 @@ import (
"io"
"log"
"math/rand"
"net"
neturl "net/url"
"strings"
"sync"
@@ -29,11 +28,25 @@ type VKCredentials struct {
ClientSecret string
}
type legacyVKCredentialProvider string
const (
legacyVKProviderCustom legacyVKCredentialProvider = "legacy-custom"
legacyVKProviderBuiltIn legacyVKCredentialProvider = "legacy-built-in"
)
type legacyVKCredentialCandidate struct {
Credentials VKCredentials
Provider legacyVKCredentialProvider
}
var vkCredentialsList = []VKCredentials{
{ClientID: "6287487", ClientSecret: "MuAxFaKDYDOICzGnEOhp"},
{ClientID: "8202606", ClientSecret: "lMRsTiMCyPnp5vfoldmn"},
}
var customVKCredentials *VKCredentials
// Full list of known credentials to match against when setting active client IDs
var knownVKCredentials = map[string]VKCredentials{
"6287487": {ClientID: "6287487", ClientSecret: "MuAxFaKDYDOICzGnEOhp"},
@@ -56,6 +69,44 @@ func SetActiveClientIds(ids string) {
}
}
func SetCustomVKCredentials(clientID, clientSecret string) error {
clientID = strings.TrimSpace(clientID)
if clientID == "" || len(clientID) > 20 {
return errors.New("client ID must contain 1 to 20 digits")
}
for _, char := range clientID {
if char < '0' || char > '9' {
return errors.New("client ID must contain digits only")
}
}
if strings.TrimSpace(clientSecret) == "" {
return errors.New("client secret is empty")
}
credentials := VKCredentials{
ClientID: clientID,
ClientSecret: clientSecret,
}
customVKCredentials = &credentials
return nil
}
func legacyVKCredentialCandidates() []legacyVKCredentialCandidate {
result := make([]legacyVKCredentialCandidate, 0, len(vkCredentialsList)+1)
if customVKCredentials != nil {
result = append(result, legacyVKCredentialCandidate{
Credentials: *customVKCredentials,
Provider: legacyVKProviderCustom,
})
}
for _, credentials := range vkCredentialsList {
result = append(result, legacyVKCredentialCandidate{
Credentials: credentials,
Provider: legacyVKProviderBuiltIn,
})
}
return result
}
func GetActiveClientIdsString() string {
var ids []string
for _, cred := range vkCredentialsList {
@@ -82,6 +133,14 @@ type TurnCredentials struct {
Link string
}
type fetchedTurnCredentials struct {
Username string
Password string
ServerAddrs []string
Lifetime time.Duration
Provider string
}
type StreamCredentialsCache struct {
creds TurnCredentials
mutex sync.RWMutex
@@ -96,6 +155,20 @@ const (
errorWindow = 10 * time.Second
)
func credentialCacheLifetime(reported time.Duration) time.Duration {
if reported <= 0 {
return credentialLifetime - cacheSafetyMargin
}
if reported > 24*time.Hour {
reported = 24 * time.Hour
}
margin := cacheSafetyMargin
if reported <= 2*cacheSafetyMargin {
margin = reported / 5
}
return reported - margin
}
var streamsPerCache = 10
func getCacheID(streamID int) int {
@@ -325,19 +398,21 @@ func getVkCredsCached(ctx context.Context, link string, streamID int) (string, s
return cache.creds.Username, cache.creds.Password, cloneStringSlice(cache.creds.ServerAddrs), nil
}
user, pass, addrs, err := fetchVkCredsSerialized(ctx, link, streamID)
fetched, err := fetchVkCredsSerialized(ctx, link, streamID)
if err != nil {
return "", "", nil, err
}
cacheLifetime := credentialCacheLifetime(fetched.Lifetime)
cache.creds = TurnCredentials{
Username: user,
Password: pass,
ServerAddrs: addrs,
ExpiresAt: time.Now().Add(credentialLifetime - cacheSafetyMargin),
Username: fetched.Username,
Password: fetched.Password,
ServerAddrs: fetched.ServerAddrs,
ExpiresAt: time.Now().Add(cacheLifetime),
Link: link,
}
return user, pass, cloneStringSlice(addrs), nil
log.Printf("[STREAM %d] [VK Provider] %s: TURN-данные сохранены на %v", streamID, fetched.Provider, cacheLifetime.Truncate(time.Second))
return fetched.Username, fetched.Password, cloneStringSlice(fetched.ServerAddrs), nil
}
// ─── Serialized (throttled) fetcher ───
@@ -347,7 +422,7 @@ var (
globalLastVkFetchTime time.Time
)
func fetchVkCredsSerialized(ctx context.Context, link string, streamID int) (string, string, []string, error) {
func fetchVkCredsSerialized(ctx context.Context, link string, streamID int) (fetchedTurnCredentials, error) {
vkRequestMu.Lock()
defer vkRequestMu.Unlock()
@@ -360,7 +435,7 @@ func fetchVkCredsSerialized(ctx context.Context, link string, streamID int) (str
log.Printf("[STREAM %d] [VK Auth] Throttling: waiting %v to prevent rate limit...", streamID, wait.Truncate(time.Millisecond))
select {
case <-ctx.Done():
return "", "", nil, ctx.Err()
return fetchedTurnCredentials{}, ctx.Err()
case <-time.After(wait):
}
}
@@ -374,67 +449,89 @@ func fetchVkCredsSerialized(ctx context.Context, link string, streamID int) (str
// ─── Main credential fetcher (rotates through stable credential sets) ───
func fetchVkCreds(ctx context.Context, link string, streamID int) (string, string, []string, error) {
func fetchVkCreds(ctx context.Context, link string, streamID int) (fetchedTurnCredentials, error) {
if vkCallsPreflightEnabled.Load() {
if pause := vkCallsFloodPauseRemaining(time.Now()); pause > 0 {
log.Printf("[STREAM %d] [VKCalls] preflight временно пропущен после ограничения VK (%v); продолжаем captcha-цепочку", streamID, pause.Truncate(time.Second))
log.Printf("[STREAM %d] [VKCalls] preflight временно пропущен после ограничения VK (%v); продолжаем резервную legacy-цепочку", streamID, pause.Truncate(time.Second))
} else {
log.Printf("[STREAM %d] [VKCalls] preflight", streamID)
if user, pass, addrs, err := getVKCredsViaVKCalls(ctx, link, streamID); err == nil {
return user, pass, addrs, nil
if user, pass, addrs, lifetime, err := getVKCredsViaVKCalls(ctx, link, streamID); err == nil {
log.Printf("[STREAM %d] [VK Provider] modern-vkcalls: успешно", streamID)
return fetchedTurnCredentials{
Username: user,
Password: pass,
ServerAddrs: addrs,
Lifetime: lifetime,
Provider: "modern-vkcalls",
}, nil
} else if isVKCallsFloodError(err) {
startVKCallsFloodPause(time.Now())
log.Printf("[STREAM %d] [VKCalls] VK временно ограничил анонимный вход; продолжаем captcha-цепочку", streamID)
log.Printf("[STREAM %d] [VKCalls] VK временно ограничил анонимный вход; продолжаем резервную legacy-цепочку", streamID)
} else {
log.Printf("[STREAM %d] [VKCalls] preflight не сработал: %v; продолжаем captcha-цепочку", streamID, err)
log.Printf("[STREAM %d] [VKCalls] preflight не сработал: %v; продолжаем резервную legacy-цепочку", streamID, err)
}
}
}
if time.Now().Unix() < globalCaptchaLockout.Load() {
return "", "", nil, fmt.Errorf("CAPTCHA_WAIT_REQUIRED: global lockout active")
return fetchedTurnCredentials{}, fmt.Errorf("CAPTCHA_WAIT_REQUIRED: global lockout active")
}
candidates := legacyVKCredentialCandidates()
if len(candidates) == 0 {
return fetchedTurnCredentials{}, errors.New("no legacy VK credentials configured")
}
attemptLimit := vkCredentialAttemptLimit
if len(candidates) > attemptLimit {
attemptLimit = len(candidates)
}
var lastErr error
jar := tlsclient.NewCookieJar()
for attempt := 0; attempt < vkCredentialAttemptLimit; attempt++ {
creds := vkCredentialsList[attempt%len(vkCredentialsList)]
log.Printf("[STREAM %d] [VK Auth] Trying credentials: client_id=%s (attempt %d/%d)", streamID, creds.ClientID, attempt+1, vkCredentialAttemptLimit)
for attempt := 0; attempt < attemptLimit; attempt++ {
candidate := candidates[attempt%len(candidates)]
creds := candidate.Credentials
provider := string(candidate.Provider)
log.Printf("[STREAM %d] [VK Provider] %s: пробуем client_id=%s (попытка %d/%d)", streamID, provider, creds.ClientID, attempt+1, attemptLimit)
user, pass, addrs, err := getTokenChain(ctx, link, streamID, creds, jar)
if err == nil {
log.Printf("[STREAM %d] [VK Auth] Success with client_id=%s", streamID, creds.ClientID)
return user, pass, addrs, nil
log.Printf("[STREAM %d] [VK Provider] %s: успешно", streamID, provider)
return fetchedTurnCredentials{
Username: user,
Password: pass,
ServerAddrs: addrs,
Provider: provider,
}, nil
}
lastErr = err
log.Printf("[STREAM %d] [VK Auth] Failed with client_id=%s: %v", streamID, creds.ClientID, err)
log.Printf("[STREAM %d] [VK Provider] %s: client_id=%s не сработал: %v", streamID, provider, creds.ClientID, err)
if strings.Contains(err.Error(), "CAPTCHA_WAIT_REQUIRED") || strings.Contains(err.Error(), "FATAL_CAPTCHA") {
return "", "", nil, err
return fetchedTurnCredentials{}, err
}
if strings.Contains(err.Error(), "INVALID_JOIN_LINK") || strings.Contains(err.Error(), "ANON_BLOCKED") || strings.Contains(err.Error(), "CALL_FULL") {
return "", "", nil, err
return fetchedTurnCredentials{}, err
}
if strings.Contains(err.Error(), "error_code:29") || strings.Contains(err.Error(), "error_code: 29") || strings.Contains(err.Error(), "Rate limit") {
log.Printf("[STREAM %d] [VK Auth] Rate limit detected, trying next credentials...", streamID)
}
if attempt%len(vkCredentialsList) == len(vkCredentialsList)-1 && attempt+1 < vkCredentialAttemptLimit {
if attempt%len(candidates) == len(candidates)-1 && attempt+1 < attemptLimit {
wait := time.Duration(900+rand.Intn(900)) * time.Millisecond
log.Printf("[STREAM %d] [VK Auth] Both VK credentials failed, retrying stable pair after %v...", streamID, wait)
log.Printf("[STREAM %d] [VK Auth] Все legacy-провайдеры временно не сработали, повтор через %v...", streamID, wait)
select {
case <-ctx.Done():
return "", "", nil, ctx.Err()
return fetchedTurnCredentials{}, ctx.Err()
case <-time.After(wait):
}
}
}
return "", "", nil, fmt.Errorf("all VK credentials failed: %w", lastErr)
return fetchedTurnCredentials{}, fmt.Errorf("all VK credential providers failed: %w", lastErr)
}
// ─── Token chain: anon_token → getCallPreview → getAnonymousToken → OK session → joinConversation → TURN creds ───
@@ -485,7 +582,7 @@ func getTokenChain(ctx context.Context, link string, streamID int, creds VKCrede
httpResp, err := client.Do(req)
if err != nil {
return nil, err
return nil, fmt.Errorf("VK HTTPS %s: %w", domain, err)
}
defer func() {
if closeErr := httpResp.Body.Close(); closeErr != nil {
@@ -680,9 +777,9 @@ func getTokenChain(ctx context.Context, link string, streamID int, creds VKCrede
if !ok {
continue
}
clean := strings.Split(urlStr, "?")[0]
address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
addresses = append(addresses, address)
if normalized := normalizeTURNURL(urlStr); normalized != "" {
addresses = append(addresses, normalized)
}
}
if len(addresses) == 0 {
@@ -875,51 +972,3 @@ func requestWebViewCaptcha(ctx context.Context, streamID int, captchaErr *VkCapt
func GetCreds(ctx context.Context, link string, streamID int) (string, string, []string, error) {
return getVkCredsCached(ctx, link, streamID)
}
// ─── DNS dialer setup ───
func setupGlobalResolver() {
dialer := &net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}
yandexDNSServers := []string{"77.88.8.8:53", "77.88.8.1:53"}
net.DefaultResolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
var lastErr error
for _, dns := range yandexDNSServers {
conn, err := dialer.DialContext(ctx, "udp", dns)
if err == nil {
return conn, nil
}
lastErr = err
conn, err = dialer.DialContext(ctx, "tcp", dns)
if err == nil {
return conn, nil
}
lastErr = err
}
address = strings.TrimSpace(address)
if address != "" && !isYandexDNSAddress(address) {
conn, err := dialer.DialContext(ctx, network, address)
if err == nil {
return conn, nil
}
lastErr = err
}
return nil, lastErr
},
}
}
func isYandexDNSAddress(address string) bool {
host, _, err := net.SplitHostPort(address)
if err != nil {
host = address
}
host = strings.Trim(host, "[]")
return host == "77.88.8.8" || host == "77.88.8.1"
}
+80
View File
@@ -0,0 +1,80 @@
package main
import (
"testing"
"time"
)
func TestSetCustomVKCredentialsAddsIndependentLegacyProvider(t *testing.T) {
originalCredentials := append([]VKCredentials(nil), vkCredentialsList...)
originalCustomCredentials := customVKCredentials
defer func() {
vkCredentialsList = originalCredentials
customVKCredentials = originalCustomCredentials
}()
vkCredentialsList = []VKCredentials{
{ClientID: "6287487", ClientSecret: "built-in-one"},
{ClientID: "8202606", ClientSecret: "built-in-two"},
}
customVKCredentials = nil
if err := SetCustomVKCredentials("12345678", "test-only-secret"); err != nil {
t.Fatalf("SetCustomVKCredentials returned error: %v", err)
}
candidates := legacyVKCredentialCandidates()
if len(candidates) != 3 {
t.Fatalf("candidate count = %d, want 3", len(candidates))
}
if candidates[0].Provider != legacyVKProviderCustom || candidates[0].Credentials.ClientID != "12345678" {
t.Fatalf("first candidate = %#v, want custom credentials", candidates[0])
}
if candidates[1].Provider != legacyVKProviderBuiltIn || candidates[1].Credentials.ClientID != "6287487" {
t.Fatalf("second candidate = %#v, want first built-in credentials", candidates[1])
}
if candidates[2].Provider != legacyVKProviderBuiltIn || candidates[2].Credentials.ClientID != "8202606" {
t.Fatalf("third candidate = %#v, want second built-in credentials", candidates[2])
}
if vkCallsClientID != "8093730" {
t.Fatalf("fixed VK Calls client ID = %q", vkCallsClientID)
}
}
func TestSetCustomVKCredentialsRejectsIncompleteValues(t *testing.T) {
tests := []struct {
name string
id string
secret string
}{
{name: "empty id", secret: "test-only-secret"},
{name: "non numeric id", id: "123abc", secret: "test-only-secret"},
{name: "empty secret", id: "12345678"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if err := SetCustomVKCredentials(test.id, test.secret); err == nil {
t.Fatal("expected validation error")
}
})
}
}
func TestCredentialCacheLifetime(t *testing.T) {
tests := []struct {
name string
reported time.Duration
want time.Duration
}{
{name: "legacy fallback", want: 9 * time.Minute},
{name: "server lifetime", reported: 10 * time.Minute, want: 9 * time.Minute},
{name: "short lifetime", reported: 100 * time.Second, want: 80 * time.Second},
{name: "short safe margin", reported: 20 * time.Second, want: 16 * time.Second},
{name: "bounded", reported: 48 * time.Hour, want: 23*time.Hour + 59*time.Minute},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := credentialCacheLifetime(test.reported); got != test.want {
t.Fatalf("cache lifetime = %v, want %v", got, test.want)
}
})
}
}
+27 -1
View File
@@ -1,6 +1,9 @@
package main
import "testing"
import (
"errors"
"testing"
)
func TestClassifyTerminalVKJoinError(t *testing.T) {
tests := []struct {
@@ -53,3 +56,26 @@ func TestClassifyTerminalVKJoinErrorIgnoresTransient(t *testing.T) {
t.Fatalf("unexpected terminal error: %v", got)
}
}
func TestClassifyHashCheckErrorKeepsTerminalAndTransientStatusesSeparate(t *testing.T) {
tests := []struct {
errText string
status string
}{
{errText: "INVALID_JOIN_LINK: VK API error_code:9008", status: "dead"},
{errText: "ANON_BLOCKED: anonymous join is disabled", status: "blocked"},
{errText: "CALL_FULL: call is full", status: "full"},
{errText: "vchat.joinConversationByLink: participant.check.flood", status: "limited"},
{errText: "vchat.joinConversationByLink: VK HTTPS api.vk.me: timeout", status: "network"},
{errText: "vchat.joinConversationByLink: unexpected response", status: "error"},
}
for _, test := range tests {
t.Run(test.status+"_"+test.errText[:4], func(t *testing.T) {
status, _ := classifyHashCheckError(errors.New(test.errText))
if status != test.status {
t.Fatalf("status = %q, want %q", status, test.status)
}
})
}
}
+129 -34
View File
@@ -9,6 +9,7 @@ import (
"io"
"log"
neturl "net/url"
"strconv"
"strings"
"sync/atomic"
"time"
@@ -29,8 +30,25 @@ const (
var (
errVKCallsFlood = errors.New("VKCalls participant check flood")
vkCallsFloodUntil atomic.Int64
vkCallsAPIBaseURLs = [...]string{
"https://api.vk.me",
"https://api.vk.ru",
}
)
func vkCallsJoinURL(link string) string {
return neturl.QueryEscape("https://vk.ru/call/join/" + link)
}
func vkCallsAPIRequestURLs(path string) []string {
cleanPath := "/" + strings.TrimLeft(path, "/")
result := make([]string, 0, len(vkCallsAPIBaseURLs))
for _, baseURL := range vkCallsAPIBaseURLs {
result = append(result, strings.TrimRight(baseURL, "/")+cleanPath)
}
return result
}
func isVKCallsFloodError(err error) bool {
return errors.Is(err, errVKCallsFlood)
}
@@ -52,11 +70,11 @@ func stableVKCallsUUID(scope string) string {
return uuid.NewSHA1(uuid.NameSpaceOID, []byte(seed)).String()
}
func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (string, string, []string, error) {
func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (string, string, []string, time.Duration, error) {
deviceID := stableVKCallsUUID("vk")
okDeviceID := stableVKCallsUUID("ok")
name := generateName()
joinURL := neturl.QueryEscape("https://vk.com/call/join/" + link)
joinURL := vkCallsJoinURL(link)
client, err := tlsclient.NewHttpClient(
tlsclient.NewNoopLogger(),
@@ -65,10 +83,15 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin
tlsclient.WithCookieJar(tlsclient.NewCookieJar()),
)
if err != nil {
return "", "", nil, fmt.Errorf("setup: %w", err)
return "", "", nil, 0, fmt.Errorf("setup: %w", err)
}
doRequest := func(step, requestURL string) (map[string]interface{}, error) {
parsedURL, parseErr := neturl.Parse(requestURL)
host := ""
if parseErr == nil {
host = parsedURL.Hostname()
}
req, err := fhttp.NewRequestWithContext(ctx, "POST", requestURL, bytes.NewReader(nil))
if err != nil {
return nil, fmt.Errorf("%s create request: %w", step, err)
@@ -80,6 +103,9 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin
resp, err := client.Do(req)
if err != nil {
if host != "" {
return nil, fmt.Errorf("%s VK HTTPS %s: %w", step, host, err)
}
return nil, fmt.Errorf("%s request: %w", step, err)
}
defer resp.Body.Close()
@@ -93,55 +119,73 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin
}
return result, nil
}
doVKAPIRequest := func(step, path string) (map[string]interface{}, error) {
var lastErr error
requestURLs := vkCallsAPIRequestURLs(path)
for index, requestURL := range requestURLs {
result, requestErr := doRequest(step, requestURL)
if requestErr == nil {
return result, nil
}
lastErr = requestErr
if index+1 < len(requestURLs) {
log.Printf("[VKCalls] %s через основной API-домен не выполнен, пробуем совместимый резерв: %v", step, requestErr)
}
}
return nil, lastErr
}
step1URL := fmt.Sprintf(
"https://api.vk.me/method/auth.getAnonymToken?v=%s&client_id=%s&link=%s&device_id=%s&anonymName=%s&lang=ru",
step1Path := fmt.Sprintf(
"/method/auth.getAnonymToken?v=%s&client_id=%s&link=%s&device_id=%s&anonymName=%s&lang=ru",
vkCallsAPIVersion, vkCallsClientID, joinURL, deviceID, neturl.QueryEscape(name),
)
step1, err := doRequest("auth.getAnonymToken", step1URL)
step1, err := doVKAPIRequest("auth.getAnonymToken", step1Path)
if err != nil {
return "", "", nil, err
return "", "", nil, 0, err
}
if err := parseVKCallsAPIError(step1); err != nil {
return "", "", nil, 0, fmt.Errorf("auth.getAnonymToken: %w", err)
}
anonymToken, err := extractVKCallsString(step1, "response", "token")
if err != nil {
return "", "", nil, fmt.Errorf("auth.getAnonymToken: %w", err)
return "", "", nil, 0, fmt.Errorf("auth.getAnonymToken: %w", err)
}
step2URL := fmt.Sprintf(
"https://api.vk.me/method/messages.getCallPreview?v=%s&anonymous_token=%s&device_id=%s&extended=1&fields=first_name,last_name,photo_200&lang=ru&link=%s",
step2Path := fmt.Sprintf(
"/method/messages.getCallPreview?v=%s&anonymous_token=%s&device_id=%s&extended=1&fields=first_name,last_name,photo_200&lang=ru&link=%s",
vkCallsAPIVersion, neturl.QueryEscape(anonymToken), deviceID, joinURL,
)
step2, err := doRequest("messages.getCallPreview", step2URL)
step2, err := doVKAPIRequest("messages.getCallPreview", step2Path)
if err != nil {
return "", "", nil, err
return "", "", nil, 0, err
}
if err := parseVKCallsAPIError(step2); err != nil {
return "", "", nil, fmt.Errorf("messages.getCallPreview: %w", err)
return "", "", nil, 0, fmt.Errorf("messages.getCallPreview: %w", err)
}
userID, err := extractVKCallsNumber(step2, "response", "user_id")
if err != nil {
return "", "", nil, fmt.Errorf("messages.getCallPreview user_id: %w", err)
return "", "", nil, 0, fmt.Errorf("messages.getCallPreview user_id: %w", err)
}
secret, err := extractVKCallsString(step2, "response", "secret")
if err != nil {
return "", "", nil, fmt.Errorf("messages.getCallPreview secret: %w", err)
return "", "", nil, 0, fmt.Errorf("messages.getCallPreview secret: %w", err)
}
step3URL := fmt.Sprintf(
"https://api.vk.me/method/messages.getAnonymCallToken?v=%s&anonymous_token=%s&device_id=%s&link=%s&name=%s&user_id=%.0f&secret=%s&lang=ru",
step3Path := fmt.Sprintf(
"/method/messages.getAnonymCallToken?v=%s&anonymous_token=%s&device_id=%s&link=%s&name=%s&user_id=%.0f&secret=%s&lang=ru",
vkCallsAPIVersion, neturl.QueryEscape(anonymToken), deviceID, joinURL,
neturl.QueryEscape(name), userID, neturl.QueryEscape(secret),
)
step3, err := doRequest("messages.getAnonymCallToken", step3URL)
step3, err := doVKAPIRequest("messages.getAnonymCallToken", step3Path)
if err != nil {
return "", "", nil, err
return "", "", nil, 0, err
}
if err := parseVKCallsAPIError(step3); err != nil {
return "", "", nil, fmt.Errorf("messages.getAnonymCallToken: %w", err)
return "", "", nil, 0, fmt.Errorf("messages.getAnonymCallToken: %w", err)
}
okAnonymToken, err := extractVKCallsString(step3, "response", "token")
if err != nil {
return "", "", nil, fmt.Errorf("messages.getAnonymCallToken token: %w", err)
return "", "", nil, 0, fmt.Errorf("messages.getAnonymCallToken token: %w", err)
}
sessionData := neturl.QueryEscape(fmt.Sprintf(`{"version":2,"device_id":"%s","client_version":"1.0.1"}`, okDeviceID))
@@ -149,11 +193,14 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin
"&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA"
step4, err := doRequest("auth.anonymLogin", step4URL)
if err != nil {
return "", "", nil, err
return "", "", nil, 0, err
}
if err := parseVKCallsOKError(step4); err != nil {
return "", "", nil, 0, fmt.Errorf("auth.anonymLogin: %w", err)
}
sessionKey, err := extractVKCallsString(step4, "session_key")
if err != nil {
return "", "", nil, fmt.Errorf("auth.anonymLogin session_key: %w", err)
return "", "", nil, 0, fmt.Errorf("auth.anonymLogin session_key: %w", err)
}
step5URL := fmt.Sprintf(
@@ -162,25 +209,29 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin
)
step5, err := doRequest("vchat.joinConversationByLink", step5URL)
if err != nil {
return "", "", nil, err
return "", "", nil, 0, err
}
if terminal := classifyTerminalVKJoinError(step5); terminal != nil {
return "", "", nil, 0, terminal
}
if err := parseVKCallsOKError(step5); err != nil {
return "", "", nil, fmt.Errorf("vchat.joinConversationByLink: %w", err)
return "", "", nil, 0, fmt.Errorf("vchat.joinConversationByLink: %w", err)
}
user, err := extractVKCallsString(step5, "turn_server", "username")
if err != nil {
return "", "", nil, err
return "", "", nil, 0, err
}
pass, err := extractVKCallsString(step5, "turn_server", "credential")
if err != nil {
return "", "", nil, err
return "", "", nil, 0, err
}
addrs := parseVKCallsTURNAddresses(step5)
if len(addrs) == 0 {
return "", "", nil, fmt.Errorf("turn_server.urls empty")
return "", "", nil, 0, fmt.Errorf("turn_server.urls empty")
}
log.Printf("[STREAM %d] [VKCalls] TURN credentials получены, адресов=%d", streamID, len(addrs))
return user, pass, addrs, nil
lifetime := parseVKCallsTURNLifetime(step5, user, time.Now())
log.Printf("[STREAM %d] [VKCalls] TURN credentials получены, адресов=%d, lifetime=%v", streamID, len(addrs), lifetime.Truncate(time.Second))
return user, pass, addrs, lifetime, nil
}
func extractVKCallsString(resp map[string]interface{}, keys ...string) (string, error) {
@@ -230,15 +281,52 @@ func parseVKCallsTURNAddresses(resp map[string]interface{}) []string {
if !ok {
continue
}
value = strings.Split(value, "?")[0]
value = strings.TrimPrefix(strings.TrimPrefix(value, "turn:"), "turns:")
if value != "" {
result = append(result, value)
if normalized := normalizeTURNURL(value); normalized != "" {
result = append(result, normalized)
}
}
return result
}
func parseVKCallsTURNLifetime(resp map[string]interface{}, username string, now time.Time) time.Duration {
if turnServer, ok := resp["turn_server"].(map[string]interface{}); ok {
for _, key := range []string{"lifetime", "ttl"} {
if seconds := vkCallsPositiveSeconds(turnServer[key]); seconds > 0 {
return time.Duration(seconds) * time.Second
}
}
}
// TURN REST обычно кодирует срок действия в начале username.
if separator := strings.IndexByte(username, ':'); separator > 0 {
if expiresAt, err := strconv.ParseInt(username[:separator], 10, 64); err == nil {
lifetime := time.Unix(expiresAt, 0).Sub(now)
if lifetime > 0 {
return lifetime
}
}
}
return 0
}
func vkCallsPositiveSeconds(value interface{}) int64 {
switch number := value.(type) {
case float64:
if number > 0 {
return int64(number)
}
case json.Number:
if parsed, err := number.Int64(); err == nil && parsed > 0 {
return parsed
}
case string:
if parsed, err := time.ParseDuration(strings.TrimSpace(number) + "s"); err == nil && parsed > 0 {
return int64(parsed / time.Second)
}
}
return 0
}
func parseVKCallsAPIError(resp map[string]interface{}) error {
errObject, ok := resp["error"].(map[string]interface{})
if !ok {
@@ -249,6 +337,13 @@ func parseVKCallsAPIError(resp map[string]interface{}) error {
if int(code) == 14 {
return parseVkCaptchaError(errObject)
}
lowerMessage := strings.ToLower(message)
if int(code) == 29 || strings.Contains(lowerMessage, "flood") || strings.Contains(lowerMessage, "rate limit") {
return fmt.Errorf("%w: VK API %.0f: %s", errVKCallsFlood, code, message)
}
if terminal := classifyTerminalVKJoinError(errObject); terminal != nil {
return terminal
}
if code != 0 || message != "" {
return fmt.Errorf("VK API error %.0f: %s", code, message)
}
+80 -1
View File
@@ -2,11 +2,34 @@ package main
import (
"errors"
"net/url"
"reflect"
"testing"
"time"
)
func TestVKCallsUsesVkRuJoinLink(t *testing.T) {
encoded := vkCallsJoinURL("join-code")
decoded, err := url.QueryUnescape(encoded)
if err != nil {
t.Fatalf("decode join URL: %v", err)
}
if decoded != "https://vk.ru/call/join/join-code" {
t.Fatalf("join URL = %q", decoded)
}
}
func TestVKCallsUsesVkMeAPIWithCompatibilityFallback(t *testing.T) {
got := vkCallsAPIRequestURLs("/method/test?v=5.276")
want := []string{
"https://api.vk.me/method/test?v=5.276",
"https://api.vk.ru/method/test?v=5.276",
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("API URLs = %#v, want %#v", got, want)
}
}
func TestStableVKCallsUUID(t *testing.T) {
setVKCallsPreflight(true, "device-a")
first := stableVKCallsUUID("vk")
@@ -30,7 +53,7 @@ func TestParseVKCallsTURNAddresses(t *testing.T) {
},
},
}
want := []string{"1.2.3.4:3478", "turn.example:443"}
want := []string{"turn:1.2.3.4:3478?transport=udp", "turns:turn.example:443?transport=tcp"}
if got := parseVKCallsTURNAddresses(resp); !reflect.DeepEqual(got, want) {
t.Fatalf("addresses = %#v, want %#v", got, want)
}
@@ -64,6 +87,62 @@ func TestParseVKCallsFloodError(t *testing.T) {
}
}
func TestParseVKCallsAPIFloodError(t *testing.T) {
err := parseVKCallsAPIError(map[string]interface{}{
"error": map[string]interface{}{
"error_code": float64(29),
"error_msg": "Rate limit reached",
},
})
if !isVKCallsFloodError(err) {
t.Fatalf("expected VKCalls flood error, got %v", err)
}
}
func TestParseVKCallsTURNLifetime(t *testing.T) {
now := time.Unix(1_700_000_000, 0)
tests := []struct {
name string
response map[string]interface{}
username string
want time.Duration
}{
{
name: "lifetime",
response: map[string]interface{}{
"turn_server": map[string]interface{}{"lifetime": float64(600)},
},
want: 10 * time.Minute,
},
{
name: "ttl",
response: map[string]interface{}{
"turn_server": map[string]interface{}{"ttl": "300"},
},
want: 5 * time.Minute,
},
{
name: "username expiry",
response: map[string]interface{}{"turn_server": map[string]interface{}{}},
username: "1700000600:participant",
want: 10 * time.Minute,
},
{
name: "unknown",
response: map[string]interface{}{},
username: "participant",
want: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := parseVKCallsTURNLifetime(test.response, test.username, now); got != test.want {
t.Fatalf("lifetime = %v, want %v", got, test.want)
}
})
}
}
func TestVKCallsFloodPause(t *testing.T) {
now := time.Unix(1_700_000_000, 0)
startVKCallsFloodPause(now)
+161
View File
@@ -0,0 +1,161 @@
package main
import (
"context"
"fmt"
"log"
"net"
"strings"
"time"
)
const dnsProbeHost = "login.vk.ru"
type dnsRoute struct {
Label string
Network string
Address string
System bool
}
type dnsRouteProbe struct {
Route dnsRoute
Err error
}
type directDNSProbe func(context.Context, dnsRoute, time.Duration) error
type systemDNSProbe func(context.Context, *net.Resolver, time.Duration) error
func setupGlobalResolver() {
systemResolver := net.DefaultResolver
route, probes := chooseDNSRoute(context.Background(), systemResolver)
if route.System {
logDNSSystemRoute(probes)
return
}
if route.Address == "" {
logDNSUnavailable(probes)
return
}
log.Printf("[DNS] Прямой DNS %s отвечает для %s; используем его", route.Label, dnsProbeHost)
net.DefaultResolver = fixedDNSResolver(route)
}
func chooseDNSRoute(ctx context.Context, systemResolver *net.Resolver) (dnsRoute, []dnsRouteProbe) {
return chooseDNSRouteWithProbes(ctx, systemResolver, probeDNSRoute, probeSystemDNS)
}
func chooseDNSRouteWithProbes(
ctx context.Context,
systemResolver *net.Resolver,
probeDirect directDNSProbe,
probeSystem systemDNSProbe,
) (dnsRoute, []dnsRouteProbe) {
candidates := []dnsRoute{
{Label: "77.88.8.8 UDP", Network: "udp", Address: "77.88.8.8:53"},
{Label: "77.88.8.1 UDP", Network: "udp", Address: "77.88.8.1:53"},
{Label: "77.88.8.8 TCP", Network: "tcp", Address: "77.88.8.8:53"},
{Label: "77.88.8.1 TCP", Network: "tcp", Address: "77.88.8.1:53"},
}
probes := make([]dnsRouteProbe, 0, len(candidates)+1)
for _, route := range candidates {
timeout := 1200 * time.Millisecond
if route.Network == "tcp" {
timeout = 1500 * time.Millisecond
}
err := probeDirect(ctx, route, timeout)
probes = append(probes, dnsRouteProbe{Route: route, Err: err})
if err == nil {
return route, probes
}
}
systemRoute := dnsRoute{Label: "системный DNS устройства", System: true}
err := probeSystem(ctx, systemResolver, 1800*time.Millisecond)
probes = append(probes, dnsRouteProbe{Route: systemRoute, Err: err})
if err == nil {
return systemRoute, probes
}
return dnsRoute{}, probes
}
func probeDNSRoute(ctx context.Context, route dnsRoute, timeout time.Duration) error {
probeCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
resolver := fixedDNSResolver(route)
return lookupHostWithResolver(probeCtx, resolver, dnsProbeHost)
}
func probeSystemDNS(ctx context.Context, resolver *net.Resolver, timeout time.Duration) error {
if resolver == nil {
resolver = &net.Resolver{}
}
probeCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return lookupHostWithResolver(probeCtx, resolver, dnsProbeHost)
}
func fixedDNSResolver(route dnsRoute) *net.Resolver {
dialer := &net.Dialer{
Timeout: 1200 * time.Millisecond,
KeepAlive: 30 * time.Second,
}
if route.Network == "tcp" {
dialer.Timeout = 1500 * time.Millisecond
}
return &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
return dialer.DialContext(ctx, route.Network, route.Address)
},
}
}
func lookupHostWithResolver(ctx context.Context, resolver *net.Resolver, host string) error {
addrs, err := resolver.LookupIPAddr(ctx, host)
if err != nil {
return err
}
if len(addrs) == 0 {
return fmt.Errorf("пустой DNS-ответ")
}
return nil
}
func logDNSSystemRoute(probes []dnsRouteProbe) {
failedDirect := summarizeDNSFailures(probes, false)
if failedDirect == "" {
log.Printf("[DNS] Системный DNS устройства отвечает для %s; используем его", dnsProbeHost)
return
}
log.Printf("[DNS] Прямой DNS клиента недоступен (%s); системный DNS устройства отвечает — используем его", failedDirect)
}
func logDNSUnavailable(probes []dnsRouteProbe) {
log.Printf("[DNS] DNS до VK недоступен: прямой DNS клиента и системный DNS устройства не ответили (%s)", summarizeDNSFailures(probes, true))
}
func summarizeDNSFailures(probes []dnsRouteProbe, includeSystem bool) string {
parts := make([]string, 0, len(probes))
for _, probe := range probes {
if probe.Err == nil || (!includeSystem && probe.Route.System) {
continue
}
parts = append(parts, probe.Route.Label+": "+shortDNSError(probe.Err))
}
return strings.Join(parts, "; ")
}
func shortDNSError(err error) string {
if err == nil {
return "OK"
}
text := strings.ReplaceAll(err.Error(), "\n", " ")
text = strings.ReplaceAll(text, "\r", " ")
if len(text) > 120 {
return text[:120] + "…"
}
return text
}
+91
View File
@@ -0,0 +1,91 @@
package main
import (
"context"
"errors"
"io"
"net"
"testing"
"time"
)
func TestChooseDNSRouteFallsBackToSystemAfterDirectTimeouts(t *testing.T) {
directAttempts := make([]string, 0, 4)
systemAttempts := 0
route, probes := chooseDNSRouteWithProbes(
context.Background(),
&net.Resolver{},
func(_ context.Context, route dnsRoute, _ time.Duration) error {
directAttempts = append(directAttempts, route.Label)
return context.DeadlineExceeded
},
func(_ context.Context, _ *net.Resolver, _ time.Duration) error {
systemAttempts++
return nil
},
)
wantAttempts := []string{
"77.88.8.8 UDP",
"77.88.8.1 UDP",
"77.88.8.8 TCP",
"77.88.8.1 TCP",
}
if len(directAttempts) != len(wantAttempts) {
t.Fatalf("direct attempts = %v, want %v", directAttempts, wantAttempts)
}
for i := range wantAttempts {
if directAttempts[i] != wantAttempts[i] {
t.Fatalf("direct attempts = %v, want %v", directAttempts, wantAttempts)
}
}
if !route.System || route.Label != "системный DNS устройства" {
t.Fatalf("route = %+v, want system resolver", route)
}
if systemAttempts != 1 {
t.Fatalf("system attempts = %d, want 1", systemAttempts)
}
if len(probes) != len(wantAttempts)+1 {
t.Fatalf("probes = %d, want %d", len(probes), len(wantAttempts)+1)
}
}
func TestLookupHostRequiresDNSResponseFromConnectedSocket(t *testing.T) {
resolver := &net.Resolver{
PreferGo: true,
Dial: func(context.Context, string, string) (net.Conn, error) {
client, server := net.Pipe()
go func() {
defer server.Close()
_, _ = io.Copy(io.Discard, server)
}()
return client, nil
},
}
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
defer cancel()
if err := lookupHostWithResolver(ctx, resolver, dnsProbeHost); err == nil {
t.Fatal("connected DNS socket without a response was treated as working")
}
}
func TestSummarizeDNSFailuresSkipsSystemWhenRequested(t *testing.T) {
probes := []dnsRouteProbe{
{Route: dnsRoute{Label: "77.88.8.8 UDP"}, Err: errors.New("timeout")},
{Route: dnsRoute{Label: "системный DNS устройства", System: true}, Err: nil},
}
got := summarizeDNSFailures(probes, false)
if got != "77.88.8.8 UDP: timeout" {
t.Fatalf("summary = %q", got)
}
}
func TestShortDNSErrorLimitsLongText(t *testing.T) {
long := "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
got := shortDNSError(errors.New(long))
if len(got) > 123 {
t.Fatalf("short error too long: %d", len(got))
}
}
+235 -11
View File
@@ -14,8 +14,112 @@ import (
const (
workersPerGroup = 9
defaultCycleSecs = 36000
defaultWorkerRetryMin = 5 * time.Second
defaultWorkerRetryMax = 15 * time.Second
wrapHandshakeRetryMin = 1 * time.Second
wrapHandshakeRetryMax = 3 * time.Second
)
func workerRetryDelayBounds(err error) (time.Duration, time.Duration) {
if err != nil && strings.Contains(strings.ToUpper(err.Error()), "WRAP_AUTH_TIMEOUT") {
return wrapHandshakeRetryMin, wrapHandshakeRetryMax
}
return defaultWorkerRetryMin, defaultWorkerRetryMax
}
func workerRetryDelay(err error) time.Duration {
minDelay, maxDelay := workerRetryDelayBounds(err)
steps := int((maxDelay-minDelay)/time.Second) + 1
return minDelay + time.Duration(rand.Intn(steps))*time.Second
}
type workerPolicyRetryGate struct {
mu sync.Mutex
blockedUntil time.Time
round int
}
func workerPolicyRetryDelay(round int) time.Duration {
if round < 1 {
round = 1
}
delay := time.Duration(3+round*2) * time.Second
if delay > 15*time.Second {
return 15 * time.Second
}
return delay
}
// wait объединяет одновременные отказы всех воркеров в одно окно повтора.
// Небольшой разброс не даёт девяти DTLS-handshake стартовать в одну миллисекунду.
func (g *workerPolicyRetryGate) wait(ctx context.Context, workerID int) (bool, int, error) {
g.mu.Lock()
now := time.Now()
startedRound := !now.Before(g.blockedUntil)
if startedRound {
g.round++
g.blockedUntil = now.Add(workerPolicyRetryDelay(g.round))
}
round := g.round
retryAt := g.blockedUntil.Add(time.Duration(workerID%workersPerGroup) * 250 * time.Millisecond)
g.mu.Unlock()
wait := time.Until(retryAt)
if wait <= 0 {
return startedRound, round, nil
}
timer := time.NewTimer(wait)
defer timer.Stop()
select {
case <-timer.C:
return startedRound, round, nil
case <-ctx.Done():
return startedRound, round, ctx.Err()
}
}
func (g *workerPolicyRetryGate) reset() {
g.mu.Lock()
g.blockedUntil = time.Time{}
g.round = 0
g.mu.Unlock()
}
type configFirstStartGate struct {
enabled bool
ready chan struct{}
once sync.Once
}
func newConfigFirstStartGate(enabled bool) *configFirstStartGate {
gate := &configFirstStartGate{enabled: enabled}
if enabled {
gate.ready = make(chan struct{})
}
return gate
}
func (g *configFirstStartGate) wait(ctx context.Context, workerIndex int) error {
if g == nil || !g.enabled || workerIndex == 0 {
return nil
}
select {
case <-g.ready:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (g *configFirstStartGate) release() {
if g == nil || !g.enabled {
return
}
g.once.Do(func() {
close(g.ready)
})
}
// WorkerGroup:
// Запускает 9 потоков с одними кредами. Ротации нет — работает до смерти воркеров.
func WorkerGroup(
@@ -30,8 +134,11 @@ func WorkerGroup(
getConfig bool,
configCh chan<- string,
workerIDs []int,
requestedWorkers int,
configFirstStart bool,
hashFallback bool,
pauseFlag *int32,
deviceID, password, deviceInfo string,
deviceID, password, deviceInfo, transportSession string,
stats *Stats,
waitReady <-chan struct{},
signalReady chan<- struct{},
@@ -50,6 +157,9 @@ func WorkerGroup(
if !getConfig {
configSent = 1
}
configStartGate := newConfigFirstStartGate(
configFirstStart && getConfig && requestedWorkers == workersPerGroup,
)
var signalReadyOnce sync.Once
signalNext := func(delay time.Duration, reason string) {
@@ -79,15 +189,35 @@ func WorkerGroup(
time.Sleep(1 * time.Second)
}
hash := tp.Hashes[hashIndex%len(tp.Hashes)]
shortHash := hash
if len(shortHash) > 8 {
shortHash = shortHash[:8]
hashCandidates := []string{tp.Hashes[hashIndex%len(tp.Hashes)]}
if hashFallback && len(tp.Hashes) > 1 {
hashCandidates = make([]string, 0, len(tp.Hashes))
for offset := 0; offset < len(tp.Hashes); offset++ {
hashCandidates = append(
hashCandidates,
tp.Hashes[(hashIndex+offset)%len(tp.Hashes)],
)
}
log.Printf("[ГРУППА #%d] Запрос кредов (хеш: %s...)", groupID, shortHash)
}
selectedHash := 0
hash := hashCandidates[selectedHash]
log.Printf("[ГРУППА #%d] Запрос реквизитов подключения", groupID)
credStreamID := groupID * 100
user, pass, turnURLs, err := GetCreds(ctx, hash, credStreamID)
for err != nil &&
selectedHash+1 < len(hashCandidates) &&
isHashFallbackCredentialError(err) {
selectedHash++
hash = hashCandidates[selectedHash]
log.Printf(
"[ГРУППА #%d] Текущий VK-хеш недоступен; пробуем резерв %d из %d",
groupID,
selectedHash+1,
len(hashCandidates),
)
user, pass, turnURLs, err = GetCreds(ctx, hash, credStreamID)
}
if err != nil && getConfig {
log.Printf("[ГРУППА #%d] Стартовые креды не получены: %v; завершаем запуск для чистого повтора", groupID, err)
cancel()
@@ -119,6 +249,7 @@ func WorkerGroup(
var credsMu sync.RWMutex
var refreshMu sync.Mutex
var lastCredRefresh atomic.Int64
var policyRetryGate workerPolicyRetryGate
refreshCreds := func(reason string) bool {
refreshMu.Lock()
@@ -131,12 +262,43 @@ func WorkerGroup(
return true
}
rotateForTurnFailure := hashFallback &&
len(hashCandidates) > 1 &&
strings.HasPrefix(strings.ToUpper(strings.TrimSpace(reason)), "TURN")
order := hashRefreshOrder(selectedHash, len(hashCandidates), rotateForTurnFailure)
var (
u string
p string
urls []string
refreshErr error
nextHashIndex = selectedHash
)
for attempt, candidateIndex := range order {
candidateHash := hashCandidates[candidateIndex]
if attempt > 0 || candidateIndex != selectedHash {
log.Printf(
"[ГРУППА #%d] Пробуем резервный VK-хеш %d из %d после ошибки TURN",
groupID,
candidateIndex+1,
len(hashCandidates),
)
}
getStreamCache(credStreamID).invalidate(credStreamID)
u, p, urls, refreshErr := GetCreds(ctx, hash, credStreamID)
u, p, urls, refreshErr = GetCreds(ctx, candidateHash, credStreamID)
if refreshErr == nil {
nextHashIndex = candidateIndex
break
}
if !isHashFallbackCredentialError(refreshErr) {
break
}
}
if refreshErr != nil {
log.Printf("[TURN] Не удалось обновить креды после %s: %v", reason, refreshErr)
return false
}
selectedHash = nextHashIndex
hash = hashCandidates[selectedHash]
credsMu.Lock()
creds = &Credentials{User: u, Pass: p, TurnURLs: urls, CacheStreamID: credStreamID}
@@ -155,9 +317,13 @@ func WorkerGroup(
// Stagger: 500мс между воркерами
workerDelay := time.Duration(i) * 500 * time.Millisecond
go func(wid int, delay time.Duration) {
go func(workerIndex, wid int, delay time.Duration) {
defer wg.Done()
if err := configStartGate.wait(ctx, workerIndex); err != nil {
return
}
if delay > 0 {
select {
case <-time.After(delay):
@@ -182,6 +348,15 @@ func WorkerGroup(
if getConf {
cc = configCh
}
requireConfig := configStartGate.enabled && getConf
var onConfigDelivered func()
if requireConfig {
onConfigDelivered = func() {
atomic.StoreInt32(&configSent, 1)
configStartGate.release()
log.Printf("[ГРУППА #%d] Новое подключение зарегистрировано; запускаем остальные воркеры", groupID)
}
}
credsMu.RLock()
credsSnapshot := *creds
@@ -189,7 +364,9 @@ func WorkerGroup(
credsMu.RUnlock()
configDelivered, sessErr := RunSession(ctx, tp, peer, d, localPort,
getConf, cc, wid, &credsSnapshot, deviceID, password, deviceInfo, stats)
getConf, cc, requireConfig, onConfigDelivered, wid, &credsSnapshot,
deviceID, password, deviceInfo,
transportSession, stats)
if getConf {
if configDelivered {
@@ -203,6 +380,27 @@ func WorkerGroup(
if ctx.Err() != nil {
return
}
if maxWorkers, limited := workerPolicyLimit(sessErr); limited {
if shouldRetryWorkerPolicy(maxWorkers, requestedWorkers) {
startedRound, round, waitErr := policyRetryGate.wait(ctx, wid)
if startedRound && (round == 1 || round%6 == 0) {
log.Printf(
"[МОЩНОСТЬ] Лимит временно занят другими потоками этого доступа (максимум: %d); повторяем подключение",
maxWorkers,
)
}
if waitErr != nil {
return
}
continue
}
log.Printf(
"[МОЩНОСТЬ] Сервер остановил лишний поток согласно ограничению доступа (максимум: %d)",
maxWorkers,
)
return
}
policyRetryGate.reset()
errStr := sessErr.Error()
errStrLower := strings.ToLower(errStr)
@@ -255,14 +453,14 @@ func WorkerGroup(
return
}
retryDelay := time.Duration(5+rand.Intn(11)) * time.Second
retryDelay := workerRetryDelay(sessErr)
select {
case <-time.After(retryDelay):
case <-ctx.Done():
return
}
}
}(wid, workerDelay)
}(i, wid, workerDelay)
}
wg.Wait()
@@ -280,6 +478,32 @@ func isTerminalGroupCredentialError(err error) bool {
strings.Contains(message, "FATAL_AUTH")
}
func isHashFallbackCredentialError(err error) bool {
if err == nil {
return false
}
message := strings.ToUpper(err.Error())
return strings.Contains(message, "INVALID_JOIN_LINK") ||
strings.Contains(message, "ANON_BLOCKED") ||
strings.Contains(message, "CALL_FULL")
}
func hashRefreshOrder(current, total int, rotate bool) []int {
if total <= 0 {
return nil
}
current = ((current % total) + total) % total
start := current
if rotate && total > 1 {
start = (current + 1) % total
}
order := make([]int, 0, total)
for offset := 0; offset < total; offset++ {
order = append(order, (start+offset)%total)
}
return order
}
func groupCredentialRetryDelay(err error) time.Duration {
if err != nil {
message := strings.ToUpper(err.Error())
+96
View File
@@ -1,7 +1,9 @@
package main
import (
"context"
"errors"
"reflect"
"testing"
"time"
)
@@ -17,12 +19,106 @@ func TestTerminalGroupCredentialErrors(t *testing.T) {
}
}
func TestManagedHashFallbackUsesOnlyHashSpecificFailures(t *testing.T) {
for _, message := range []string{"INVALID_JOIN_LINK", "ANON_BLOCKED", "CALL_FULL"} {
if !isHashFallbackCredentialError(errors.New(message)) {
t.Fatalf("%q must try the next managed-profile hash", message)
}
}
for _, message := range []string{"CAPTCHA_WAIT_REQUIRED", "VK HTTPS timeout", "FATAL_AUTH"} {
if isHashFallbackCredentialError(errors.New(message)) {
t.Fatalf("%q must not fan out across all hashes", message)
}
}
}
func TestHashRefreshOrderRotatesReserveAfterTurnFailure(t *testing.T) {
got := hashRefreshOrder(0, 4, true)
want := []int{1, 2, 3, 0}
if !reflect.DeepEqual(got, want) {
t.Fatalf("rotated order = %v, want %v", got, want)
}
got = hashRefreshOrder(2, 4, false)
want = []int{2, 3, 0, 1}
if !reflect.DeepEqual(got, want) {
t.Fatalf("regular refresh order = %v, want %v", got, want)
}
}
func TestCaptchaCredentialRetryDelay(t *testing.T) {
if got := groupCredentialRetryDelay(errors.New("CAPTCHA_WAIT_REQUIRED")); got != 90*time.Second {
t.Fatalf("captcha retry delay = %v", got)
}
}
func TestWorkerPolicyRetryDelayIsBounded(t *testing.T) {
if got := workerPolicyRetryDelay(1); got != 5*time.Second {
t.Fatalf("first policy retry delay = %v", got)
}
if got := workerPolicyRetryDelay(100); got != 15*time.Second {
t.Fatalf("maximum policy retry delay = %v", got)
}
}
func TestWrapHandshakeRetryUsesShortDedicatedWindow(t *testing.T) {
minDelay, maxDelay := workerRetryDelayBounds(
errors.New("WRAP_AUTH_TIMEOUT: отдельный DTLS-канал не ответил вовремя"),
)
if minDelay != time.Second || maxDelay != 3*time.Second {
t.Fatalf("WRAP retry bounds = %v..%v, want 1s..3s", minDelay, maxDelay)
}
minDelay, maxDelay = workerRetryDelayBounds(errors.New("TURN Allocate timeout"))
if minDelay != 5*time.Second || maxDelay != 15*time.Second {
t.Fatalf("regular retry bounds = %v..%v, want 5s..15s", minDelay, maxDelay)
}
}
func TestWrapHandshakeTimeoutAllowsFourFlightsBeforeFastRetry(t *testing.T) {
if got := dtlsHandshakeTimeout(true); got != 8*time.Second {
t.Fatalf("WRAP handshake timeout = %v, want 8s", got)
}
if got := dtlsHandshakeTimeout(false); got != 20*time.Second {
t.Fatalf("regular handshake timeout = %v, want 20s", got)
}
}
func TestConfigFirstStartGateOnlyBlocksFollowingWorkersWhenEnabled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
regular := newConfigFirstStartGate(false)
if err := regular.wait(ctx, 1); err != nil {
t.Fatalf("regular start path was blocked: %v", err)
}
managed := newConfigFirstStartGate(true)
if err := managed.wait(ctx, 0); err != nil {
t.Fatalf("config worker was blocked: %v", err)
}
waitDone := make(chan error, 1)
go func() {
waitDone <- managed.wait(ctx, 1)
}()
select {
case err := <-waitDone:
t.Fatalf("following worker passed before GETCONF: %v", err)
case <-time.After(20 * time.Millisecond):
}
managed.release()
select {
case err := <-waitDone:
if err != nil {
t.Fatalf("following worker failed after GETCONF: %v", err)
}
case <-time.After(time.Second):
t.Fatal("following worker did not start after GETCONF")
}
}
func TestWebViewTimeoutOrdering(t *testing.T) {
if captchaAutoWebViewTimeout <= 18*time.Second {
t.Fatalf("Go auto timeout %v must exceed Android WebView timeout", captchaAutoWebViewTimeout)
+74 -10
View File
@@ -3,6 +3,8 @@ package main
import (
"bufio"
"context"
"crypto/rand"
"encoding/hex"
"flag"
"fmt"
"log"
@@ -122,14 +124,22 @@ func classifyHashCheckError(err error) (string, string) {
switch {
case strings.Contains(text, "captcha_required") || strings.Contains(text, "captcha_wait_required"):
return "captcha", "VK просит капчу"
case strings.Contains(text, "call not found") ||
strings.Contains(text, "joinconversationbylink") ||
strings.Contains(text, "missing turn_server") ||
strings.Contains(text, "9000"):
case strings.Contains(text, "invalid_join_link") ||
strings.Contains(text, "call not found") ||
strings.Contains(text, "join link is not valid") ||
strings.Contains(text, "error 9000") ||
strings.Contains(text, "error 9008") ||
strings.Contains(text, "error_code:9000") ||
strings.Contains(text, "error_code:9008"):
return "dead", "Звонок не найден или закрыт"
case strings.Contains(text, "anon_blocked") || strings.Contains(text, "anonymous join is disabled"):
return "blocked", "В звонке запрещён анонимный вход"
case strings.Contains(text, "call_full") || strings.Contains(text, "call is full"):
return "full", "В звонке сейчас нет свободных мест"
case strings.Contains(text, "flood") || strings.Contains(text, "rate limit") || strings.Contains(text, "error_code:29"):
return "limited", "VK временно ограничил запросы"
case strings.Contains(text, "timeout") || strings.Contains(text, "deadline") || strings.Contains(text, "lookup") || strings.Contains(text, "network"):
case strings.Contains(text, "timeout") || strings.Contains(text, "deadline") || strings.Contains(text, "lookup") ||
strings.Contains(text, "network") || strings.Contains(text, "vk https"):
return "network", "Сетевая ошибка"
default:
return "error", err.Error()
@@ -257,21 +267,23 @@ func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if !strings.Contains(line, "error:tunnel stopped") {
log.Printf("[STDIN] %s", line)
}
switch {
case line == "PAUSE":
log.Printf("[STDIN] Команда PAUSE")
atomic.StoreInt32(&pauseFlag, 1)
case line == "RESUME":
log.Printf("[STDIN] Команда RESUME")
atomic.StoreInt32(&pauseFlag, 0)
case line == "STOP":
log.Printf("[STDIN] Команда STOP")
cancel()
return
case strings.HasPrefix(line, "CAPTCHA_RESULT|"):
result := parseCaptchaResultPayload(strings.TrimPrefix(line, "CAPTCHA_RESULT|"))
enqueueCaptchaResult(result)
log.Printf("[КАПЧА] Результат от Kotlin принят (request=%q)", result.RequestID)
default:
log.Printf("[STDIN] Неизвестная команда проигнорирована")
}
}
}()
@@ -293,9 +305,20 @@ func main() {
peerAddr := flag.String("peer", "", "адрес:порт VPS сервера")
numW := flag.Int("n", 24, "количество воркеров (кратно 9)")
checkHashes := flag.Bool("check-hashes", false, "проверить VK-хеши и выйти")
configFirstStart := flag.Bool(
"config-first-start",
false,
"дождаться GETCONF перед запуском остальных воркеров единственной группы",
)
hashFallback := flag.Bool(
"hash-fallback",
false,
"использовать остальные VK-хеши как резерв единственной группы",
)
deviceID := flag.String("device-id", "unknown", "уникальный ID устройства")
deviceInfo := flag.String("device-info", "", "JSON с безопасной информацией об устройстве")
transportSessionFlag := flag.String("transport-session", "", "поколение текущего запуска транспорта")
connPassword := flag.String("password", "", "пароль подключения")
captchaMode := flag.String("captcha-mode", "auto", "режим обхода капчи (auto/wv/rjs)")
vkCallsPreflight := flag.Bool("vkcalls-preflight", true, "пробовать VKCalls до captcha-цепочки")
@@ -303,6 +326,10 @@ func main() {
clientIdsFlag := flag.String("client-ids", "", "ID клиентов VK через запятую")
flag.Parse()
transportSession := normalizeTransportSession(*transportSessionFlag)
if transportSession == "" {
transportSession = newTransportSession()
}
activeCaptchaMode := setCaptchaMode(*captchaMode)
setVKCallsPreflight(*vkCallsPreflight, *deviceID)
@@ -313,9 +340,18 @@ func main() {
if *fingerprint != "" {
SetActiveFingerprint(*fingerprint)
}
customClientID := os.Getenv("WDTT_CUSTOM_VK_CLIENT_ID")
customClientSecret := os.Getenv("WDTT_CUSTOM_VK_CLIENT_SECRET")
_ = os.Unsetenv("WDTT_CUSTOM_VK_CLIENT_ID")
_ = os.Unsetenv("WDTT_CUSTOM_VK_CLIENT_SECRET")
if *clientIdsFlag != "" {
SetActiveClientIds(*clientIdsFlag)
}
if customClientID != "" || customClientSecret != "" {
if err := SetCustomVKCredentials(customClientID, customClientSecret); err != nil {
log.Fatalf("[КЛИЕНТ] Некорректные пользовательские реквизиты VK: %v", err)
}
}
hashes := ParseHashes(*vkHash)
if len(hashes) == 0 {
@@ -365,6 +401,8 @@ func main() {
*numW = workersPerGroup
}
*numW = (*numW / workersPerGroup) * workersPerGroup
useConfigFirstStart := *configFirstStart && *numW == workersPerGroup
useHashFallback := *hashFallback && *numW == workersPerGroup
tp := &TurnParams{
Host: *host,
@@ -429,7 +467,7 @@ func main() {
log.Printf("[КЛИЕНТ] Протокол: UDP")
log.Printf("[КЛИЕНТ] WRAP: %s", wrapStatus)
log.Printf("[WRAP] Ключ выведен из пароля, режим RTP AEAD активен")
log.Printf("[КЛИЕНТ] Device ID: %s", *deviceID)
log.Printf("[КЛИЕНТ] Идентификатор устройства инициализирован")
log.Printf("[КЛИЕНТ] Captcha: %s", captchaStatus)
log.Println("[КЛИЕНТ] ═══════════════════════════════════════")
@@ -516,7 +554,8 @@ func main() {
go func(groupID int, isFirstGroup bool, configChan chan<- string, workerIds []int, startHashIndex int, waitR <-chan struct{}, sigR chan<- struct{}) {
defer wg.Done()
WorkerGroup(ctx, cancel, groupID, startHashIndex, tp, peer, disp, localPort,
isFirstGroup, configChan, workerIds, &pauseFlag, *deviceID, *connPassword, *deviceInfo, stats, waitR, sigR)
isFirstGroup, configChan, workerIds, *numW, useConfigFirstStart, useHashFallback, &pauseFlag,
*deviceID, *connPassword, *deviceInfo, transportSession, stats, waitR, sigR)
}(gID, isFirst, cc, ids, g, myWaitReady, mySignalReady)
}
@@ -525,3 +564,28 @@ func main() {
<-configDone
log.Println("[КЛИЕНТ] Все воркеры завершены")
}
func newTransportSession() string {
var value [16]byte
if _, err := rand.Read(value[:]); err == nil {
return hex.EncodeToString(value[:])
}
return fmt.Sprintf("fallback-%d-%d", time.Now().UnixNano(), os.Getpid())
}
func normalizeTransportSession(value string) string {
value = strings.TrimSpace(value)
if len(value) < 16 || len(value) > 64 {
return ""
}
for _, char := range value {
if (char >= 'a' && char <= 'z') ||
(char >= 'A' && char <= 'Z') ||
(char >= '0' && char <= '9') ||
char == '-' || char == '_' {
continue
}
return ""
}
return value
}
+67 -19
View File
@@ -1,37 +1,49 @@
package main
import (
"context"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
)
// RequestConfig запрашивает WireGuard конфиг через DTLS-соединение.
func RequestConfig(conn net.Conn, localPort, deviceID, password, deviceInfo string) (string, error) {
payload := fmt.Sprintf("GETCONF:%s|%s|%s", localPort, deviceID, password)
if strings.TrimSpace(deviceInfo) != "" {
payload += "|" + strings.ReplaceAll(deviceInfo, "|", " ")
}
if _, err := conn.Write([]byte(payload)); err != nil {
return "", fmt.Errorf("отправка GETCONF: %w", err)
}
type workerPolicyLimitError struct {
maxWorkers int
}
b := make([]byte, 4096)
if err := conn.SetReadDeadline(time.Now().Add(15 * time.Second)); err != nil {
return "", fmt.Errorf("установка дедлайна: %w", err)
}
n, err := conn.Read(b)
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
return "", fmt.Errorf("чтение ответа конфига: %w", err)
}
func (e *workerPolicyLimitError) Error() string {
return fmt.Sprintf("WORKER_POLICY_LIMIT:%d", e.maxWorkers)
}
resp := string(b[:n])
func workerPolicyLimit(err error) (int, bool) {
var policyError *workerPolicyLimitError
if !errors.As(err, &policyError) {
return 0, false
}
return policyError.maxWorkers, true
}
func shouldRetryWorkerPolicy(maxWorkers, requestedWorkers int) bool {
return requestedWorkers > 0 && maxWorkers >= requestedWorkers
}
func parseConfigResponse(resp string) (string, error) {
if resp == "NOCONF" {
return "", nil
}
if strings.HasPrefix(resp, "POLICY:max_workers=") {
value := strings.TrimSpace(strings.TrimPrefix(resp, "POLICY:max_workers="))
maxWorkers, err := strconv.Atoi(value)
if err != nil || maxWorkers < 1 || maxWorkers > 128 {
return "", fmt.Errorf("некорректная политика мощности сервера")
}
return "", &workerPolicyLimitError{maxWorkers: maxWorkers}
}
if strings.HasPrefix(resp, "DENIED:") {
reason := strings.TrimPrefix(resp, "DENIED:")
switch reason {
@@ -48,3 +60,39 @@ func RequestConfig(conn net.Conn, localPort, deviceID, password, deviceInfo stri
return resp, nil
}
// RequestConfig запрашивает WireGuard конфиг через DTLS-соединение.
func RequestConfig(
ctx context.Context,
conn net.Conn,
localPort, deviceID, password, deviceInfo, transportSession string,
) (string, error) {
payload := fmt.Sprintf("GETCONF:%s|%s|%s", localPort, deviceID, password)
safeDeviceInfo := strings.ReplaceAll(strings.TrimSpace(deviceInfo), "|", " ")
safeTransportSession := normalizeTransportSession(transportSession)
if safeDeviceInfo != "" || safeTransportSession != "" {
payload += "|" + safeDeviceInfo
}
if safeTransportSession != "" {
payload += "|" + safeTransportSession
}
if _, err := conn.Write([]byte(payload)); err != nil {
return "", fmt.Errorf("отправка GETCONF: %w", err)
}
b := make([]byte, 4096)
if err := conn.SetReadDeadline(time.Now().Add(15 * time.Second)); err != nil {
return "", fmt.Errorf("установка дедлайна: %w", err)
}
stopRead := context.AfterFunc(ctx, func() {
_ = conn.SetReadDeadline(time.Now())
})
defer stopRead()
n, err := conn.Read(b)
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
return "", fmt.Errorf("чтение ответа конфига: %w", err)
}
return parseConfigResponse(string(b[:n]))
}
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more