Выпуск WDTT Plus v19
This commit is contained in:
1 parent
af0ff89108
commit
ed8893a2a6
143 files changed
+15817
-3821
No files matched your search
@@ -196,7 +196,7 @@ body:
|
||||
id: server_diagnostics
|
||||
attributes:
|
||||
label: Диагностика собственного сервера из «Деплой»
|
||||
description: 'Для своего сервера: «Деплой» → «Установка на сервер» → лупа «Проверить сервер» → «Скопировать отчёт». SSH-доступ нужен только к серверу, которым вы управляете. Для полученного профиля без такого доступа поле можно пропустить. Перед публикацией проверьте адреса, логины, порты и сведения о системе.'
|
||||
description: 'Для своего сервера: «Деплой» → лупа «Проверить сервер» → «Скопировать отчёт». SSH-доступ нужен только к серверу, которым вы управляете. Для полученного профиля без такого доступа поле можно пропустить. Перед публикацией проверьте адреса, логины, порты и сведения о системе.'
|
||||
render: text
|
||||
validations:
|
||||
required: false
|
||||
|
||||
@@ -2,6 +2,58 @@
|
||||
|
||||
Здесь фиксируются заметные пользовательские изменения WDTT Plus.
|
||||
|
||||
## v19 — 29.09.2026
|
||||
|
||||
Для новых возможностей соединения обновите серверную часть до версии 19 с сохранением данных. Приложение и сервер сохраняют совместимость с предыдущими версиями.
|
||||
|
||||
### Подключение и устойчивость
|
||||
|
||||
- Два режима: «UDP» по умолчанию с резервом TCP/TLS и «TCP/TLS» без внешнего UDP и HTTP/3. Прежняя «Сеть РТ» переименована в «TCP/TLS».
|
||||
- Соединение учитывает потери пакетов и подстраивает передачу данных. Потерянные каналы восстанавливаются без остановки остальных.
|
||||
- Отказ одного канала больше не переводит новые подключения на TCP/TLS, пока другие UDP-каналы работают. Улучшен набор каналов после первого успешного подключения.
|
||||
- Исправления подключения и работы каналов могут повысить скорость передачи данных.
|
||||
- Улучшена отдача при коротких всплесках исходящего трафика; устаревшие пакеты не накапливаются в очереди.
|
||||
- При общих потерях исходящего трафика соединение снижает нагрузку до проверки отдельных каналов, чтобы избежать их массового исключения.
|
||||
- Исправлены ошибки повторного подключения, замены каналов и остановки VPN после смены сети, включая падение приложения.
|
||||
- Внешний SNI и резерв MASQUE доступны в обоих режимах. MASQUE включается отдельно.
|
||||
|
||||
### ВК-хеши
|
||||
|
||||
- Помимо получения ВК-хешей в браузере, добавлены два встроенных способа получения прямо в приложении.
|
||||
- Вход в ВК для готовых профилей сохраняется отдельно для каждого профиля. Исправлен сброс второго и третьего профилей; очистка затрагивает только выбранный профиль.
|
||||
|
||||
### Установка и управление сервером
|
||||
|
||||
- «Деплой» объединяет выбор «Установить» и «Подключить» в одном блоке. SSH-доступ и параметры открываются компактными кнопками, которые выделяются при нехватке обязательных данных.
|
||||
- Добавлен мастер первой установки с проверкой VPS, настройками и итоговым подтверждением. Для нового сервера пароль администратора создаётся автоматически; его можно сгенерировать заново и скопировать.
|
||||
- После первой установки параметры сохраняются, данные сервера показываются для копирования, а пустой «Туннель» заполняется автоматически. Остаётся добавить ВК-хеши; переход на вкладку «Туннель» отменяется, если пользователь уже открыл другой раздел.
|
||||
- Готовый сервер можно подключить или обновить без прохождения мастера. Для изменения параметров есть отдельная кнопка; перед установкой показываются отличия от текущих настроек сервера.
|
||||
- При обновлении с сохранением остаются действующими пароли, привязки устройств и ключи. После прерванного обновления сервер можно восстановить из страховочной копии прямо в приложении.
|
||||
- Исправлено управление сервером по SSH при входе обычным пользователем с правами администратора ([PR #27](https://github.com/Ivan4537/WDTT-Plus/pull/27)).
|
||||
- Встроенный Telegram-бот переименован в «WDTT Plus Менеджер»; большие объёмы трафика отображаются в ГБ и ТБ.
|
||||
|
||||
### Прокси и выходной IP
|
||||
|
||||
- Занятый порт больше не приводит к ложному состоянию готовности прокси: приложение объясняет причину и предлагает выбрать другой порт.
|
||||
- Исправлено включение внешнего TCP-прокси, WARP, WireGuard и существующего VPN-интерфейса на серверах с ограничивающими правилами сети. При ошибке включения WireGuard восстанавливается прямой выход.
|
||||
- Проверка выходного IP точнее определяет работу выбранного подключения и не принимает прямой выход или неполный ответ за успех.
|
||||
|
||||
### Логи и проверки
|
||||
|
||||
- В журнале отдельно сохраняются подтверждения UDP и TCP/TLS, этапы неудачного подключения и время ожидания. Добавлен фильтр предупреждений и ошибок; убраны устаревшие названия режимов.
|
||||
- Результаты серверных действий показываются по-русски. Технические подробности со скрытыми секретами можно раскрыть и скопировать; успешные действия больше не отмечаются как ошибки.
|
||||
- Проверка сервера ограничена по времени и отменяется крестиком. Обрывы SSH и тайм-ауты больше не выдаются за отсутствие прав администратора; неполные результаты отмечаются явно.
|
||||
- Проверки устройства и сервера учитывают выбранный профиль и режим подключения. Старые записи о завершении приложения отделены от текущих проблем; отчёты поясняют, что проверено на VPS, а что — на телефоне.
|
||||
|
||||
### Интерфейс и профили
|
||||
|
||||
- Профили переключаются свайпом по верхней части вкладок «Туннель» и «Деплой» с уведомлением о выбранном профиле.
|
||||
- Окно «Подключение» стало компактнее: дополнительные параметры свёрнуты, справка разбита на понятные блоки. У значков без подписей появились подсказки при долгом нажатии.
|
||||
- Исправлено обрезание длинных окон и инструкций, в том числе при увеличенном шрифте и открытой клавиатуре. Кнопка «Скопировать отчёт» остаётся доступной при прокрутке.
|
||||
- Положение плавающей шестерёнки сохраняется после перезапуска и обновления приложения.
|
||||
- Для готовых управляемых профилей передача настроек заменена инструкцией по переносу и кнопкой управления профилем при доступности сервиса. Такие профили исключены из копии настроек администратора; передача собственных профилей сохранена.
|
||||
- Обновлены краткая справка и варианты обращения в «Инфо → Действия»: помощь с готовым профилем показывается только для соответствующих профилей.
|
||||
|
||||
## v18 — 11.09.2026
|
||||
|
||||
### Режимы работы при выключенном экране
|
||||
@@ -58,6 +110,7 @@
|
||||
|
||||
### Управление сервером
|
||||
|
||||
- Серверная часть и оба встроенных установщика синхронизированы с версией 18; обновление по-прежнему сохраняет клиентов, ключи, настройки и резервные копии.
|
||||
- При удалении сервера теперь можно сохранить клиентов, привязки, ключи и настройки для последующей переустановки либо полностью удалить все данные WDTT Plus. Оба варианта требуют непрерывного трёхсекундного удержания и проверяются после выполнения.
|
||||
- Ручной сервер-инсталлер теперь распознаёт данные, сохранённые Android после удаления службы, и может явно восстановить их под своим управлением без потери клиентов, настроек и WireGuard-ключей; неудачная или прерванная операция полностью откатывается.
|
||||
- Ручная установка больше не останавливается с ошибкой при проверке свободного места на сервере.
|
||||
|
||||
@@ -61,6 +61,7 @@
|
||||
- **Прокси без VPN-слота:** профиль может поднять SOCKS5, HTTP CONNECT или автоматический совместный обработчик на одном порту вместо системного VPN. SOCKS5 поддерживает TCP `CONNECT` и UDP `ASSOCIATE`, а HTTP CONNECT добавляет совместимость с TCP-программами без SOCKS5. Доступ можно оставить на `127.0.0.1`, безопасно открыть для ближайшей локальной подсети либо включить оба точных адреса одновременно; любой LAN-доступ требует аутентификацию.
|
||||
- **Доверенные сети 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.
|
||||
|
||||
@@ -85,7 +86,7 @@
|
||||
- **Деплой с телефона:** вкладка **«Деплой»** подключается к серверу по SSH, загружает `wdtt-server`, создаёт `systemd`-сервис, включает NAT/firewall и открывает рабочие UDP-порты.
|
||||
- **Резервные копии сервера:** во вкладке **«Деплой»** настраиваются автоматический интервал и количество хранимых копий, отображаются последняя попытка, следующая копия и история. Выбранную копию можно проверить, восстановить, скачать на устройство в зашифрованном виде или загрузить обратно через системный выбор файла Android.
|
||||
- **SSH по паролю или ключу:** установка, подключение без установки, управление клиентами, перенос сервера и инструменты выходного IP работают как с SSH-паролем, так и с приватным ключом OpenSSH/PEM. Поддерживаются распространённые ключи OpenSSH `ed25519`, `rsa`, `ecdsa` и PEM-ключи RSA/EC/PRIVATE/ENCRYPTED PRIVATE KEY; в поле нужно вставлять приватный ключ целиком с BEGIN/END, а не публичную строку `ssh-ed25519` или `ssh-rsa`. Способ входа выбирается явно; в режиме ключа пароль можно оставить для `sudo`, если он требуется сервером. Ключ можно вставить, прочитать из файла или буфера обмена и проверить перед сохранением. Основной и дополнительный VPS хранят свои ключи отдельно в защищённом хранилище Android; ключи не отправляются на сервер и не входят в перенос настроек администратора.
|
||||
- **Подключение к готовому серверу:** если сервер уже установлен, приложение проверяет SSH-доступ и главный пароль, показывает отличия и после подтверждения восстанавливает локальные поля. Если серверный профиль владельца был сохранён из переименованного VPN-профиля, это название также вернётся в приложение; стандартные VPN 1/2/3 локальное имя не затирают. Этот режим работает только от сервера к приложению и ничего не записывает на сервер.
|
||||
- **Подключение к готовому серверу:** в «Деплой» выберите «Подключить», заполните SSH-доступ и главный пароль через значки ключа и шестерёнки. Приложение проверяет SSH-доступ и главный пароль, показывает отличия и после подтверждения восстанавливает локальные поля. Если серверный профиль владельца был сохранён из переименованного VPN-профиля, это название также вернётся в приложение; стандартные VPN 1/2/3 локальное имя не затирают. Этот режим работает только от сервера к приложению и ничего не записывает на сервер.
|
||||
- **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит пользовательских паролей, 16-символьную генерацию, ручное задание пароля с проверками, привязку к устройству и срок действия. Клиентов можно создавать, импортировать, экспортировать, отключать, продлевать, отвязывать, удалять и менять им пароль из приложения или Telegram-бота.
|
||||
- **Горячее обновление WRAP-ключей:** создание, удаление и истечение паролей обновляют набор WRAP-ключей на сервере без перезапуска ядра.
|
||||
- **Исключения приложений и адресов:** ЧС и БС хранят независимые наборы приложений, доменов, IPv4-адресов и подсетей. В ЧС выбранное работает напрямую, в БС — направляется в VPN; точные домены преобразуются в их текущие IPv4-маршруты при запуске VPN.
|
||||
@@ -119,14 +120,14 @@ SOCKS5: приложение цепочек → 127.0.0.1:1080 → userspace Wir
|
||||
2. Установите приложение на Android-смартфон. Основной ориентир совместимости — Android 10+.
|
||||
3. Подготовьте домен или IP сервера, SSH-логин и SSH-пароль.
|
||||
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` для управления доступом.
|
||||
8. Нажмите **«Установить»** и дождитесь завершения деплоя.
|
||||
9. Во вкладке **«Туннель»** укажите IP/домен сервера, VK-хеши, пароль подключения и количество потоков.
|
||||
10. Нажмите **«Подключить»** предварительно выдав все необходимые разрешения приложению.
|
||||
5. Откройте **WDTT Plus**, перейдите во вкладку **«Деплой»** и выберите **«Установить»**.
|
||||
6. Нажмите **«Установка сервера»**: мастер запросит SSH-доступ и проверит VPS без изменений на нём. Для уже работающего сервера можно сразу выбрать **«Подключить»** — мастер установки не требуется. На заполненном профиле **«Обновить сервер»** проверит VPS и предложит способ обновления; **«Изменить настройки»** откроет мастер с текущими значениями. После успешной первой установки SSH-доступ и параметры сохраняются автоматически. Если «Туннель» ещё не заполнен, приложение выбирает **«Вручную»** и записывает адрес, пароль администратора и порты; добавьте ВК-хеши в настройках. После закрытия данных сервера и отсчёта таймера откроется вкладка **«Туннель»**, без открытия окна настроек. Если вы уже перешли в другой раздел или окно, автоматический переход отменяется, а заполнение подключения сохраняется. Уже заданное подключение сохраняется. Обновление и переустановка не меняют подключение и оставляют вас в **«Деплое»**.
|
||||
7. Если VPS чистый, пароль администратора WDTT будет создан автоматически. Его можно изменить, сгенерировать заново или скопировать прямо из поля. Если найдены прежние данные, понадобится существующий пароль; неизвестная установка не будет автоматически заменена.
|
||||
8. Оставьте стандартные DNS и порты либо укажите свои. Telegram-бот необязателен: можно пропустить его настройку. Подтвердите установку и дождитесь завершения.
|
||||
9. После первой установки приложение один раз покажет данные сервера. Сохраните их; подключение владельца уже заполнено в **«Туннеле»**, а **«Деплой»** вернётся к компактному виду.
|
||||
10. Добавьте VK-хеши во вкладке **«Туннель»**, если их ещё нет, и нажмите **«Подключить»**, предварительно выдав необходимые разрешения.
|
||||
|
||||
Если на сервере уже есть установленный WDTT Plus, приложение покажет предупреждение перед деплоем. Режим **«Обновить с сохранением»** заменит серверный бинарник и применит настройки из текущих полей деплоя, сохранив выданные ссылки, привязки устройств, историю и WireGuard-ключи. Режим **«Начать с нуля»** удалит серверные данные WDTT Plus и развернёт чистую установку.
|
||||
Если на сервере уже есть установленный WDTT Plus, приложение покажет предупреждение перед деплоем. Режим **«Обновить с сохранением»** заменит серверный бинарник и применит параметры WDTT и параметров установки, сохранив выданные ссылки, привязки устройств, историю и WireGuard-ключи. Режим **«Начать с нуля»** удалит серверные данные WDTT Plus и развернёт чистую установку.
|
||||
|
||||
Для переноса на другой сервер во вкладке **«Деплой»** используйте блок **«Резервные копии и перенос»**. Частичный экспорт сохраняет базу WDTT Plus: профиль владельца, Telegram-настройки, клиентов, привязки устройств, статистику и историю. Полный экспорт дополнительно требует и сохраняет WireGuard-ключи сервера; формат v3 также переносит сохранённый профиль выходного IP, прокси и VPN/WireGuard. Старые `wdtt://` ссылки останутся рабочими без перевыдачи, если в них был домен, DNS указывает на новый сервер и сохранены прежние порты; для ссылок со старым IP или при смене портов создайте новые. Импорт можно выполнить при деплое или на работающем сервере: режим **«Заменить»** подходит для переезда, режим **«Добавить»** переносит отсутствующие записи, проверяет конфликты устройств и назначает свободные внутренние IP. Перед изменением создаются постоянная и транзакционная страховочные копии, после импорта проверяются данные и служба, а при ошибке выполняется откат.
|
||||
|
||||
@@ -176,7 +177,7 @@ VPN-подключения.
|
||||
- `9000/udp` — локальный порт Android-клиента.
|
||||
- `10.66.66.0/24` — подсеть WireGuard-устройств.
|
||||
|
||||
Если включить ручное управление портами, эти значения можно изменить в **«Секретах»**.
|
||||
Если включить ручное управление портами, порты DTLS и WireGuard можно изменить в **параметрах установки**; SSH-порт находится в настройках **SSH**.
|
||||
|
||||
## Резервное копирование сервера
|
||||
|
||||
@@ -296,7 +297,7 @@ Telegram-бот умеет посмотреть статус и диагност
|
||||
>
|
||||
> Авторы и участники этой модификации не призывают использовать WDTT Plus для обхода блокировок или нарушения правил каких-либо платформ, а также не несут ответственности за финальные сценарии использования утилиты пользователями. Любые специфические технические особенности приложения описаны как исследование сетевой архитектуры и протоколов.
|
||||
>
|
||||
> Проект является полностью некоммерческим, не содержит платных функций, скрытых подписок или коммерческой выгоды.
|
||||
> Публичное приложение и самостоятельный сервер доступны бесплатно и не требуют подписки для самостоятельного использования.
|
||||
|
||||
## Для разработки
|
||||
|
||||
|
||||
+42
-6
@@ -46,7 +46,8 @@ plugins {
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
}
|
||||
|
||||
val appVersionName = "18"
|
||||
val appVersionName = "19"
|
||||
val appVersionCode = 19
|
||||
val releaseApkBaseName = "WDTT-Plus"
|
||||
|
||||
val localProperties = Properties()
|
||||
@@ -81,6 +82,20 @@ val releaseCredentialsComplete =
|
||||
.all { !localProperties.getProperty(it).isNullOrBlank() }
|
||||
val localReleaseAuditRequired = rootProject.file("release.keystore").exists()
|
||||
val localReleaseAudit = rootProject.file("release-audit")
|
||||
val localClientModeProperties = Properties()
|
||||
val localClientModeFile = rootProject.file(".codex-local/android-build/client-mode.properties")
|
||||
if (localClientModeFile.isFile) {
|
||||
localClientModeProperties.load(localClientModeFile.inputStream())
|
||||
}
|
||||
val localReleaseLike = localClientModeProperties.getProperty("release_like")
|
||||
?.trim()
|
||||
?.toBooleanStrictOrNull()
|
||||
?: false
|
||||
val localDiagnostics = localClientModeProperties.getProperty("diagnostics")
|
||||
?.trim()?.toBooleanStrictOrNull() ?: false
|
||||
// High-volume per-path measurements are opt-in even in local diagnostic builds.
|
||||
val transportDiagnostics = localDiagnostics && providers.gradleProperty("TRANSPORT_METRICS")
|
||||
.map { it.toBooleanStrict() }.getOrElse(false)
|
||||
|
||||
android {
|
||||
namespace = "com.wdtt.plus"
|
||||
@@ -90,9 +105,10 @@ android {
|
||||
applicationId = "com.wdtt.plus"
|
||||
minSdk = 28
|
||||
targetSdk = 35
|
||||
versionCode = 18
|
||||
versionCode = 19
|
||||
versionName = appVersionName
|
||||
buildConfigField("String", "MOD_RELEASE_DATE", "\"11.09.2026\"")
|
||||
buildConfigField("String", "MOD_RELEASE_DATE", "\"29.09.2026\"")
|
||||
buildConfigField("boolean", "TRANSPORT_DIAGNOSTICS", transportDiagnostics.toString())
|
||||
buildConfigField("String", "WDTT_PLUS_DOMAIN", buildConfigString(wdttPlusDomain))
|
||||
manifestPlaceholders["wdttPlusDomain"] = wdttPlusDomain
|
||||
manifestPlaceholders["appLabel"] = "WDTT Plus"
|
||||
@@ -151,9 +167,12 @@ android {
|
||||
}
|
||||
create("preview") {
|
||||
initWith(getByName("release"))
|
||||
versionNameSuffix = "-preview-ui2"
|
||||
manifestPlaceholders["appLabel"] = "WDTT Plus Preview"
|
||||
buildConfigField("boolean", "REMOTE_ACTION_PREVIEW", "true")
|
||||
if (!localReleaseLike) {
|
||||
versionNameSuffix = "-preview-ui2"
|
||||
}
|
||||
manifestPlaceholders["appLabel"] =
|
||||
if (localReleaseLike) "WDTT Plus" else "WDTT Plus Preview"
|
||||
buildConfigField("boolean", "REMOTE_ACTION_PREVIEW", (!localReleaseLike).toString())
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
@@ -188,6 +207,10 @@ android {
|
||||
getByName("main") {
|
||||
jniLibs.setSrcDirs(listOf("src/main/jniLibs"))
|
||||
}
|
||||
val privateAdapterTests = rootProject.file(".codex-local/android-vk-release-tests")
|
||||
if (privateAdapterTests.isDirectory) {
|
||||
getByName("test") { kotlin.directories.add(privateAdapterTests.absolutePath) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,6 +241,7 @@ tasks.register<Exec>("buildNativeClient") {
|
||||
inputs.files(fileTree(goClientDir.asFile) {
|
||||
include("**/*.go", "go.mod", "go.sum")
|
||||
})
|
||||
inputs.files(fileTree(rootProject.file("pathprobe")) { include("**/*.go", "go.mod") })
|
||||
outputs.files(
|
||||
listOf("arm64-v8a", "armeabi-v7a", "x86_64").map { abi ->
|
||||
jniLibsDir.file("$abi/libclient.so")
|
||||
@@ -336,15 +360,24 @@ tasks.matching {
|
||||
dependsOn("buildNativeClient")
|
||||
}
|
||||
|
||||
val verifyVersionSynchronization = tasks.register<Exec>("verifyVersionSynchronization") {
|
||||
group = "verification"
|
||||
description = "Fails when Android, wdtt-server, installers, or the release changelog use different versions."
|
||||
workingDir(rootProject.layout.projectDirectory.asFile)
|
||||
commandLine("bash", rootProject.file("server-installer/tests/version_sync_test.sh").absolutePath)
|
||||
}
|
||||
|
||||
tasks.register<Exec>("buildServerAsset") {
|
||||
group = "build"
|
||||
description = "Builds the Linux wdtt-server binary embedded into Android deploy assets."
|
||||
dependsOn(verifyVersionSynchronization)
|
||||
workingDir(rootProject.layout.projectDirectory.asFile)
|
||||
|
||||
inputs.files(fileTree(rootProject.layout.projectDirectory.asFile) {
|
||||
include("*.go", "go.mod", "go.sum")
|
||||
exclude("build/**", "app/**", "go_client/**")
|
||||
})
|
||||
inputs.files(fileTree(rootProject.file("pathprobe")) { include("**/*.go", "go.mod") })
|
||||
outputs.file(serverAssetFile)
|
||||
|
||||
commandLine(
|
||||
@@ -473,6 +506,9 @@ tasks.configureEach {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
implementation("androidx.webkit:webkit:1.13.0")
|
||||
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
|
||||
implementation("androidx.core:core-ktx:1.15.0")
|
||||
implementation(platform("androidx.compose:compose-bom:2024.12.01"))
|
||||
implementation("androidx.compose.ui:ui")
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
@@ -199,6 +200,25 @@
|
||||
android:resource="@xml/vpn_widget_compact_info" />
|
||||
</receiver>
|
||||
|
||||
<service android:name="com.wdtt.plus.vk.NativeVkBrokerService" android:exported="false" />
|
||||
<activity android:name="com.wdtt.plus.vk.ModernVkProfile0Activity"
|
||||
android:exported="false" android:process=":local_web_auth_p0" android:launchMode="singleTop"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar" android:configChanges="orientation|screenSize|keyboardHidden|uiMode" />
|
||||
<activity android:name="com.wdtt.plus.vk.ModernVkProfile1Activity"
|
||||
android:exported="false" android:process=":local_web_auth_p1" android:launchMode="singleTop"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar" android:configChanges="orientation|screenSize|keyboardHidden|uiMode" />
|
||||
<activity android:name="com.wdtt.plus.vk.ModernVkProfile2Activity"
|
||||
android:exported="false" android:process=":local_web_auth_p2" android:launchMode="singleTop"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar" android:configChanges="orientation|screenSize|keyboardHidden|uiMode" />
|
||||
<activity android:name="com.wdtt.plus.vk.NativeVkProfile0Activity"
|
||||
android:exported="false" android:process=":local_web_auth_p0" android:launchMode="singleTop"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar" android:configChanges="orientation|screenSize|keyboardHidden|uiMode" />
|
||||
<activity android:name="com.wdtt.plus.vk.NativeVkProfile1Activity"
|
||||
android:exported="false" android:process=":local_web_auth_p1" android:launchMode="singleTop"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar" android:configChanges="orientation|screenSize|keyboardHidden|uiMode" />
|
||||
<activity android:name="com.wdtt.plus.vk.NativeVkProfile2Activity"
|
||||
android:exported="false" android:process=":local_web_auth_p2" android:launchMode="singleTop"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar" android:configChanges="orientation|screenSize|keyboardHidden|uiMode" />
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -2,16 +2,16 @@
|
||||
# ==============================================================================
|
||||
# WDTT Plus Server — Универсальный установщик для VPS
|
||||
# Поддержка: Debian 11+, Ubuntu 20.04+, CentOS/RHEL/Fedora/AlmaLinux/Rocky
|
||||
# Версия: 3.11 | Дата: 2026-09-06
|
||||
# Версия: 3.13 | Дата: 2026-09-12
|
||||
# NAT: MASQUERADE через iptables
|
||||
# WG: порт 56001 (не конфликтует с существующим WG на 51820)
|
||||
# DTLS: порт 56000
|
||||
# ==============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
readonly SCRIPT_VERSION="3.11"
|
||||
readonly SCRIPT_VERSION="3.13"
|
||||
readonly WDTT_DEPLOY_CONTRACT_VERSION="1"
|
||||
readonly WDTT_SERVER_VERSION="17"
|
||||
readonly WDTT_SERVER_VERSION="19"
|
||||
readonly WDTT_SERVER_BINARY_PATH="/usr/local/bin/wdtt-server"
|
||||
readonly WDTT_SYSTEMD_UNIT_PATH="/etc/systemd/system/wdtt.service"
|
||||
readonly WDTT_ANDROID_DEPLOY_MARKER="Managed by WDTT Plus Android deploy"
|
||||
|
||||
@@ -88,6 +88,13 @@ data class AccessProfileUpdate(
|
||||
val link: RemoteDocumentLink,
|
||||
)
|
||||
|
||||
/** Ephemeral presentation for one exact remote binding; never persisted as a launch target. */
|
||||
data class RemoteProfileAction(
|
||||
val binding: String,
|
||||
val expiresAtSeconds: Long,
|
||||
val action: RemoteUiAction,
|
||||
)
|
||||
|
||||
data class AccessLifecycleStatus(
|
||||
val allowConnect: Boolean,
|
||||
val actionAvailable: Boolean,
|
||||
@@ -108,6 +115,7 @@ data class AccessLifecycleStatus(
|
||||
val profileUpdate: AccessProfileUpdate? = null,
|
||||
val cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable,
|
||||
val exchange: RemoteProfileExchange? = null,
|
||||
val profileAction: RemoteProfileAction? = null,
|
||||
)
|
||||
|
||||
data class StoredAccessLifecycle(
|
||||
|
||||
@@ -72,7 +72,7 @@ object AccessLifecycleCoordinator {
|
||||
val currentNow = System.currentTimeMillis()
|
||||
if (!current.capability.available) return@withLock AccessLifecycleRefreshResult.Unmanaged
|
||||
if (current.status?.continuationAvailable != false) {
|
||||
syncPendingProfileValues(store, profile, current.capability)
|
||||
syncPendingProfileValues(appContext, store, profile, current.capability)
|
||||
}
|
||||
if (
|
||||
!force &&
|
||||
@@ -92,6 +92,7 @@ object AccessLifecycleCoordinator {
|
||||
setRefreshing(profile, true)
|
||||
try {
|
||||
val received = AccessLifecycleGateway.fetch(
|
||||
context = appContext,
|
||||
capability = current.capability,
|
||||
device = store.getOrCreateConnectDeviceId(),
|
||||
client = BuildConfig.VERSION_NAME,
|
||||
@@ -119,7 +120,7 @@ object AccessLifecycleCoordinator {
|
||||
}
|
||||
if (received.continuationAvailable != false) {
|
||||
try {
|
||||
syncPendingProfileValues(store, profile, effectiveCapability)
|
||||
syncPendingProfileValues(appContext, store, profile, effectiveCapability)
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (error: Exception) {
|
||||
@@ -276,6 +277,7 @@ object AccessLifecycleCoordinator {
|
||||
} ?: "Действие сейчас недоступно."
|
||||
}
|
||||
val target = AccessLifecycleGateway.begin(
|
||||
context = context.applicationContext,
|
||||
capability = current.capability,
|
||||
device = store.getOrCreateConnectDeviceId(),
|
||||
client = BuildConfig.VERSION_NAME,
|
||||
@@ -374,6 +376,7 @@ object AccessLifecycleCoordinator {
|
||||
}
|
||||
store.markProfileValuesSyncPending(profile)
|
||||
val updatedExchange = AccessLifecycleGateway.submitProfileValues(
|
||||
context = context.applicationContext,
|
||||
capability = current.capability,
|
||||
token = exchange.submitToken,
|
||||
device = store.getOrCreateConnectDeviceId(),
|
||||
@@ -416,6 +419,7 @@ object AccessLifecycleCoordinator {
|
||||
"Действие для этого профиля больше недоступно."
|
||||
}
|
||||
val link = AccessLifecycleGateway.invokeProfileAction(
|
||||
context = appContext,
|
||||
capability = current.capability,
|
||||
token = exchange.actionToken,
|
||||
device = store.getOrCreateConnectDeviceId(),
|
||||
@@ -431,6 +435,7 @@ object AccessLifecycleCoordinator {
|
||||
client = BuildConfig.VERSION_NAME,
|
||||
system = Build.VERSION.RELEASE.orEmpty(),
|
||||
localBindings = store.remoteDocumentBindings(),
|
||||
context = appContext,
|
||||
)
|
||||
require(delivery.kind == RemoteDocumentKind.UPDATE) {
|
||||
"WDTT Plus вернул неподходящее обновление профиля."
|
||||
@@ -458,6 +463,7 @@ object AccessLifecycleCoordinator {
|
||||
}
|
||||
|
||||
private suspend fun syncPendingProfileValues(
|
||||
context: Context,
|
||||
store: SettingsStore,
|
||||
profile: Int,
|
||||
capability: RemoteAccessCapability,
|
||||
@@ -473,6 +479,7 @@ object AccessLifecycleCoordinator {
|
||||
.take(4)
|
||||
runCatching {
|
||||
val updatedExchange = AccessLifecycleGateway.submitProfileValues(
|
||||
context = context,
|
||||
capability = capability,
|
||||
token = exchange.submitToken,
|
||||
device = store.getOrCreateConnectDeviceId(),
|
||||
@@ -506,6 +513,7 @@ object AccessLifecycleCoordinator {
|
||||
client = BuildConfig.VERSION_NAME,
|
||||
system = Build.VERSION.RELEASE.orEmpty(),
|
||||
localBindings = store.remoteDocumentBindings(),
|
||||
context = appContext,
|
||||
)
|
||||
require(delivery.kind == RemoteDocumentKind.UPDATE) {
|
||||
"WDTT Plus вернул неподходящее обновление профиля."
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
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
|
||||
|
||||
enum class AccessLifecycleFailureKind {
|
||||
REJECTED,
|
||||
@@ -34,6 +34,7 @@ object AccessLifecycleGateway {
|
||||
)
|
||||
|
||||
suspend fun fetch(
|
||||
context: Context,
|
||||
capability: RemoteAccessCapability,
|
||||
device: String,
|
||||
client: String,
|
||||
@@ -41,6 +42,7 @@ object AccessLifecycleGateway {
|
||||
timezone: String,
|
||||
profileRevision: Long,
|
||||
): AccessLifecycleStatus = request(
|
||||
context = context,
|
||||
capability = capability,
|
||||
device = device,
|
||||
client = client,
|
||||
@@ -51,6 +53,7 @@ object AccessLifecycleGateway {
|
||||
).let(::parseStatus)
|
||||
|
||||
suspend fun begin(
|
||||
context: Context,
|
||||
capability: RemoteAccessCapability,
|
||||
device: String,
|
||||
client: String,
|
||||
@@ -58,6 +61,7 @@ object AccessLifecycleGateway {
|
||||
timezone: String,
|
||||
profileRevision: Long,
|
||||
): RemoteLaunchTarget = request(
|
||||
context = context,
|
||||
capability = capability,
|
||||
device = device,
|
||||
client = client,
|
||||
@@ -68,6 +72,7 @@ object AccessLifecycleGateway {
|
||||
).let(::parseLaunchTarget)
|
||||
|
||||
suspend fun submitProfileValues(
|
||||
context: Context,
|
||||
capability: RemoteAccessCapability,
|
||||
token: String,
|
||||
device: String,
|
||||
@@ -78,6 +83,7 @@ object AccessLifecycleGateway {
|
||||
): RemoteProfileExchange =
|
||||
parseExchangeResult(
|
||||
request(
|
||||
context = context,
|
||||
capability = capability,
|
||||
device = device,
|
||||
client = client,
|
||||
@@ -90,6 +96,7 @@ object AccessLifecycleGateway {
|
||||
)
|
||||
|
||||
suspend fun invokeProfileAction(
|
||||
context: Context,
|
||||
capability: RemoteAccessCapability,
|
||||
token: String,
|
||||
device: String,
|
||||
@@ -98,6 +105,7 @@ object AccessLifecycleGateway {
|
||||
timezone: String,
|
||||
profileRevision: Long,
|
||||
): RemoteDocumentLink = request(
|
||||
context = context,
|
||||
capability = capability,
|
||||
device = device,
|
||||
client = client,
|
||||
@@ -108,6 +116,7 @@ object AccessLifecycleGateway {
|
||||
).let(::parseActionDocument)
|
||||
|
||||
private suspend fun request(
|
||||
context: Context,
|
||||
capability: RemoteAccessCapability,
|
||||
device: String,
|
||||
client: String,
|
||||
@@ -154,7 +163,23 @@ object AccessLifecycleGateway {
|
||||
val relayAllowed = operation == "status" && action.isBlank() && values.isEmpty() &&
|
||||
TunnelManager.isUpdateRelayAvailable()
|
||||
try {
|
||||
if (relayAllowed) {
|
||||
when (
|
||||
val relayed = TunnelManager.postOpaqueHttpsStatusThroughTunnel(
|
||||
capability.url,
|
||||
payload,
|
||||
)
|
||||
) {
|
||||
is OpaqueHttpsRelayResult.Success -> return@withContext HttpResponse(
|
||||
status = relayed.status,
|
||||
body = relayed.body,
|
||||
codeHint = relayed.codeHint,
|
||||
).bodyOrThrow(operation)
|
||||
is OpaqueHttpsRelayResult.Unavailable -> Unit
|
||||
}
|
||||
}
|
||||
requestDirect(
|
||||
context = context,
|
||||
url = capability.url,
|
||||
payload = payload,
|
||||
connectTimeoutMs = if (relayAllowed) 2_500 else 7_000,
|
||||
@@ -164,31 +189,13 @@ object AccessLifecycleGateway {
|
||||
throw cancelled
|
||||
} catch (error: Exception) {
|
||||
if (error is IllegalStateException) throw error
|
||||
if (relayAllowed) {
|
||||
when (
|
||||
val relayed = TunnelManager.postOpaqueHttpsStatusThroughTunnel(
|
||||
capability.url,
|
||||
payload,
|
||||
)
|
||||
) {
|
||||
is OpaqueHttpsRelayResult.Success -> HttpResponse(
|
||||
status = relayed.status,
|
||||
body = relayed.body,
|
||||
codeHint = relayed.codeHint,
|
||||
).bodyOrThrow(operation)
|
||||
is OpaqueHttpsRelayResult.Unavailable -> throw IllegalStateException(
|
||||
"Не удалось проверить состояние доступа к профилю. " +
|
||||
"Сохранённые настройки подключения не изменены.",
|
||||
)
|
||||
}
|
||||
} else {
|
||||
throw IllegalStateException(requestFailureMessage(operation, action))
|
||||
}
|
||||
throw IllegalStateException(requestFailureMessage(operation, action))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestDirect(
|
||||
context: Context,
|
||||
url: String,
|
||||
payload: ByteArray,
|
||||
connectTimeoutMs: Int,
|
||||
@@ -196,7 +203,7 @@ object AccessLifecycleGateway {
|
||||
): HttpResponse {
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
connection = URL(url).openConnection() as HttpURLConnection
|
||||
connection = openDefaultHttpConnection(context, url)
|
||||
connection.requestMethod = "POST"
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.connectTimeout = connectTimeoutMs
|
||||
@@ -352,9 +359,25 @@ object AccessLifecycleGateway {
|
||||
profileUpdate = update,
|
||||
cachedAction = cachedAction,
|
||||
exchange = exchange,
|
||||
profileAction = root.optJSONObject("profile_action")?.let(::parseProfileAction),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun parseProfileAction(source: JSONObject): RemoteProfileAction? = runCatching {
|
||||
val binding = source.optString("binding").trim()
|
||||
val expires = source.optLong("expires", 0)
|
||||
val title = source.optString("title").trim().take(120)
|
||||
val message = source.optString("message").trim().take(2400)
|
||||
val label = source.optString("label").trim().take(80)
|
||||
require(binding.isNotBlank() && binding.length <= 256 && expires > 0)
|
||||
require(title.isNotBlank() && message.isNotBlank() && label.isNotBlank())
|
||||
RemoteProfileAction(
|
||||
binding = binding,
|
||||
expiresAtSeconds = expires,
|
||||
action = RemoteUiAction(title, message, label, parseLaunchTarget(source.toString())),
|
||||
)
|
||||
}.getOrNull()
|
||||
|
||||
internal fun parseLaunchTarget(body: String): RemoteLaunchTarget {
|
||||
val root = parseRoot(body)
|
||||
val primary = root.optString("url").trim()
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
internal fun connectionModeTitle(streamOnly: Boolean): String = if (streamOnly) "TCP/TLS" else "UDP"
|
||||
|
||||
internal fun connectionPathTitle(path: String): String? = when (path) {
|
||||
"udp" -> "UDP"
|
||||
"tcp" -> "TCP"
|
||||
"tls" -> "TLS"
|
||||
"tls-front" -> "TLS · внешний SNI"
|
||||
"h2" -> "MASQUE · HTTP/2"
|
||||
"h3" -> "MASQUE · HTTP/3"
|
||||
else -> null
|
||||
}
|
||||
|
||||
internal data class ConnectionEventLog(val key: String, val message: String, val warning: Boolean = false)
|
||||
|
||||
internal fun connectionEventLog(event: String, networkEpoch: Long): ConnectionEventLog? {
|
||||
val parts = event.trim().split(' ')
|
||||
return when (parts.firstOrNull()) {
|
||||
"TRY" -> {
|
||||
if (parts.size != 2) return null
|
||||
val path = connectionPathTitle(parts[1]) ?: return null
|
||||
ConnectionEventLog("try_${parts[1]}", "Пробуем подключиться через $path")
|
||||
}
|
||||
"READY" -> {
|
||||
if (parts.size != 3 || parts[1].toLongOrNull() != networkEpoch) return null
|
||||
val path = connectionPathTitle(parts[2]) ?: return null
|
||||
ConnectionEventLog("ready_${parts[2]}", "Сервер ответил · $path ✓")
|
||||
}
|
||||
"FAILED" -> {
|
||||
if (parts.size != 6 || parts[1].toLongOrNull() != networkEpoch) return null
|
||||
val path = connectionPathTitle(parts[2]) ?: return null
|
||||
val stage = when (parts[3]) {
|
||||
"turn" -> "подключение к ретранслятору"
|
||||
"dtls" -> "защищённое соединение с сервером"
|
||||
"registration" -> "регистрация на сервере"
|
||||
"protocol" -> "согласование передачи данных"
|
||||
"confirmation" -> "проверка ответа сервера"
|
||||
"active" -> "работа канала"
|
||||
else -> return null
|
||||
}
|
||||
val reason = when (parts[4]) {
|
||||
"timeout" -> "истекло время ожидания"
|
||||
"network" -> "сетевая ошибка"
|
||||
"closed" -> "канал закрыт"
|
||||
"limit" -> "достигнут лимит подключений"
|
||||
"capacity" -> "ретранслятор занят"
|
||||
"auth" -> "доступ не подтверждён"
|
||||
"protocol" -> "несовместимые параметры передачи"
|
||||
"interrupted" -> "попытка прервана"
|
||||
else -> return null
|
||||
}
|
||||
val elapsed = parts[5].toLongOrNull()?.takeIf { it >= 0 } ?: return null
|
||||
ConnectionEventLog("failed_${parts[2]}_${parts[3]}_${parts[4]}",
|
||||
"$path: $stage — $reason (${elapsed / 1000} с).", warning = true)
|
||||
}
|
||||
"UDP_PARTIAL" -> {
|
||||
if (parts.size != 2 || parts[1].toLongOrNull() != networkEpoch) return null
|
||||
ConnectionEventLog("udp_partial", "Один UDP-канал не ответил. Остальные UDP-каналы работают; восстанавливаем недостающие.", warning = true)
|
||||
}
|
||||
"UDP_BACKOFF" -> {
|
||||
if (parts.size != 2 || parts[1].toLongOrNull() != networkEpoch) return null
|
||||
ConnectionEventLog("udp_backoff", "Рабочих UDP-каналов нет. Пробуем TCP/TLS; новые проверки внешнего UDP отложены на 5 минут.", warning = true)
|
||||
}
|
||||
"PAUSED" -> ConnectionEventLog("paused", "Лимит попыток исчерпан. Смените сеть или подключитесь заново.", warning = true)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
internal fun connectionModeDiagnostic(streamOnly: Boolean): DeviceCheckItem = DeviceCheckItem(
|
||||
title = "Подключение",
|
||||
status = connectionModeTitle(streamOnly),
|
||||
details = (if (streamOnly) "Используются TLS и TCP. Внешние UDP и HTTP/3 запрещены; UDP внутри VPN остаётся доступен. "
|
||||
else "Сначала проверяется UDP, при недоступности — TCP/TLS. Пауза для новых проверок UDP действует, когда рабочих UDP-каналов нет. Отказ отдельного канала не отключает остальные. Рабочий резерв не заменяется фоновыми проверками. ") +
|
||||
"В обоих режимах проверяется ответ сервера и восстанавливаются потерянные каналы. После серии неудач попытки приостанавливаются.",
|
||||
recommendation = "Приложение не определяет блокировку SIM. Если интернет пропал полностью, проверьте доступ без VPN.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** Only a short retry deadline is cached, never a permanent transport preference. */
|
||||
internal object ConnectionNetwork {
|
||||
private const val udpPauseMs = 5 * 60_000L
|
||||
|
||||
fun underlying(context: Context): Network? {
|
||||
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return null
|
||||
fun usable(n: Network): Boolean = cm.getNetworkCapabilities(n)?.let {
|
||||
it.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
|
||||
it.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
|
||||
} == true
|
||||
return cm.activeNetwork?.takeIf(::usable) ?: cm.allNetworks.firstOrNull(::usable)
|
||||
}
|
||||
|
||||
fun cacheKey(context: Context, params: TunnelParams): String? {
|
||||
val network = underlying(context) ?: return null
|
||||
// Digest is private local data. It is never exported or written to logs.
|
||||
val identity = listOf(
|
||||
network.networkHandle, params.profileIndex, params.peer, params.vkHashes,
|
||||
params.secondaryVkHash, params.connectionPassword, params.rtTurnSni,
|
||||
params.rtMasque, params.rtNetwork, params.mode,
|
||||
).joinToString("\u0000")
|
||||
return MessageDigest.getInstance("SHA-256").digest(identity.toByteArray())
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
fun udpBackoffSeconds(context: Context, key: String?, now: Long = System.currentTimeMillis()): Long {
|
||||
if (key == null) return 0
|
||||
val until = context.getSharedPreferences("connection_retry", Context.MODE_PRIVATE).getLong(key, 0L)
|
||||
return ((until - now).coerceIn(0L, udpPauseMs) + 999L) / 1_000L
|
||||
}
|
||||
|
||||
fun noteUdpFailure(context: Context, key: String?) {
|
||||
if (key == null) return
|
||||
val prefs = context.getSharedPreferences("connection_retry", Context.MODE_PRIVATE)
|
||||
val now = System.currentTimeMillis()
|
||||
val edit = prefs.edit()
|
||||
prefs.all.forEach { (name, value) ->
|
||||
if (value !is Long || value <= now || prefs.all.size > 128) edit.remove(name)
|
||||
}
|
||||
edit.putLong(key, now + udpPauseMs).apply()
|
||||
}
|
||||
|
||||
fun noteReady(context: Context, key: String?, kind: String) {
|
||||
if (key != null && kind == "udp") context.getSharedPreferences("connection_retry", Context.MODE_PRIVATE)
|
||||
.edit().remove(key).apply()
|
||||
}
|
||||
|
||||
// These small HTTPS requests are bound to the underlying network, never to
|
||||
// the VPN. Failure alone is inconclusive (including Android lockdown).
|
||||
fun reachable(network: Network, host: String): Boolean = runCatching {
|
||||
val connection = network.openConnection(URL("https://$host/")) as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = 3_000
|
||||
connection.readTimeout = 3_000
|
||||
connection.requestMethod = "HEAD"
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.responseCode in 100..599
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
/** Unknown accessibility is not an outage. Only loss of both previously
|
||||
* reachable controls on the same network can suspend new VPN attempts. */
|
||||
internal class ConnectionReachability {
|
||||
private var confirmed = false
|
||||
private var failures = 0
|
||||
fun observe(first: Boolean, second: Boolean): Boolean {
|
||||
if (first && second) confirmed = true
|
||||
failures = if (first || second) 0 else failures + 1
|
||||
return confirmed && failures >= 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.content.Context
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* Opens a neutral HTTPS request through Android's default network for this UID.
|
||||
*
|
||||
* Deliberately do not bind service traffic to a physical `NOT_VPN` network:
|
||||
* Android's default may be an external VPN that is required to reach the
|
||||
* service. Temporary direct routing for an external continuation is handled
|
||||
* separately and only for the exact backend-provided destinations.
|
||||
*/
|
||||
internal fun openDefaultHttpConnection(
|
||||
@Suppress("UNUSED_PARAMETER") context: Context?,
|
||||
url: String,
|
||||
): HttpURLConnection = URL(url).openConnection() as HttpURLConnection
|
||||
@@ -204,6 +204,7 @@ internal fun processExitHistoryItem(
|
||||
manufacturer: String,
|
||||
backgroundRestricted: Boolean?,
|
||||
batteryOptimizationsIgnored: Boolean?,
|
||||
nowMs: Long = System.currentTimeMillis(),
|
||||
): DeviceCheckItem {
|
||||
val unexpected = history.latestUnexpected
|
||||
if (unexpected == null) {
|
||||
@@ -239,25 +240,47 @@ internal fun processExitHistoryItem(
|
||||
val category = classifyProcessExit(unexpected)
|
||||
val time = processExitTimestamp(unexpected.timestampMs)
|
||||
val marker = recognizedSystemExitMarker(unexpected.description)
|
||||
val newerExpectedEvent = history.latest
|
||||
?.takeIf { it.timestampMs > unexpected.timestampMs }
|
||||
?.let(::classifyProcessExit)
|
||||
?.takeIf {
|
||||
it == ProcessExitCategory.UserAction ||
|
||||
it == ProcessExitCategory.PackageChange ||
|
||||
it == ProcessExitCategory.NormalExit
|
||||
}
|
||||
val laterEventNote = if (newerExpectedEvent != null) {
|
||||
" После этого Android зафиксировал более новое штатное событие, но оно не отменяет найденное неожиданное завершение."
|
||||
} else {
|
||||
""
|
||||
}
|
||||
val markerText = if (marker.isNotBlank()) " Метка оболочки Android: $marker." else ""
|
||||
val commonRecommendation = backgroundRestrictionRecommendation(
|
||||
manufacturer = manufacturer,
|
||||
backgroundRestricted = backgroundRestricted,
|
||||
batteryOptimizationsIgnored = batteryOptimizationsIgnored,
|
||||
)
|
||||
val laterEventNote = history.latest
|
||||
?.takeIf { it.timestampMs > unexpected.timestampMs }
|
||||
?.let { " После этого в истории есть более новое завершение процесса." }.orEmpty()
|
||||
val oldEvent = nowMs - unexpected.timestampMs > 24L * 60L * 60L * 1000L
|
||||
val knownRestriction = backgroundRestricted == true || batteryOptimizationsIgnored == false
|
||||
val settingsPermitted = backgroundRestricted == false && batteryOptimizationsIgnored == true
|
||||
val commonRecommendation = if (settingsPermitted) {
|
||||
"Android сейчас разрешает фоновую работу и исключение из оптимизации батареи. " +
|
||||
"Повторно менять эти разрешения не нужно. Если VPN снова прервётся, " +
|
||||
"сразу скопируйте отчёт устройства и журнал приложения."
|
||||
} else {
|
||||
backgroundRestrictionRecommendation(manufacturer, backgroundRestricted, batteryOptimizationsIgnored)
|
||||
}
|
||||
// Exit history describes a previous process, not the current health of this installation.
|
||||
// REASON_OTHER and vendor descriptions cannot establish a battery-policy cause.
|
||||
val historicalOnly = oldEvent ||
|
||||
(category in setOf(ProcessExitCategory.SystemPolicy, ProcessExitCategory.Unknown) && !knownRestriction)
|
||||
if (historicalOnly) {
|
||||
val description = when (category) {
|
||||
ProcessExitCategory.Crash -> "сбой приложения"
|
||||
ProcessExitCategory.LowMemory -> "остановку при нехватке памяти"
|
||||
ProcessExitCategory.ExcessiveResources -> "остановку из-за использования ресурсов"
|
||||
ProcessExitCategory.Dependency -> "остановку после завершения системного компонента"
|
||||
else -> "завершение основного процесса"
|
||||
}
|
||||
return DeviceCheckItem(
|
||||
title = "Последнее завершение приложения",
|
||||
status = "запись в истории",
|
||||
details = "Android сохранил $description $time.$markerText$laterEventNote " +
|
||||
"Эта запись не подтверждает текущую неисправность VPN и не влияет на итог проверки." +
|
||||
if (marker.isNotBlank()) " По метке оболочки нельзя определить, какие настройки стали причиной." else "",
|
||||
recommendation = if (knownRestriction) {
|
||||
"Актуальные ограничения показаны отдельно в проверке батареи и фоновой работы."
|
||||
} else if (settingsPermitted) commonRecommendation else {
|
||||
"Если VPN работает без обрывов, дополнительных действий не требуется. " +
|
||||
"При повторении сразу сохраните отчёт устройства и журнал приложения."
|
||||
},
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
}
|
||||
|
||||
return when (category) {
|
||||
ProcessExitCategory.SystemPolicy -> DeviceCheckItem(
|
||||
@@ -266,7 +289,7 @@ internal fun processExitHistoryItem(
|
||||
details = "Android завершил основной процесс WDTT Plus $time вне штатной остановки приложения.$markerText$laterEventNote",
|
||||
recommendation = commonRecommendation,
|
||||
severity = DeviceCheckSeverity.Warning,
|
||||
action = DeviceCheckAction.BatterySettings,
|
||||
action = if (knownRestriction) DeviceCheckAction.BatterySettings else null,
|
||||
)
|
||||
ProcessExitCategory.ExcessiveResources -> DeviceCheckItem(
|
||||
title = "Последнее завершение приложения",
|
||||
@@ -967,51 +990,45 @@ object DeviceCompatibility {
|
||||
return pageSizeCompatibilityItem(pageSize, android.os.Process.is64Bit())
|
||||
}
|
||||
|
||||
fun rtNetworkModeItem(context: Context, profile: TunnelProfileSnapshot): DeviceCheckItem {
|
||||
fun masqueModeItem(context: Context, profile: TunnelProfileSnapshot): DeviceCheckItem {
|
||||
val enrollment = inspectRtMasqueEnrollment(
|
||||
File(context.filesDir, RT_MASQUE_CONFIG_FILE_NAME)
|
||||
)
|
||||
return when {
|
||||
!profile.rtNetwork -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
status = "выключен",
|
||||
details = "Используется обычный порядок транспортов; настройки РТ этого профиля не влияют на подключение.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
!profile.rtMasque -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
status = "TURN/TLS и TCP включены · MASQUE выключен",
|
||||
details = "Для активного профиля включён только основной механизм Сети РТ. Регистрация WARP не требуется.",
|
||||
title = "MASQUE",
|
||||
status = "выключен",
|
||||
details = "Используются TURN-пути без дополнительного резерва Cloudflare. Регистрация WARP не требуется.",
|
||||
severity = DeviceCheckSeverity.Ok,
|
||||
)
|
||||
profile.rtMasqueServerBootstrap && !profile.rtMasqueServerAccessReady -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
status = "«Через сервер» настроен не полностью",
|
||||
details = "MASQUE включён, но в активном профиле нет полного SSH-доступа из раздела «Деплой».",
|
||||
recommendation = "Заполните адрес и пароль либо приватный SSH-ключ в «Деплой» или выключите «Через сервер».",
|
||||
profile.rtMasqueServerBootstrap && !profile.rtMasqueServerAccessReady && enrollment == RtMasqueEnrollmentState.Missing -> DeviceCheckItem(
|
||||
title = "MASQUE",
|
||||
status = "«Регистрация по SSH» настроен не полностью",
|
||||
details = "MASQUE включён, но в активном профиле нет полного SSH-доступа в «Деплой → SSH».",
|
||||
recommendation = "Заполните адрес и пароль либо приватный SSH-ключ в «Деплой → SSH» или выключите «Регистрация по SSH».",
|
||||
severity = DeviceCheckSeverity.Warning,
|
||||
)
|
||||
enrollment == RtMasqueEnrollmentState.Invalid -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
title = "MASQUE",
|
||||
status = "регистрация WARP повреждена",
|
||||
details = "Локальный файл регистрации MASQUE не содержит корректной структуры версии 1. Секретные поля в отчёт не включены.",
|
||||
recommendation = "Остановите VPN и выполните «Сбросить регистрацию WARP» в инструкции MASQUE.",
|
||||
severity = DeviceCheckSeverity.Warning,
|
||||
)
|
||||
enrollment == RtMasqueEnrollmentState.Missing -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
title = "MASQUE",
|
||||
status = "MASQUE включён · регистрация ещё не создана",
|
||||
details = "При следующем запуске VPN приложение попробует зарегистрировать отдельное устройство WARP. Прямые TURN-пути продолжат работать во время подготовки.",
|
||||
details = "Регистрация потребуется при первом использовании резерва MASQUE. Она начинается только после перехода к этому резерву; готовность TURN-путей не требует регистрации WARP.",
|
||||
recommendation = if (profile.rtMasqueServerBootstrap) {
|
||||
"Если прямой TLS Cloudflare недоступен, приложение сможет использовать SSH-выход активного профиля."
|
||||
} else {
|
||||
"Если регистрация не выполняется, проверьте журнал MASQUE; при необходимости настройте «Через сервер»."
|
||||
"Если регистрация не выполняется, проверьте журнал MASQUE; при необходимости настройте «Регистрация по SSH»."
|
||||
},
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
else -> DeviceCheckItem(
|
||||
title = "Режим Сеть РТ",
|
||||
status = "MASQUE готов",
|
||||
title = "MASQUE",
|
||||
status = "регистрация WARP сохранена",
|
||||
details = "Структура сохранённой регистрации WARP корректна; при запуске её дополнительно проверит нативный клиент.",
|
||||
severity = DeviceCheckSeverity.Ok,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
/** Provider process initialization. No remote discovery. */
|
||||
interface LocalBuildExtension {
|
||||
fun initializeAuxiliaryProcess(application: Application): Boolean
|
||||
|
||||
@Composable
|
||||
fun Content()
|
||||
}
|
||||
|
||||
object LocalBuildExtensions {
|
||||
private val extension: LocalBuildExtension? by lazy {
|
||||
try {
|
||||
Class.forName("com.wdtt.plus.vk.VkProcessInitializer")
|
||||
.getField("INSTANCE").get(null) as LocalBuildExtension
|
||||
} catch (_: ClassNotFoundException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun initializeAuxiliaryProcess(application: Application): Boolean =
|
||||
extension?.initializeAuxiliaryProcess(application) == true
|
||||
|
||||
@Composable
|
||||
fun Content() {
|
||||
extension?.Content()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.net.Uri
|
||||
import kotlinx.coroutines.CancellationException
|
||||
|
||||
/** Provider-neutral continuation interface for the built-in device adapter. */
|
||||
interface LocalContinuationExtension {
|
||||
/** Optional isolated preview route. The normal continuation remains the default. */
|
||||
val experimentalAvailable: Boolean
|
||||
get() = false
|
||||
|
||||
suspend fun execute(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit,
|
||||
): Uri
|
||||
|
||||
fun offerCallback(uri: Uri?): Boolean
|
||||
|
||||
suspend fun recoverPending(activity: MainActivity): Uri?
|
||||
|
||||
fun acknowledgeDocument(activity: MainActivity, uri: Uri)
|
||||
|
||||
suspend fun executeExperimental(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit,
|
||||
): Uri = throw IllegalStateException("Экспериментальный способ недоступен в этой сборке.")
|
||||
}
|
||||
|
||||
class LocalContinuationCancelledException : CancellationException("Получение из ВК отменено.")
|
||||
|
||||
/** No external mutation was started, so another continuation may be tried safely. */
|
||||
class LocalContinuationSafeFallbackException : IllegalStateException(
|
||||
"Нужен резервный способ получения ВК-хешей.",
|
||||
)
|
||||
|
||||
object LocalContinuationExtensions {
|
||||
private val extension: LocalContinuationExtension? by lazy {
|
||||
runCatching {
|
||||
Class.forName(EXTENSION_CLASS)
|
||||
.getField("INSTANCE")
|
||||
.get(null) as LocalContinuationExtension
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
val available: Boolean
|
||||
get() = extension != null
|
||||
|
||||
val experimentalAvailable: Boolean
|
||||
get() = extension?.experimentalAvailable == true
|
||||
|
||||
suspend fun execute(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit,
|
||||
): Uri {
|
||||
val current = extension
|
||||
?: throw IllegalStateException("Локальное продолжение недоступно в этой сборке.")
|
||||
return try {
|
||||
current.execute(
|
||||
activity,
|
||||
target,
|
||||
deviceId,
|
||||
hasCompleteLocalValues,
|
||||
onProgress,
|
||||
)
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun executeExperimental(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit,
|
||||
): Uri {
|
||||
val current = extension
|
||||
?.takeIf { it.experimentalAvailable }
|
||||
?: throw IllegalStateException("Экспериментальный способ недоступен в этой сборке.")
|
||||
return current.executeExperimental(
|
||||
activity = activity,
|
||||
target = target,
|
||||
deviceId = deviceId,
|
||||
hasCompleteLocalValues = hasCompleteLocalValues,
|
||||
onProgress = onProgress,
|
||||
)
|
||||
}
|
||||
|
||||
fun offerCallback(uri: Uri?): Boolean = extension?.offerCallback(uri) == true
|
||||
|
||||
suspend fun recoverPending(activity: MainActivity): Uri? =
|
||||
extension?.recoverPending(activity)
|
||||
|
||||
fun acknowledgeDocument(activity: MainActivity, uri: Uri) {
|
||||
extension?.acknowledgeDocument(activity, uri)
|
||||
}
|
||||
|
||||
private const val EXTENSION_CLASS = "com.wdtt.plus.vk.VkContinuationExecutor"
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import com.wdtt.plus.ui.BoundedAlertDialog
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -74,10 +76,14 @@ import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.PointerEventType
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.layout.boundsInWindow
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
@@ -101,6 +107,9 @@ import com.wdtt.plus.ui.AppUpdateDialog
|
||||
import com.wdtt.plus.ui.FloatingToolbar
|
||||
import com.wdtt.plus.ui.LogsTab
|
||||
import com.wdtt.plus.ui.SettingsTab
|
||||
import com.wdtt.plus.ui.VK_HASH_AUTO_HELP_TEXT
|
||||
import com.wdtt.plus.ui.HintIconButton
|
||||
import com.wdtt.plus.ui.WdttInlineNotice
|
||||
import com.wdtt.plus.ui.DeployTab
|
||||
import com.wdtt.plus.ui.DeviceCompatibilityDialog
|
||||
import com.wdtt.plus.ui.ExceptionsTab
|
||||
@@ -187,6 +196,9 @@ class MainActivity : ComponentActivity() {
|
||||
@Volatile
|
||||
private var uiReadyForFirstDraw = false
|
||||
private val remoteAuthTabLauncher = AuthTabIntent.registerActivityResultLauncher(this) { result ->
|
||||
if (LocalContinuationExtensions.offerCallback(result.resultUri)) {
|
||||
return@registerActivityResultLauncher
|
||||
}
|
||||
if (result.resultCode != AuthTabIntent.RESULT_OK) return@registerActivityResultLauncher
|
||||
if (RemoteContinuationLauncher.isCancellationCallback(result.resultUri)) {
|
||||
connectActionJob?.cancel()
|
||||
@@ -214,6 +226,13 @@ class MainActivity : ComponentActivity() {
|
||||
super.onStart()
|
||||
activeActivities++
|
||||
ManlCaptchaWebViewManager.checkAndShowPendingCaptcha(this)
|
||||
lifecycleScope.launch {
|
||||
runCatching {
|
||||
LocalContinuationExtensions.recoverPending(this@MainActivity)
|
||||
}.getOrNull()?.let { documentUri ->
|
||||
handleRemoteDocument(documentUri)
|
||||
}
|
||||
}
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
val profiles = AccessLifecycleCoordinator.takePendingExternalRefreshProfiles() +
|
||||
settingsStore.takeAccessLifecycleActionProfiles()
|
||||
@@ -349,7 +368,9 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
}
|
||||
},
|
||||
onStartWdttConnectAction = ::startConnectAction,
|
||||
onStartWdttConnectAction = { profile, continuation ->
|
||||
startConnectAction(profile, continuation)
|
||||
},
|
||||
onCancelWdttConnectAction = ::cancelConnectAction,
|
||||
onSaveWdttConnectManualHashes = ::saveConnectManualHashes,
|
||||
onRestoreWdttConnectHashes = ::restoreConnectHashes,
|
||||
@@ -420,6 +441,16 @@ class MainActivity : ComponentActivity() {
|
||||
RemoteContinuationLauncher.launch(this, target, remoteAuthTabLauncher)
|
||||
}
|
||||
|
||||
internal fun launchLocalContinuation(url: Uri) {
|
||||
AuthTabIntent.Builder()
|
||||
.build()
|
||||
.launch(remoteAuthTabLauncher, url, "wdtt")
|
||||
}
|
||||
|
||||
internal fun acceptLocalContinuationDocument(uri: Uri) {
|
||||
handleRemoteDocument(uri)
|
||||
}
|
||||
|
||||
private fun handleIncomingIntent(intent: Intent?) {
|
||||
when (intent?.action) {
|
||||
Intent.ACTION_VIEW -> {
|
||||
@@ -428,7 +459,9 @@ class MainActivity : ComponentActivity() {
|
||||
externalIntentConsumed = true
|
||||
replaceConsumedIncomingIntent()
|
||||
if (data == null) return
|
||||
if (RemoteDocumentGateway.extractLink(data) != null) {
|
||||
if (LocalContinuationExtensions.offerCallback(data)) {
|
||||
return
|
||||
} else if (RemoteDocumentGateway.extractLink(data) != null) {
|
||||
handleRemoteDocument(data)
|
||||
} else if (
|
||||
data.scheme.equals("wdtt", ignoreCase = true) &&
|
||||
@@ -529,7 +562,7 @@ class MainActivity : ComponentActivity() {
|
||||
WdttTransferCodec.isAdminTransfer(value) -> pendingAdminTransfer = value.trim()
|
||||
WdttTransferCodec.isEncryptedServerBackup(value) ||
|
||||
WdttTransferCodec.documentFormat(value) == "wdtt-server-backup" -> {
|
||||
wdttDeepLinkMessage = "Распознана резервная копия сервера. Она применяется к выбранному серверу во вкладке «Деплой» → «Перенос сервера» → «Импорт»."
|
||||
wdttDeepLinkMessage = "Распознана резервная копия сервера. Она применяется к выбранному серверу во вкладке «Деплой» → «Резервные копии и перенос»."
|
||||
}
|
||||
WdttTransferCodec.documentFormat(value) == "wdtt-plus-admin-settings" -> {
|
||||
wdttDeepLinkMessage = "Распознаны незашифрованные настройки администратора. В целях безопасности импортируется только защищённый файл, созданный в разделе «Получение/Передача»."
|
||||
@@ -544,13 +577,14 @@ class MainActivity : ComponentActivity() {
|
||||
wdttDeepLinkMessage = "Ссылка подключения повреждена или устарела."
|
||||
return
|
||||
}
|
||||
receiveRemoteDocument(link)
|
||||
receiveRemoteDocument(link, completionDocument = uri)
|
||||
}
|
||||
|
||||
private fun receiveRemoteDocument(
|
||||
link: RemoteDocumentLink,
|
||||
localDocument: String? = null,
|
||||
attachmentProfile: Int? = null,
|
||||
completionDocument: Uri? = null,
|
||||
) {
|
||||
if (!remoteDocumentRequests.add(link.url)) return
|
||||
lifecycleScope.launch {
|
||||
@@ -570,6 +604,7 @@ class MainActivity : ComponentActivity() {
|
||||
localBindings = settingsStore.remoteDocumentBindings(),
|
||||
localDocument = document,
|
||||
profileAttachment = profileAttachment,
|
||||
context = this@MainActivity,
|
||||
)
|
||||
val delivery = try {
|
||||
request(
|
||||
@@ -683,6 +718,7 @@ class MainActivity : ComponentActivity() {
|
||||
delivery = delivery,
|
||||
preferredProfile = boundProfile,
|
||||
existingRemoteProfile = boundProfile != null,
|
||||
completionDocument = completionDocument,
|
||||
)
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
@@ -708,6 +744,7 @@ class MainActivity : ComponentActivity() {
|
||||
delivery: RemoteDocumentDelivery? = null,
|
||||
preferredProfile: Int? = null,
|
||||
existingRemoteProfile: Boolean = false,
|
||||
completionDocument: Uri? = null,
|
||||
) {
|
||||
lifecycleScope.launch {
|
||||
val store = SettingsStore(this@MainActivity)
|
||||
@@ -738,6 +775,7 @@ class MainActivity : ComponentActivity() {
|
||||
delivery = delivery,
|
||||
isBoundUpdate = true,
|
||||
existingRemoteProfile = true,
|
||||
completionDocument = completionDocument,
|
||||
)
|
||||
} else if (
|
||||
fromRemoteDocument &&
|
||||
@@ -763,6 +801,7 @@ class MainActivity : ComponentActivity() {
|
||||
delivery,
|
||||
isBoundUpdate = false,
|
||||
existingRemoteProfile = existingRemoteProfile,
|
||||
completionDocument = completionDocument,
|
||||
)
|
||||
}
|
||||
}.onFailure { error ->
|
||||
@@ -783,6 +822,7 @@ class MainActivity : ComponentActivity() {
|
||||
delivery: RemoteDocumentDelivery? = null,
|
||||
isBoundUpdate: Boolean = false,
|
||||
existingRemoteProfile: Boolean = false,
|
||||
completionDocument: Uri? = null,
|
||||
) {
|
||||
lifecycleScope.launch {
|
||||
if (fromRemoteDocument) {
|
||||
@@ -809,6 +849,9 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
}
|
||||
}.onSuccess { result ->
|
||||
completionDocument?.let { document ->
|
||||
LocalContinuationExtensions.acknowledgeDocument(this@MainActivity, document)
|
||||
}
|
||||
val savedProfile = result?.targetProfile ?: plan.targetProfile
|
||||
if (fromRemoteDocument && result != null) {
|
||||
requestTunnelProfileRuntimeUpdate(savedProfile)
|
||||
@@ -826,7 +869,7 @@ class MainActivity : ComponentActivity() {
|
||||
?.hashes
|
||||
.isNullOrBlank()
|
||||
) {
|
||||
append(" Добавьте свой VK-хеш перед запуском соединения.")
|
||||
append(" Добавьте свой ВК-хеш перед запуском соединения.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -888,7 +931,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun startConnectAction(profile: Int, continuation: RemoteContinuation) {
|
||||
private fun startConnectAction(
|
||||
profile: Int,
|
||||
continuation: RemoteContinuation,
|
||||
) {
|
||||
// The dialog can deliver two taps before Compose has rendered the
|
||||
// ExternalAction state. Do not cancel an already running preparation
|
||||
// and start a second browser/login flow: VK treats those parallel
|
||||
@@ -903,69 +949,114 @@ class MainActivity : ComponentActivity() {
|
||||
profile = profile,
|
||||
continuation = continuation,
|
||||
access = access,
|
||||
message = "Подготавливаем безопасный переход в VK..."
|
||||
message = "Подготавливаем безопасный переход в ВК..."
|
||||
)
|
||||
connectActionJob = lifecycleScope.launch {
|
||||
val runningJob = coroutineContext[Job]
|
||||
if (!continuation.available) {
|
||||
wdttConnectFlow = WdttConnectFlow.Failed(
|
||||
continuation.message.ifBlank {
|
||||
"Автоматическое получение сейчас недоступно. Заполните VK-хеши вручную."
|
||||
"Автоматическое получение сейчас недоступно. Заполните ВК-хеши вручную."
|
||||
}
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
var tunnelStoppedForVk = false
|
||||
try {
|
||||
if (
|
||||
TunnelManager.running.value ||
|
||||
TunnelManager.transition.value != TunnelTransition.IDLE
|
||||
) {
|
||||
val deviceId = settingsStore.getOrCreateConnectDeviceId()
|
||||
val localDocument = settingsStore.remoteActionProfileDocument(profile)
|
||||
if (LocalContinuationExtensions.available) {
|
||||
wdttConnectFlow = WdttConnectFlow.ExternalAction(
|
||||
profile = profile,
|
||||
continuation = continuation,
|
||||
access = access,
|
||||
message = "Останавливаем соединение и ждём стабильного доступа в интернет перед входом в VK..."
|
||||
message = "Связываемся с WDTT Plus через ещё работающее соединение..."
|
||||
)
|
||||
}
|
||||
val stopResult = TunnelStopCoordinator.stopAndAwait(this@MainActivity)
|
||||
if (!stopResult.succeeded) {
|
||||
throw IllegalStateException(
|
||||
if (stopResult == TunnelStopResult.TIMED_OUT) {
|
||||
"Соединение не остановилось за 20 секунд. Вернитесь в приложение и повторите попытку."
|
||||
val target = RemoteContinuationLauncher.begin(
|
||||
context = this@MainActivity,
|
||||
capability = continuation,
|
||||
device = deviceId,
|
||||
localDocument = localDocument,
|
||||
)
|
||||
val hasCompleteLocalValues = VkJoinLink.hasCompleteHashSet(
|
||||
settingsStore.tunnelProfileSnapshot(profile).vkHashes,
|
||||
)
|
||||
val progress: (String) -> Unit = { message ->
|
||||
wdttConnectFlow = WdttConnectFlow.ExternalAction(
|
||||
profile = profile,
|
||||
continuation = continuation,
|
||||
access = access,
|
||||
message = message,
|
||||
)
|
||||
}
|
||||
val documentUri = LocalContinuationExtensions.execute(
|
||||
activity = this@MainActivity,
|
||||
target = target.copy(localProfile = settingsStore.localContinuationProfile(profile)),
|
||||
deviceId = deviceId,
|
||||
hasCompleteLocalValues = hasCompleteLocalValues,
|
||||
onProgress = progress,
|
||||
)
|
||||
handleRemoteDocument(documentUri)
|
||||
} else {
|
||||
// The legacy build deliberately keeps its proven stop-first
|
||||
// native-handler/browser sequence for already installed APKs.
|
||||
if (
|
||||
TunnelManager.running.value ||
|
||||
TunnelManager.transition.value != TunnelTransition.IDLE
|
||||
) {
|
||||
wdttConnectFlow = WdttConnectFlow.ExternalAction(
|
||||
profile = profile,
|
||||
continuation = continuation,
|
||||
access = access,
|
||||
message = "Останавливаем соединение и ждём стабильного доступа в интернет перед входом в ВК..."
|
||||
)
|
||||
}
|
||||
val stopResult = TunnelStopCoordinator.stopAndAwait(this@MainActivity)
|
||||
if (!stopResult.succeeded) {
|
||||
throw IllegalStateException(
|
||||
if (stopResult == TunnelStopResult.TIMED_OUT) {
|
||||
"Соединение не остановилось за 20 секунд. Вернитесь в приложение и повторите попытку."
|
||||
} else {
|
||||
"Не удалось запросить остановку соединения. Остановите его и повторите попытку."
|
||||
}
|
||||
)
|
||||
}
|
||||
if (stopResult == TunnelStopResult.STOPPED) {
|
||||
tunnelStoppedForVk = true
|
||||
delay(TunnelStopCoordinator.DIRECT_NETWORK_SETTLE_MS)
|
||||
}
|
||||
wdttConnectFlow = WdttConnectFlow.ExternalAction(
|
||||
profile = profile,
|
||||
continuation = continuation,
|
||||
access = access,
|
||||
message = "Открываем защищённое продолжение..."
|
||||
)
|
||||
val target = RemoteContinuationLauncher.begin(
|
||||
context = this@MainActivity,
|
||||
capability = continuation,
|
||||
device = deviceId,
|
||||
localDocument = localDocument,
|
||||
)
|
||||
launchRemoteContinuation(target)
|
||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
||||
if (tunnelStoppedForVk) {
|
||||
"Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически. Соединение оставлено выключенным."
|
||||
} else {
|
||||
"Не удалось запросить остановку соединения. Остановите его и повторите попытку."
|
||||
"Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически."
|
||||
}
|
||||
)
|
||||
}
|
||||
if (stopResult == TunnelStopResult.STOPPED) {
|
||||
tunnelStoppedForVk = true
|
||||
delay(TunnelStopCoordinator.DIRECT_NETWORK_SETTLE_MS)
|
||||
}
|
||||
wdttConnectFlow = WdttConnectFlow.ExternalAction(
|
||||
} catch (_: LocalContinuationCancelledException) {
|
||||
wdttConnectFlow = WdttConnectFlow.SelectHashes(
|
||||
profile = profile,
|
||||
continuation = continuation,
|
||||
access = access,
|
||||
message = "Открываем защищённое продолжение..."
|
||||
)
|
||||
val target = RemoteContinuationLauncher.begin(
|
||||
capability = continuation,
|
||||
device = settingsStore.getOrCreateConnectDeviceId(),
|
||||
localDocument = settingsStore.remoteActionProfileDocument(profile),
|
||||
)
|
||||
launchRemoteContinuation(target)
|
||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
||||
if (tunnelStoppedForVk) {
|
||||
"Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически. Соединение оставлено выключенным."
|
||||
} else {
|
||||
"Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически."
|
||||
}
|
||||
)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
wdttConnectFlow = WdttConnectFlow.Failed(
|
||||
error.message ?: "Не удалось автоматически получить VK-хеши."
|
||||
error.message ?: "Не удалось автоматически получить ВК-хеши."
|
||||
)
|
||||
} finally {
|
||||
if (connectActionJob === runningJob) {
|
||||
@@ -989,7 +1080,7 @@ class MainActivity : ComponentActivity() {
|
||||
private fun skipConnectHashes() {
|
||||
if (wdttConnectFlow !is WdttConnectFlow.SelectHashes) return
|
||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
||||
"Доступ добавлен. VK-хеши можно заполнить позже в настройках профиля."
|
||||
"Доступ добавлен. ВК-хеши можно заполнить позже в настройках профиля."
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1008,7 +1099,7 @@ class MainActivity : ComponentActivity() {
|
||||
.distinct()
|
||||
if (hashes.isEmpty()) {
|
||||
wdttConnectFlow = WdttConnectFlow.Failed(
|
||||
"Вставьте от 1 до 4 VK-хешей или ссылок VK Звонков."
|
||||
"Вставьте от 1 до 4 ВК-хешей или ссылок ВК Звонков."
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
@@ -1023,11 +1114,11 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
}
|
||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
||||
"VK-хеши сохранены в новом профиле подключения."
|
||||
"ВК-хеши сохранены в новом профиле подключения."
|
||||
)
|
||||
}.onFailure { error ->
|
||||
wdttConnectFlow = WdttConnectFlow.Failed(
|
||||
error.message ?: "Не удалось сохранить VK-хеши."
|
||||
error.message ?: "Не удалось сохранить ВК-хеши."
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1037,7 +1128,7 @@ class MainActivity : ComponentActivity() {
|
||||
connectActionJob?.cancel()
|
||||
wdttConnectFlow = WdttConnectFlow.Progress(
|
||||
capability.exchange.message.ifBlank {
|
||||
"Возвращаем сохранённые VK-хеши в этот профиль..."
|
||||
"Возвращаем сохранённые ВК-хеши в этот профиль..."
|
||||
}
|
||||
)
|
||||
connectActionJob = lifecycleScope.launch {
|
||||
@@ -1049,13 +1140,13 @@ class MainActivity : ComponentActivity() {
|
||||
expectedCapability = capability,
|
||||
)
|
||||
wdttConnectFlow = WdttConnectFlow.Complete(
|
||||
"Сохранённые VK-хеши возвращены в профиль."
|
||||
"Сохранённые ВК-хеши возвращены в профиль."
|
||||
)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
wdttConnectFlow = WdttConnectFlow.Failed(
|
||||
error.message ?: "Не удалось вернуть сохранённые VK-хеши."
|
||||
error.message ?: "Не удалось вернуть сохранённые ВК-хеши."
|
||||
)
|
||||
} finally {
|
||||
if (connectActionJob === runningJob) {
|
||||
@@ -1070,12 +1161,12 @@ class MainActivity : ComponentActivity() {
|
||||
val looksLikeJoinLink = trimmed.contains("/call/join/", ignoreCase = true)
|
||||
val looksLikeRawHash = Regex("^[A-Za-z0-9_-]{16,512}$").matches(trimmed)
|
||||
if (!looksLikeJoinLink && !looksLikeRawHash) {
|
||||
sharedVkHashError = "Данные не распознаны. Поддерживаются ссылка подключения wdtt://, файл или QR WDTT Plus и ссылка VK-звонка."
|
||||
sharedVkHashError = "Данные не распознаны. Поддерживаются ссылка подключения wdtt://, файл или QR WDTT Plus и ссылка ВК-звонка."
|
||||
return
|
||||
}
|
||||
val hash = VkJoinLink.extractHash(sharedText)
|
||||
if (!VkJoinLink.isValidHash(hash)) {
|
||||
sharedVkHashError = "В переданной ссылке не найден VK-хеш звонка."
|
||||
sharedVkHashError = "В переданной ссылке не найден ВК-хеш звонка."
|
||||
return
|
||||
}
|
||||
lifecycleScope.launch {
|
||||
@@ -1094,7 +1185,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
}.onFailure { error ->
|
||||
sharedVkHashError = error.message ?: "Не удалось сохранить VK-хеш."
|
||||
sharedVkHashError = error.message ?: "Не удалось сохранить ВК-хеш."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1473,11 +1564,8 @@ private fun MainScreen(
|
||||
remoteManagedProfile = remoteManagedProfile,
|
||||
)
|
||||
SideEffect(onUiReadyForFirstDraw)
|
||||
val migrationDeployHost by settingsStore.deployIp.collectAsStateWithLifecycle(initialValue = "")
|
||||
val migrationSshPassword by settingsStore.deployPassword.collectAsStateWithLifecycle(initialValue = "")
|
||||
val migrationSshPrivateKey by settingsStore.deploySshPrivateKey.collectAsStateWithLifecycle(initialValue = "")
|
||||
val migrationSshAuthMode by settingsStore.deploySshAuthMode.collectAsStateWithLifecycle(initialValue = "password")
|
||||
val migrationMainPassword by settingsStore.deployMainPassword.collectAsStateWithLifecycle(initialValue = "")
|
||||
val migrationServerSettings by settingsStore.serverSetupSettings.collectAsStateWithLifecycle(initialValue = null)
|
||||
val currentMigrationProfile by rememberUpdatedState(activeProfile)
|
||||
val serverMigrationState by settingsStore.serverMigrationState.collectAsStateWithLifecycle(initialValue = null)
|
||||
val deviceCompatibilityCheckComplete by settingsStore.deviceCompatibilityCheckComplete.collectAsStateWithLifecycle(
|
||||
initialValue = true
|
||||
@@ -1500,6 +1588,8 @@ private fun MainScreen(
|
||||
)
|
||||
}
|
||||
var selectedTab by rememberSaveable { mutableIntStateOf(0) }
|
||||
var navigationRevision by rememberSaveable { mutableIntStateOf(0) }
|
||||
val currentNavigationRevision by rememberUpdatedState(navigationRevision)
|
||||
var projectSupportDialogRequest by remember { mutableIntStateOf(0) }
|
||||
val tunnelScrollPosition = rememberSaveable { mutableIntStateOf(0) }
|
||||
val deployScrollPosition = rememberSaveable { mutableIntStateOf(0) }
|
||||
@@ -1524,7 +1614,16 @@ private fun MainScreen(
|
||||
val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" }
|
||||
val safeBottomInset = with(density) { WindowInsets.safeDrawing.getBottom(density).toDp() }
|
||||
val navOverlayReserve = safeBottomInset + 96.dp
|
||||
val profileSwipeThresholdPx = with(density) { 64.dp.toPx() }
|
||||
val profileSwipeNoticeHost = remember { SnackbarHostState() }
|
||||
val profileSwipeMutex = remember { Mutex() }
|
||||
var tunnelHeaderBounds by remember { mutableStateOf<Rect?>(null) }
|
||||
var deployHeaderBounds by remember { mutableStateOf<Rect?>(null) }
|
||||
var tunnelProfileStripEnd by remember { mutableStateOf<Float?>(null) }
|
||||
var deployProfileStripEnd by remember { mutableStateOf<Float?>(null) }
|
||||
var contentBounds by remember { mutableStateOf(Rect.Zero) }
|
||||
var showTransferCenter by rememberSaveable { mutableStateOf(false) }
|
||||
LaunchedEffect(selectedTab, activeProfile, showTransferCenter) { navigationRevision++ }
|
||||
var startupDeviceReport by remember { mutableStateOf<DeviceCompatibilityReport?>(null) }
|
||||
var startupDeviceCheckRunning by remember { mutableStateOf(false) }
|
||||
val updateInstallPermissionLauncher = rememberLauncherForActivityResult(
|
||||
@@ -1657,6 +1756,8 @@ private fun MainScreen(
|
||||
val projectExpanded = rememberSaveable { mutableStateOf(false) }
|
||||
val tabStateHolder = rememberSaveableStateHolder()
|
||||
var deployTabInitialized by rememberSaveable { mutableStateOf(false) }
|
||||
var deployInstallRequest by rememberSaveable { mutableIntStateOf(0) }
|
||||
var deployInstallProfile by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
|
||||
|
||||
|
||||
@@ -1800,6 +1901,7 @@ private fun MainScreen(
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.consumeWindowInsets(padding)
|
||||
.onGloballyPositioned { contentBounds = it.boundsInWindow() }
|
||||
.pointerInput(focusManager) {
|
||||
awaitPointerEventScope {
|
||||
while (true) {
|
||||
@@ -1810,21 +1912,73 @@ private fun MainScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
.pointerInput(selectedTab, wdttLinkMode) {
|
||||
.pointerInput(selectedTab, wdttLinkMode, remoteManagedProfile) {
|
||||
var totalDrag = 0f
|
||||
var startedOnProfileHeader = false
|
||||
detectHorizontalDragGestures(
|
||||
onDragStart = {
|
||||
onDragStart = { start ->
|
||||
totalDrag = 0f
|
||||
navigationDragActive = true
|
||||
val header = when (selectedTab) {
|
||||
0 -> tunnelHeaderBounds
|
||||
1 -> deployHeaderBounds
|
||||
else -> null
|
||||
}
|
||||
val stripEnd = when (selectedTab) {
|
||||
0 -> tunnelProfileStripEnd
|
||||
1 -> deployProfileStripEnd
|
||||
else -> null
|
||||
}
|
||||
val strip = if (header != null && stripEnd != null && header.bottom > contentBounds.top) {
|
||||
Rect(contentBounds.left,
|
||||
if (selectedTab == 0 && remoteManagedProfile) maxOf(contentBounds.top, header.top) else contentBounds.top,
|
||||
contentBounds.right, minOf(contentBounds.bottom, stripEnd))
|
||||
} else null
|
||||
startedOnProfileHeader = strip?.contains(
|
||||
Offset(contentBounds.left + start.x, contentBounds.top + start.y)
|
||||
) == true
|
||||
navigationDragActive = !startedOnProfileHeader
|
||||
dragTargetIndex = -1
|
||||
dragProgress = 0f
|
||||
},
|
||||
onDragCancel = {
|
||||
startedOnProfileHeader = false
|
||||
totalDrag = 0f
|
||||
navigationDragActive = false
|
||||
dragTargetIndex = -1
|
||||
dragProgress = 0f
|
||||
},
|
||||
onDragEnd = {
|
||||
if (startedOnProfileHeader) {
|
||||
if (kotlin.math.abs(totalDrag) >= profileSwipeThresholdPx) {
|
||||
val direction = if (totalDrag < 0f) 1 else -1
|
||||
scope.launch {
|
||||
val switchedTo = profileSwipeMutex.withLock {
|
||||
val current = settingsStore.activeProfile.first()
|
||||
val target = (current + direction).takeIf { it in 0..2 }
|
||||
?: return@withLock null
|
||||
settingsStore.saveActiveProfile(target)
|
||||
target
|
||||
}
|
||||
if (switchedTo != null) {
|
||||
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
|
||||
val name = vpnProfileDisplayName(
|
||||
switchedTo, settingsStore.profileNames.first()
|
||||
)
|
||||
profileSwipeNoticeHost.currentSnackbarData?.dismiss()
|
||||
profileSwipeNoticeHost.showSnackbar(
|
||||
"Переключено на профиль «$name»",
|
||||
duration = SnackbarDuration.Short,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
startedOnProfileHeader = false
|
||||
totalDrag = 0f
|
||||
navigationDragActive = false
|
||||
dragTargetIndex = -1
|
||||
dragProgress = 0f
|
||||
return@detectHorizontalDragGestures
|
||||
}
|
||||
val selectedIndex = activeNavItems.indexOfFirst {
|
||||
it.id == selectedTab
|
||||
}.coerceAtLeast(0)
|
||||
@@ -1847,6 +2001,7 @@ private fun MainScreen(
|
||||
if (change.isConsumed) return@detectHorizontalDragGestures
|
||||
change.consume()
|
||||
totalDrag += dragAmount
|
||||
if (startedOnProfileHeader) return@detectHorizontalDragGestures
|
||||
if (abs(totalDrag) < 12f) {
|
||||
dragTargetIndex = -1
|
||||
dragProgress = 0f
|
||||
@@ -1885,6 +2040,14 @@ private fun MainScreen(
|
||||
DeployTab(
|
||||
scrollPosition = deployScrollPosition,
|
||||
visible = deployVisible,
|
||||
openInstallRequest = deployInstallRequest,
|
||||
openInstallProfile = deployInstallProfile,
|
||||
navigationRevision = navigationRevision,
|
||||
onOpenTunnel = { profile, revision ->
|
||||
if (currentMigrationProfile == profile && selectedTab == 1 && currentNavigationRevision == revision) selectedTab = 0
|
||||
},
|
||||
onProfileHeaderBounds = { deployHeaderBounds = it },
|
||||
onProfileHeaderBoundary = { deployProfileStripEnd = it },
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(bottom = navOverlayReserve)
|
||||
@@ -1911,6 +2074,8 @@ private fun MainScreen(
|
||||
settingsStore = settingsStore,
|
||||
scrollPosition = tunnelScrollPosition,
|
||||
onVkHashesSaved = onVkHashesSaved,
|
||||
onProfileHeaderBounds = { tunnelHeaderBounds = it },
|
||||
onProfileHeaderBoundary = { tunnelProfileStripEnd = it },
|
||||
onOpenProjectSupport = {
|
||||
selectedTab = 4
|
||||
projectSupportDialogRequest += 1
|
||||
@@ -1989,27 +2154,32 @@ private fun MainScreen(
|
||||
onFingerprintChange = onFingerprintChange,
|
||||
activeClientIds = activeClientIds,
|
||||
onClientIdsChange = onClientIdsChange,
|
||||
onTransferRequested = { showTransferCenter = true }
|
||||
onTransferRequested = { showTransferCenter = true },
|
||||
onOpened = { navigationRevision++ }
|
||||
)
|
||||
SnackbarHost(
|
||||
hostState = profileSwipeNoticeHost,
|
||||
modifier = Modifier.align(Alignment.BottomCenter)
|
||||
.padding(start = 16.dp, end = 16.dp, bottom = navOverlayReserve + 8.dp),
|
||||
) { data ->
|
||||
WdttInlineNotice(data.visuals.message)
|
||||
}
|
||||
}
|
||||
|
||||
val migrationNotice = serverMigrationState
|
||||
val activeProfileManagesServer = hasManagedServerCredentials(
|
||||
host = migrationDeployHost,
|
||||
sshAuthMode = migrationSshAuthMode,
|
||||
sshPassword = migrationSshPassword,
|
||||
mainPassword = migrationMainPassword,
|
||||
sshPrivateKey = migrationSshPrivateKey
|
||||
)
|
||||
val activeProfileManagesServer = migrationServerSettings?.takeIf { it.profileIndex == activeProfile }?.let {
|
||||
hasManagedServerCredentials(it.host, it.authMode, it.sshPassword, it.mainPassword, it.privateKey)
|
||||
} == true
|
||||
val serverMigrationPromptVisible =
|
||||
selectedTab != 1 &&
|
||||
isAdminInterface &&
|
||||
!remoteManagedProfile &&
|
||||
activeProfileManagesServer &&
|
||||
migrationNotice?.noticeRequired == true &&
|
||||
migrationNotice?.shouldShowNoticeForProfile(activeProfile) == true &&
|
||||
pendingUpdateCandidate == null &&
|
||||
startupDeviceReport == null
|
||||
if (serverMigrationPromptVisible) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = {},
|
||||
properties = DialogProperties(
|
||||
dismissOnBackPress = false,
|
||||
@@ -2019,11 +2189,11 @@ private fun MainScreen(
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(
|
||||
"В новых версиях WDTT Plus была изменена серверная часть. Для корректной работы приложения с сервером выполните установку сервера с сохранением данных во вкладке «Деплой».\n\n" +
|
||||
"В новых версиях WDTT Plus была изменена серверная часть. Для корректной работы приложения с сервером во вкладке «Деплой» выберите «Установить», нажмите «Обновить сервер», затем «Обновить с сохранением».\n\n" +
|
||||
"Клиенты, выданные доступы и настройки сохранятся. Установку с нуля выполнять не нужно."
|
||||
)
|
||||
Text(
|
||||
"После успешной установки приложение отметит обновление для выбранного профиля.",
|
||||
"После успешного обновления напоминание для этого профиля исчезнет. Сервер, установленный вручную, обновляйте тем же способом.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -2032,8 +2202,13 @@ private fun MainScreen(
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = {
|
||||
val targetProfile = activeProfile
|
||||
val requiredLevel = migrationNotice.pendingLevel
|
||||
scope.launch {
|
||||
settingsStore.acknowledgeServerMigrationNotice(migrationNotice.pendingLevel)
|
||||
settingsStore.acknowledgeServerMigrationNotice(requiredLevel)
|
||||
if (currentMigrationProfile != targetProfile) return@launch
|
||||
deployInstallProfile = targetProfile
|
||||
deployInstallRequest++
|
||||
selectedTab = 1
|
||||
}
|
||||
}
|
||||
@@ -2170,7 +2345,7 @@ private fun MainScreen(
|
||||
}
|
||||
|
||||
sharedVkHashError?.let { error ->
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onSharedVkHashMessageShown,
|
||||
title = { Text("Данные не импортированы") },
|
||||
text = { Text(error) },
|
||||
@@ -2202,7 +2377,7 @@ private fun MainScreen(
|
||||
}
|
||||
|
||||
wdttDeepLinkMessage?.let { message ->
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onWdttDeepLinkMessageShown,
|
||||
title = { Text("Передача WDTT") },
|
||||
text = { Text(message) },
|
||||
@@ -2217,7 +2392,7 @@ private fun MainScreen(
|
||||
pendingWdttDeepLinkPlan?.let { plan ->
|
||||
val profileLabel = vpnProfileDisplayName(plan.targetProfile, profileNames)
|
||||
val incomingProfileName = WdttDeepLink.parse(plan.link)?.profileName.orEmpty()
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onCancelWdttDeepLinkOverwrite,
|
||||
title = { Text("Профили подключения заполнены") },
|
||||
text = {
|
||||
@@ -2312,7 +2487,7 @@ private fun WdttConnectActivationDialog(
|
||||
val canDismiss = flow is WdttConnectFlow.SelectAttachmentProfile ||
|
||||
flow is WdttConnectFlow.Complete ||
|
||||
flow is WdttConnectFlow.Failed
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = {
|
||||
when {
|
||||
flow is WdttConnectFlow.ExternalAction -> onCancelExternalAction()
|
||||
@@ -2422,14 +2597,14 @@ private fun WdttConnectActivationDialog(
|
||||
}
|
||||
is WdttConnectFlow.ConfirmLimitedSetup -> {
|
||||
val reason = state.delivery.continuation.message.ifBlank {
|
||||
"Автоматическое получение VK-хешей сейчас недоступно."
|
||||
"Автоматическое получение ВК-хешей сейчас недоступно."
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("Перед продолжением обратите внимание:")
|
||||
Text(reason)
|
||||
Text(
|
||||
"Это ограничение относится только к автоматическому получению " +
|
||||
"VK-хешей. Сам профиль можно добавить и заполнить вручную.",
|
||||
"ВК-хешей. Сам профиль можно добавить и заполнить вручную.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
@@ -2437,12 +2612,26 @@ private fun WdttConnectActivationDialog(
|
||||
}
|
||||
is WdttConnectFlow.SelectHashes -> {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("Выберите способ заполнения VK-хешей для профиля.")
|
||||
Text("Выберите способ заполнения ВК-хешей для профиля.")
|
||||
if (state.access.exchange.actionAvailable) {
|
||||
HashMethodRow(
|
||||
title = state.access.exchange.label.ifBlank {
|
||||
"Получить сохранённые данные"
|
||||
},
|
||||
body = state.access.exchange.message.ifBlank {
|
||||
"Добавить данные, сохранённые для этого профиля"
|
||||
},
|
||||
onHelp = { helpMethod = "restore" },
|
||||
onClick = {
|
||||
onRestoreSavedHashes(state.profile, state.access)
|
||||
}
|
||||
)
|
||||
}
|
||||
HashMethodRow(
|
||||
title = "Получить автоматически",
|
||||
body = if (state.continuation.available) {
|
||||
state.continuation.message.ifBlank {
|
||||
"Войти в VK при необходимости и создать ссылки"
|
||||
"Войти в ВК при необходимости и создать ссылки"
|
||||
}
|
||||
} else {
|
||||
"Недоступно — нажмите, чтобы узнать, что делать"
|
||||
@@ -2460,30 +2649,16 @@ private fun WdttConnectActivationDialog(
|
||||
)
|
||||
HashMethodRow(
|
||||
title = "Заполнить вручную",
|
||||
body = "Вставить 1-4 хеша или ссылки VK Звонков",
|
||||
body = "Вставить 1-4 хеша или ссылки ВК Звонков",
|
||||
onHelp = { helpMethod = "manual" },
|
||||
onClick = { selectedHashMethod = "manual" }
|
||||
)
|
||||
if (state.access.exchange.actionAvailable) {
|
||||
HashMethodRow(
|
||||
title = state.access.exchange.label.ifBlank {
|
||||
"Вернуть хеши"
|
||||
},
|
||||
body = state.access.exchange.message.ifBlank {
|
||||
"Восстановить сохранённые хеши этого профиля"
|
||||
},
|
||||
onHelp = { helpMethod = "restore" },
|
||||
onClick = {
|
||||
onRestoreSavedHashes(state.profile, state.access)
|
||||
}
|
||||
)
|
||||
}
|
||||
if (selectedHashMethod == "manual") {
|
||||
OutlinedTextField(
|
||||
value = manualHashes,
|
||||
onValueChange = { manualHashes = it },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text("VK-хеши или ссылки") },
|
||||
label = { Text("ВК-хеши или ссылки") },
|
||||
minLines = 2,
|
||||
maxLines = 4
|
||||
)
|
||||
@@ -2589,7 +2764,7 @@ private fun WdttConnectActivationDialog(
|
||||
)
|
||||
|
||||
helpMethod?.let { method ->
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = { helpMethod = null },
|
||||
modifier = Modifier.televisionDialogWidth(television),
|
||||
title = {
|
||||
@@ -2605,16 +2780,14 @@ private fun WdttConnectActivationDialog(
|
||||
Text(
|
||||
when (method) {
|
||||
"auto" -> {
|
||||
"WDTT Plus откроет официальное мини-приложение VK. Если вы ещё не " +
|
||||
"вошли, VK сначала покажет свою форму входа, а затем вернёт вас к " +
|
||||
"созданию ссылок. Пароль VK не передаётся WDTT Plus."
|
||||
VK_HASH_AUTO_HELP_TEXT
|
||||
}
|
||||
"restore" -> {
|
||||
"WDTT Plus безопасно вернёт хеши, ранее сохранённые именно для " +
|
||||
"этого профиля. Значения других профилей не используются."
|
||||
}
|
||||
else -> {
|
||||
"Создайте или скопируйте до четырёх ссылок-приглашений VK Звонков, " +
|
||||
"Создайте или скопируйте до четырёх ссылок-приглашений ВК Звонков, " +
|
||||
"либо вставьте готовые хеши. Разделяйте значения пробелом, запятой " +
|
||||
"или новой строкой."
|
||||
}
|
||||
@@ -2629,12 +2802,12 @@ private fun WdttConnectActivationDialog(
|
||||
}
|
||||
|
||||
unavailableAutoMessage?.let { message ->
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = { unavailableAutoMessage = null },
|
||||
title = { Text("Автоматическое получение недоступно") },
|
||||
text = {
|
||||
Text(
|
||||
"$message\n\nСейчас можно заполнить VK-хеши вручную или пропустить этот шаг."
|
||||
"$message\n\nСейчас можно заполнить ВК-хеши вручную или пропустить этот шаг."
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
@@ -2673,7 +2846,7 @@ private fun HashMethodRow(
|
||||
Text(title, fontWeight = FontWeight.SemiBold)
|
||||
Text(body, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
IconButton(
|
||||
HintIconButton(hint = "Как это работает",
|
||||
onClick = onHelp,
|
||||
modifier = Modifier.remoteHelpFocus(),
|
||||
) {
|
||||
@@ -2689,12 +2862,12 @@ private fun SharedVkHashDialog(
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
val previous = result.previousHash
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("VK-хеш добавлен") },
|
||||
title = { Text("ВК-хеш добавлен") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Слот VK Хеш ${result.slot} обновлён.")
|
||||
Text("Слот ВК-хеш ${result.slot} обновлён.")
|
||||
Text(
|
||||
text = result.hash,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import kotlinx.coroutines.flow.first
|
||||
import java.util.TimeZone
|
||||
|
||||
data class ProfileTransferState(
|
||||
val managed: Boolean,
|
||||
val capability: RemoteAccessCapability,
|
||||
val revision: Long,
|
||||
val message: String,
|
||||
)
|
||||
|
||||
internal fun RemoteProfileAction.isUsableFor(
|
||||
state: ProfileTransferState,
|
||||
nowSeconds: Long = System.currentTimeMillis() / 1000L,
|
||||
): Boolean = state.managed && state.capability.available &&
|
||||
binding == state.capability.binding && expiresAtSeconds > nowSeconds
|
||||
|
||||
/** A cached lifecycle decision is deliberately insufficient to expose this action. */
|
||||
internal suspend fun fetchProfileTransferAction(
|
||||
context: Context,
|
||||
store: SettingsStore,
|
||||
profile: Int,
|
||||
expected: ProfileTransferState,
|
||||
): RemoteProfileAction? {
|
||||
if (!expected.managed || !expected.capability.available) return null
|
||||
val status = AccessLifecycleGateway.fetch(
|
||||
context = context,
|
||||
capability = expected.capability,
|
||||
device = store.getOrCreateConnectDeviceId(),
|
||||
client = BuildConfig.VERSION_NAME,
|
||||
system = Build.VERSION.RELEASE.orEmpty(),
|
||||
timezone = TimeZone.getDefault().id,
|
||||
profileRevision = expected.revision,
|
||||
)
|
||||
val current = store.profileTransferState(profile).first()
|
||||
if (!current.managed || current.capability != expected.capability ||
|
||||
current.revision != expected.revision
|
||||
) return null
|
||||
val action = status.profileAction?.takeIf { it.isUsableFor(current) } ?: return null
|
||||
// Keep only explanatory text for offline use, never the URL or its authorization data.
|
||||
store.saveProfileTransferMessage(profile, current, action.action.message)
|
||||
return action
|
||||
}
|
||||
@@ -12,7 +12,6 @@ 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(
|
||||
@@ -21,6 +20,10 @@ data class RemoteLaunchTarget(
|
||||
val preferredHandler: String = "",
|
||||
val alternateHandlers: List<String> = emptyList(),
|
||||
val returnScheme: String = "",
|
||||
val completion: RemoteActionCompletion = RemoteActionCompletion.Unavailable,
|
||||
/** Local-only context. Never parsed from a remote response or sent to a provider. */
|
||||
val localProfile: LocalContinuationProfile? = null,
|
||||
val embedded: RemoteEmbeddedPresentation? = null,
|
||||
) {
|
||||
internal fun handlerPackages(): List<String> =
|
||||
(listOf(preferredHandler) + alternateHandlers)
|
||||
@@ -28,8 +31,37 @@ data class RemoteLaunchTarget(
|
||||
.distinct()
|
||||
}
|
||||
|
||||
data class LocalContinuationProfile(val index: Int, val identity: String)
|
||||
|
||||
/** Exact server-provided targets. Context is opaque and only correlates UI messages. */
|
||||
data class RemoteEmbeddedPresentation(
|
||||
val url: String,
|
||||
val fallback: String,
|
||||
val confirmationUrl: String,
|
||||
val confirmationFallback: String,
|
||||
val context: String,
|
||||
)
|
||||
|
||||
data class RemoteActionCompletion(
|
||||
val available: Boolean,
|
||||
val url: String = "",
|
||||
val key: String = "",
|
||||
val expiresAtSeconds: Long = 0,
|
||||
) {
|
||||
companion object {
|
||||
val Unavailable = RemoteActionCompletion(available = false)
|
||||
}
|
||||
}
|
||||
|
||||
sealed interface RemoteActionCompletionState {
|
||||
data object Pending : RemoteActionCompletionState
|
||||
data object Unavailable : RemoteActionCompletionState
|
||||
data class Ready(val document: RemoteDocumentLink) : RemoteActionCompletionState
|
||||
}
|
||||
|
||||
object RemoteContinuationLauncher {
|
||||
suspend fun begin(
|
||||
context: Context,
|
||||
capability: RemoteContinuation,
|
||||
device: String,
|
||||
localDocument: String? = null,
|
||||
@@ -50,31 +82,36 @@ object RemoteContinuationLauncher {
|
||||
val payload = request
|
||||
.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("")
|
||||
val result = requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = {
|
||||
requestContinuationDirect(
|
||||
context = context,
|
||||
url = capability.url,
|
||||
payload = payload,
|
||||
)
|
||||
},
|
||||
tunnelRequest = {
|
||||
TunnelManager.postOpaqueHttpsStatusThroughTunnel(capability.url, payload)
|
||||
},
|
||||
preferTunnel = TunnelManager.isUpdateRelayAvailable(),
|
||||
)
|
||||
if (result.status !in 200..299) {
|
||||
val detail = runCatching {
|
||||
JSONObject(result.body).optString("detail")
|
||||
}.getOrDefault("")
|
||||
throw IllegalStateException(
|
||||
detail.ifBlank { "Не удалось продолжить действие. Откройте свежую ссылку подключения." }
|
||||
)
|
||||
}
|
||||
val response = runCatching { JSONObject(body) }
|
||||
val response = runCatching { JSONObject(result.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()
|
||||
val completion = parseCompletionCapability(response.optJSONObject("completion"))
|
||||
require(safeExternalUrl(primary)) {
|
||||
"WDTT Plus вернул повреждённый адрес продолжения."
|
||||
}
|
||||
@@ -90,12 +127,17 @@ object RemoteContinuationLauncher {
|
||||
require(returnScheme.isBlank() || returnScheme == AUTH_TAB_RETURN_SCHEME) {
|
||||
"WDTT Plus вернул повреждённый способ возврата."
|
||||
}
|
||||
require(completion != null) {
|
||||
"WDTT Plus вернул повреждённое восстановление результата."
|
||||
}
|
||||
RemoteLaunchTarget(
|
||||
primaryUrl = primary,
|
||||
fallbackUrl = fallback,
|
||||
preferredHandler = handler,
|
||||
alternateHandlers = alternateHandlers,
|
||||
returnScheme = returnScheme,
|
||||
completion = completion,
|
||||
embedded = parseEmbeddedPresentation(response.optJSONObject("embedded")),
|
||||
)
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
@@ -104,12 +146,55 @@ object RemoteContinuationLauncher {
|
||||
throw IllegalStateException(
|
||||
"Не удалось связаться с WDTT Plus. Проверьте интернет и повторите попытку."
|
||||
)
|
||||
} finally {
|
||||
connection?.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun parseEmbeddedPresentation(json: JSONObject?): RemoteEmbeddedPresentation? {
|
||||
if (json == null) return null // Older backend: use the existing safe fallback.
|
||||
val urls = listOf("url", "fallback", "confirmation_url", "confirmation_fallback")
|
||||
.map { json.optString(it) }
|
||||
require(urls.all { safeExternalUrl(it) && it.length <= 4096 }) {
|
||||
"Сервис вернул повреждённые адреса встроенного окна."
|
||||
}
|
||||
val context = json.optString("context")
|
||||
require(opaqueValue(context)) { "Сервис вернул повреждённый контекст действия." }
|
||||
return RemoteEmbeddedPresentation(urls[0], urls[1], urls[2], urls[3], context)
|
||||
}
|
||||
|
||||
suspend fun checkCompletion(
|
||||
context: Context,
|
||||
completion: RemoteActionCompletion,
|
||||
device: String,
|
||||
): RemoteActionCompletionState {
|
||||
require(
|
||||
completion.available &&
|
||||
safeServiceUrl(completion.url) &&
|
||||
opaqueValue(completion.key)
|
||||
) { "Проверка готового результата недоступна." }
|
||||
require(validDevice(device)) { "Не удалось определить текущее устройство." }
|
||||
return withContext(Dispatchers.IO) {
|
||||
val payload = JSONObject()
|
||||
.put("key", completion.key.trim())
|
||||
.put("device", device.trim())
|
||||
.toString()
|
||||
.toByteArray(Charsets.UTF_8)
|
||||
val response = requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = {
|
||||
requestCompletionDirect(context, completion.url, payload)
|
||||
},
|
||||
tunnelRequest = {
|
||||
TunnelManager.postOpaqueHttpsStatusThroughTunnel(completion.url, payload)
|
||||
},
|
||||
preferTunnel = TunnelManager.isUpdateRelayAvailable(),
|
||||
)
|
||||
if (response.status !in 200..299) {
|
||||
throw IllegalStateException("Не удалось проверить готовность результата.")
|
||||
}
|
||||
parseCompletionStatus(response.body)
|
||||
}
|
||||
}
|
||||
|
||||
fun launch(
|
||||
context: Context,
|
||||
target: RemoteLaunchTarget,
|
||||
@@ -170,6 +255,11 @@ object RemoteContinuationLauncher {
|
||||
internal fun authTabLaunchUrl(target: RemoteLaunchTarget): String =
|
||||
browserLaunchUrls(target).first()
|
||||
|
||||
internal fun primaryAuthTabLaunchUrl(target: RemoteLaunchTarget): String =
|
||||
target.primaryUrl.also {
|
||||
require(safeExternalUrl(it)) { "Адрес продолжения повреждён." }
|
||||
}
|
||||
|
||||
internal fun browserLaunchUrls(target: RemoteLaunchTarget): List<String> =
|
||||
(
|
||||
// The primary URL is for the preferred native VK handler. When
|
||||
@@ -272,6 +362,91 @@ object RemoteContinuationLauncher {
|
||||
}
|
||||
}
|
||||
|
||||
internal fun parseCompletionCapability(source: JSONObject?): RemoteActionCompletion? {
|
||||
if (source == null) return RemoteActionCompletion.Unavailable
|
||||
val url = source.optString("url").trim()
|
||||
val key = source.optString("key").trim()
|
||||
val expires = source.optLong("expires", 0L)
|
||||
if (!safeServiceUrl(url) || !opaqueValue(key) || expires <= 0L) return null
|
||||
return RemoteActionCompletion(
|
||||
available = true,
|
||||
url = url,
|
||||
key = key,
|
||||
expiresAtSeconds = expires,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun parseCompletionStatus(body: String): RemoteActionCompletionState {
|
||||
val response = runCatching { JSONObject(body) }
|
||||
.getOrElse { throw IllegalStateException("WDTT Plus вернул неполный статус результата.") }
|
||||
require(response.optInt("version", 0) == 1) {
|
||||
"Для восстановления результата нужна более новая версия WDTT Plus."
|
||||
}
|
||||
return when (response.optString("state").trim()) {
|
||||
"pending" -> RemoteActionCompletionState.Pending
|
||||
"unavailable" -> RemoteActionCompletionState.Unavailable
|
||||
"ready" -> {
|
||||
val document = RemoteDocumentGateway.extractLink(
|
||||
response.optString("document").trim()
|
||||
) ?: throw IllegalStateException("WDTT Plus вернул повреждённый адрес результата.")
|
||||
RemoteActionCompletionState.Ready(document)
|
||||
}
|
||||
else -> throw IllegalStateException("WDTT Plus вернул неизвестный статус результата.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestCompletionDirect(
|
||||
context: Context,
|
||||
url: String,
|
||||
payload: ByteArray,
|
||||
): RemoteDocumentHttpResponse {
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
connection = openDefaultHttpConnection(context, url)
|
||||
connection.requestMethod = "POST"
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.connectTimeout = 5_000
|
||||
connection.readTimeout = 7_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
|
||||
RemoteDocumentHttpResponse(
|
||||
status = status,
|
||||
body = readBody(connection, status),
|
||||
)
|
||||
} finally {
|
||||
connection?.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestContinuationDirect(
|
||||
context: Context,
|
||||
url: String,
|
||||
payload: ByteArray,
|
||||
): RemoteDocumentHttpResponse {
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
connection = openDefaultHttpConnection(context, url)
|
||||
connection.requestMethod = "POST"
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.connectTimeout = 4_000
|
||||
connection.readTimeout = 8_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
|
||||
RemoteDocumentHttpResponse(
|
||||
status = status,
|
||||
body = readBody(connection, status),
|
||||
)
|
||||
} finally {
|
||||
connection?.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun opaqueValue(value: String): Boolean =
|
||||
value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -8,7 +9,6 @@ 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)
|
||||
@@ -89,6 +89,41 @@ internal fun eligibleRemoteAttachmentDocument(
|
||||
|
||||
internal fun profileAttachmentRequired(value: String?): Boolean = value?.trim() == "1"
|
||||
|
||||
internal data class RemoteDocumentHttpResponse(
|
||||
val status: Int,
|
||||
val body: String,
|
||||
val profileAttachmentRequired: Boolean = false,
|
||||
)
|
||||
|
||||
internal suspend fun requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest: () -> RemoteDocumentHttpResponse,
|
||||
tunnelRequest: suspend () -> OpaqueHttpsRelayResult,
|
||||
preferTunnel: Boolean = false,
|
||||
): RemoteDocumentHttpResponse {
|
||||
if (preferTunnel) {
|
||||
when (val relayed = tunnelRequest()) {
|
||||
is OpaqueHttpsRelayResult.Success -> return RemoteDocumentHttpResponse(
|
||||
status = relayed.status,
|
||||
body = relayed.body,
|
||||
)
|
||||
is OpaqueHttpsRelayResult.Unavailable -> Unit
|
||||
}
|
||||
}
|
||||
return try {
|
||||
directRequest()
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (directError: Exception) {
|
||||
when (val relayed = tunnelRequest()) {
|
||||
is OpaqueHttpsRelayResult.Success -> RemoteDocumentHttpResponse(
|
||||
status = relayed.status,
|
||||
body = relayed.body,
|
||||
)
|
||||
is OpaqueHttpsRelayResult.Unavailable -> throw directError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object RemoteDocumentGateway {
|
||||
private const val MAX_RESPONSE_CHARS = 32 * 1024
|
||||
|
||||
@@ -120,6 +155,7 @@ object RemoteDocumentGateway {
|
||||
localBindings: Collection<String>? = null,
|
||||
localDocument: String? = null,
|
||||
profileAttachment: Boolean = false,
|
||||
context: Context? = null,
|
||||
): RemoteDocumentDelivery {
|
||||
require(extractLink(link.url) != null) { "Ссылка повреждена или неполна." }
|
||||
require(validDevice(device)) { "Не удалось определить текущее устройство." }
|
||||
@@ -146,31 +182,31 @@ object RemoteDocumentGateway {
|
||||
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)
|
||||
val response = requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = {
|
||||
requestDirect(
|
||||
context = context,
|
||||
url = link.url,
|
||||
payload = payload,
|
||||
)
|
||||
},
|
||||
tunnelRequest = {
|
||||
TunnelManager.postOpaqueHttpsStatusThroughTunnel(link.url, payload)
|
||||
},
|
||||
preferTunnel = TunnelManager.isUpdateRelayAvailable(),
|
||||
)
|
||||
if (response.status !in 200..299) {
|
||||
val failure = parseFailure(response.body)
|
||||
throw RemoteDocumentFailure(
|
||||
failure.first.ifBlank {
|
||||
"Ссылка недоступна. Получите новую ссылку подключения."
|
||||
},
|
||||
failure.second,
|
||||
profileAttachmentRequired = profileAttachmentRequired(
|
||||
connection.getHeaderField("X-WDTT-Profile-Required")
|
||||
),
|
||||
profileAttachmentRequired = response.profileAttachmentRequired,
|
||||
)
|
||||
}
|
||||
parse(body)
|
||||
parse(response.body)
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (error: Exception) {
|
||||
@@ -178,12 +214,38 @@ object RemoteDocumentGateway {
|
||||
throw IllegalStateException(
|
||||
"Не удалось связаться с WDTT Plus. Проверьте интернет и попробуйте ещё раз."
|
||||
)
|
||||
} finally {
|
||||
connection?.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestDirect(
|
||||
context: Context?,
|
||||
url: String,
|
||||
payload: ByteArray,
|
||||
): RemoteDocumentHttpResponse {
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
connection = openDefaultHttpConnection(context, url)
|
||||
connection.requestMethod = "POST"
|
||||
connection.connectTimeout = 4_000
|
||||
connection.readTimeout = 8_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
|
||||
RemoteDocumentHttpResponse(
|
||||
status = status,
|
||||
body = readBody(connection, status),
|
||||
profileAttachmentRequired = profileAttachmentRequired(
|
||||
connection.getHeaderField("X-WDTT-Profile-Required")
|
||||
),
|
||||
)
|
||||
} finally {
|
||||
connection?.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun parse(body: String): RemoteDocumentDelivery {
|
||||
require(body.length <= MAX_RESPONSE_CHARS) { "Ответ WDTT Plus слишком большой." }
|
||||
val root = runCatching { JSONObject(body) }
|
||||
|
||||
@@ -1027,23 +1027,112 @@ internal fun buildAdminProfilePatchArgs(
|
||||
}
|
||||
}
|
||||
|
||||
internal data class AdminRootStdinExecPlan(
|
||||
val command: String,
|
||||
val stdinPayload: String,
|
||||
)
|
||||
|
||||
private const val ADMIN_STDIN_FRAME_START = "__WDTT_ADMIN_STDIN_V1__"
|
||||
private const val ADMIN_STDIN_FRAME_END = "__WDTT_ADMIN_STDIN_END_V1__"
|
||||
|
||||
private fun quoteAdminShell(value: String): String =
|
||||
"'" + value.replace("'", "'\"'\"'") + "'"
|
||||
|
||||
internal fun buildAdminStdinForwardingCommand(command: String, shell: String = "bash"): String {
|
||||
require(shell == "bash" || shell == "sh")
|
||||
val quotedStart = quoteAdminShell(ADMIN_STDIN_FRAME_START)
|
||||
val quotedEnd = quoteAdminShell(ADMIN_STDIN_FRAME_END)
|
||||
val invalidFrame = "echo 'error: invalid WDTT admin stdin frame' >&2; exit 97"
|
||||
return "IFS= read -r wdtt_frame_first || { $invalidFrame; }; " +
|
||||
"IFS= read -r wdtt_frame_second || { $invalidFrame; }; " +
|
||||
"if [ \"\$wdtt_frame_first\" = $quotedStart ] && [ \"\$wdtt_frame_second\" = $quotedEnd ]; then :; " +
|
||||
"elif [ \"\$wdtt_frame_second\" = $quotedStart ]; then " +
|
||||
"IFS= read -r wdtt_frame_third || { $invalidFrame; }; " +
|
||||
"[ \"\$wdtt_frame_third\" = $quotedEnd ] || { $invalidFrame; }; " +
|
||||
"else $invalidFrame; fi; " +
|
||||
"exec $shell -c ${quoteAdminShell(command)}"
|
||||
}
|
||||
|
||||
internal fun buildAdminRootStdinExecPlan(
|
||||
command: String,
|
||||
sudoPassword: String,
|
||||
stdinPayload: String,
|
||||
shell: String = "bash",
|
||||
): AdminRootStdinExecPlan {
|
||||
require('\n' !in sudoPassword && '\r' !in sudoPassword) {
|
||||
"Пароль sudo не должен содержать перенос строки"
|
||||
}
|
||||
// sudo читает первую строку stdin только когда действительно запрашивает пароль.
|
||||
// Две метки позволяют дочерней root-команде отбросить пароль и при запросе,
|
||||
// и при уже действующей квитанции/NOPASSWD, оставив ей ровно исходный payload.
|
||||
val forwardingCommand = buildAdminStdinForwardingCommand(command, shell)
|
||||
val quotedForwardingCommand = quoteAdminShell(forwardingCommand)
|
||||
val rootCommand =
|
||||
"if [ \"\$(id -u)\" = \"0\" ]; then exec $shell -c $quotedForwardingCommand; " +
|
||||
"elif command -v sudo >/dev/null 2>&1; then exec sudo -S -p '' $shell -c $quotedForwardingCommand; " +
|
||||
"else echo 'error: root privileges required and sudo not found'; exit 1; fi"
|
||||
val payload = buildString {
|
||||
append(sudoPassword)
|
||||
append('\n')
|
||||
append(ADMIN_STDIN_FRAME_START)
|
||||
append('\n')
|
||||
append(ADMIN_STDIN_FRAME_END)
|
||||
append('\n')
|
||||
append(stdinPayload)
|
||||
}
|
||||
return AdminRootStdinExecPlan(rootCommand, payload)
|
||||
}
|
||||
|
||||
internal fun friendlyAdminSudoError(raw: String): String? {
|
||||
val value = raw.lowercase()
|
||||
return when {
|
||||
"incorrect password" in value ||
|
||||
"sorry, try again" in value ||
|
||||
"a password is required" in value ||
|
||||
"no password was provided" in value ||
|
||||
"authentication failure" in value ->
|
||||
"Не удалось подтвердить права sudo. Проверьте SSH-пароль или пароль sudo в «Деплой → SSH»."
|
||||
"is not in the sudoers file" in value ||
|
||||
"is not allowed to execute" in value ||
|
||||
"may not run sudo" in value ->
|
||||
"У SSH-пользователя нет разрешения выполнять команды управления через sudo."
|
||||
"root privileges required" in value || "sudo not found" in value ->
|
||||
"Для управления сервером нужны root-права или установленный sudo."
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
internal fun buildSshExecStdinPlan(
|
||||
command: String,
|
||||
sudoPassword: String,
|
||||
stdinPayload: String? = null,
|
||||
): AdminRootStdinExecPlan? = when {
|
||||
stdinPayload != null -> AdminRootStdinExecPlan(command, stdinPayload)
|
||||
// Send the original script over stdin: nesting it inside another `sh -c`
|
||||
// doubles its quoting and can exceed the OS limit for one argument.
|
||||
// The original command still selects its own shell and privilege branch.
|
||||
"sudo -S" in command -> buildAdminRootStdinExecPlan(
|
||||
command = "exec sh -s",
|
||||
sudoPassword = sudoPassword,
|
||||
stdinPayload = "$command\n",
|
||||
shell = "sh",
|
||||
)
|
||||
else -> null
|
||||
}
|
||||
|
||||
private class AdminSshClient(private val session: Session, private val sudoPassword: String) {
|
||||
companion object {
|
||||
private const val MAX_COMMAND_OUTPUT_CHARS = 16_000_000
|
||||
}
|
||||
|
||||
fun execRootWithStdin(command: String, stdinPayload: String, timeout: Long): String {
|
||||
val isRoot = session.userName == "root"
|
||||
if (!isRoot) {
|
||||
exec("sudo -S -p '' -v", 20_000L, sudoPassword + "\n")
|
||||
val plan = buildAdminRootStdinExecPlan(command, sudoPassword, stdinPayload)
|
||||
return try {
|
||||
exec(plan.command, timeout, plan.stdinPayload)
|
||||
} catch (error: IllegalStateException) {
|
||||
val friendly = friendlyAdminSudoError(error.message.orEmpty()) ?: throw error
|
||||
throw IllegalStateException(friendly, error)
|
||||
}
|
||||
val quoted = "'" + command.replace("'", "'\"'\"'") + "'"
|
||||
val rootCommand = if (isRoot) {
|
||||
"bash -c $quoted"
|
||||
} else {
|
||||
"sudo -n bash -c $quoted"
|
||||
}
|
||||
return exec(rootCommand, timeout, stdinPayload)
|
||||
}
|
||||
|
||||
fun exec(command: String, timeout: Long): String = exec(command, timeout, null)
|
||||
@@ -1054,18 +1143,19 @@ private class AdminSshClient(private val session: Session, private val sudoPassw
|
||||
val stdout = StringBuilder()
|
||||
val stderr = StringBuilder()
|
||||
try {
|
||||
val plan = buildSshExecStdinPlan(command, sudoPassword, stdinPayload)
|
||||
channel = session.openChannel("exec") as ChannelExec
|
||||
channel.setCommand(command)
|
||||
channel.setCommand(plan?.command ?: command)
|
||||
val outStream = channel.outputStream
|
||||
val input = channel.inputStream
|
||||
val err = channel.errStream
|
||||
channel.connect(15_000)
|
||||
if (stdinPayload != null) {
|
||||
outStream.write(stdinPayload.toByteArray(Charsets.UTF_8))
|
||||
outStream.flush()
|
||||
} else if (command.contains("sudo -S")) {
|
||||
outStream.write("$sudoPassword\n".toByteArray(Charsets.UTF_8))
|
||||
if (plan != null) {
|
||||
// The frame is consumed before even a fast root/NOPASSWD command
|
||||
// can finish; do not write a password into an already closed channel.
|
||||
outStream.write(plan.stdinPayload.toByteArray(Charsets.UTF_8))
|
||||
outStream.flush()
|
||||
outStream.close()
|
||||
}
|
||||
val reader = input.bufferedReader()
|
||||
val errReader = err.bufferedReader()
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
|
||||
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15, 16, 17)
|
||||
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15, 16, 17, 19)
|
||||
|
||||
data class ServerMigrationState(
|
||||
val pendingLevel: Int,
|
||||
val acknowledgedLevel: Int,
|
||||
val completedLevel: Int
|
||||
val completedLevel: Int,
|
||||
val profileIndex: Int = 0,
|
||||
val installationPresent: Boolean? = null,
|
||||
) {
|
||||
fun shouldShowNoticeForProfile(profile: Int): Boolean =
|
||||
profileIndex == profile && noticeRequired && profileUpdateRequired
|
||||
|
||||
val noticeRequired: Boolean
|
||||
get() = pendingLevel > acknowledgedLevel
|
||||
|
||||
val profileUpdateRequired: Boolean
|
||||
get() = pendingLevel > completedLevel
|
||||
get() = pendingLevel > completedLevel && installationPresent != false
|
||||
}
|
||||
|
||||
internal fun resolveServerInstallationPresence(
|
||||
presence: Boolean?, probedHost: String?, probedPort: Int?, host: String, port: Int,
|
||||
): Boolean? = presence.takeIf {
|
||||
host.isNotBlank() && probedHost?.trim()?.equals(host.trim(), ignoreCase = true) == true &&
|
||||
probedPort == port
|
||||
}
|
||||
|
||||
internal data class ServerMigrationInitialization(
|
||||
|
||||
@@ -235,6 +235,7 @@ data class TunnelProfileSnapshot(
|
||||
val vpnDnsSelectionId: String = VPN_DNS_PROFILE_ID,
|
||||
val vpnDnsCustomServers: List<String> = emptyList(),
|
||||
val vkCallsPreflight: Boolean,
|
||||
val transportExperiment: String = TRANSPORT_AUTO,
|
||||
val rtNetwork: Boolean = false,
|
||||
val rtMasque: Boolean = false,
|
||||
val rtMasqueServerBootstrap: Boolean = false,
|
||||
@@ -352,6 +353,7 @@ data class ActiveTunnelProfileUiSnapshot(
|
||||
val customVkClientId: String,
|
||||
val customVkClientSecret: String,
|
||||
val vkCallsPreflight: Boolean,
|
||||
val transportExperiment: String = TRANSPORT_AUTO,
|
||||
val rtNetwork: Boolean = false,
|
||||
val rtMasque: Boolean = false,
|
||||
val rtMasqueServerBootstrap: Boolean = false,
|
||||
@@ -569,6 +571,31 @@ object WdttDeepLink {
|
||||
}
|
||||
}
|
||||
|
||||
internal fun shouldPrepareInitialServerTunnel(
|
||||
peer: String, password: String, link: String, remoteManaged: Boolean, remoteBinding: String,
|
||||
): Boolean = peer.isBlank() && password.isBlank() && link.isBlank() && !remoteManaged && remoteBinding.isBlank()
|
||||
|
||||
data class ServerConnectionAccess(
|
||||
val user: String, val password: String, val port: Int, val privateKey: String,
|
||||
val keyPassphrase: String, val authMode: String, val adminId: String,
|
||||
val botToken: String, val dns1: String, val dns2: String,
|
||||
)
|
||||
|
||||
data class ServerSetupSettings(
|
||||
val profileIndex: Int, val host: String, val user: String, val sshPassword: String,
|
||||
val sshPort: String, val authMode: String, val privateKey: String, val keyPassphrase: String,
|
||||
val mainPassword: String, val adminId: String, val botToken: String,
|
||||
val dns1: String, val dns2: String, val dtlsPort: Int, val wgPort: Int, val localPort: Int,
|
||||
val manualPorts: Boolean, val completed: Boolean,
|
||||
)
|
||||
|
||||
data class ServerSetupCompletion(
|
||||
val profileIndex: Int, val host: String, val user: String, val sshPassword: String,
|
||||
val sshPort: String, val authMode: String, val mainPassword: String,
|
||||
val dtlsPort: Int, val wgPort: Int, val localPort: Int, val dns1: String, val dns2: String,
|
||||
val adminId: String = "", val botToken: String = "", val tunnelPrepared: Boolean = false,
|
||||
)
|
||||
|
||||
class SettingsStore(context: Context) {
|
||||
private val appContext = context.applicationContext
|
||||
private val sharedPreferences = obtainSharedPreferences(appContext)
|
||||
@@ -579,7 +606,9 @@ class SettingsStore(context: Context) {
|
||||
val settingsReady: StateFlow<Boolean> = _settingsReady.asStateFlow()
|
||||
|
||||
companion object {
|
||||
private val Context.dataStore by preferencesDataStore("settings")
|
||||
private val Context.dataStore by preferencesDataStore(
|
||||
name = "settings",
|
||||
)
|
||||
private data class SharedPreferences(
|
||||
val scope: CoroutineScope,
|
||||
val state: StateFlow<Preferences?>,
|
||||
@@ -630,6 +659,7 @@ class SettingsStore(context: Context) {
|
||||
private val WDTT_LINK_MODE = booleanPreferencesKey("wdtt_link_mode")
|
||||
private val CONNECTION_INPUT_METHOD = stringPreferencesKey("connection_input_method")
|
||||
private val CONNECT_DEVICE_ID = stringPreferencesKey("connect_device_id")
|
||||
private val LOCAL_CONTINUATION_ID = stringPreferencesKey("local_continuation_id")
|
||||
private val TUNNEL_DEVICE_ID = stringPreferencesKey("tunnel_device_id")
|
||||
|
||||
private val PEER = stringPreferencesKey("peer")
|
||||
@@ -684,6 +714,7 @@ class SettingsStore(context: Context) {
|
||||
private val ACCESS_ACTION_MESSAGE = stringPreferencesKey("access_action_message")
|
||||
private val ACCESS_TITLE = stringPreferencesKey("access_title")
|
||||
private val ACCESS_MESSAGE = stringPreferencesKey("access_message")
|
||||
private val PROFILE_TRANSFER_MESSAGE = stringPreferencesKey("profile_transfer_message")
|
||||
private val ACCESS_DETAIL_LABEL = stringPreferencesKey("access_detail_label")
|
||||
private val ACCESS_DETAIL_VALUE = stringPreferencesKey("access_detail_value")
|
||||
private val ACCESS_ACTION_ICON = stringPreferencesKey("access_action_icon")
|
||||
@@ -745,6 +776,15 @@ class SettingsStore(context: Context) {
|
||||
private val CONNECTION_PASSWORD_ENCRYPTED = stringPreferencesKey("connection_password_encrypted")
|
||||
private val DEPLOY_MAIN_PASSWORD = stringPreferencesKey("deploy_main_password")
|
||||
private val DEPLOY_MAIN_PASSWORD_ENCRYPTED = stringPreferencesKey("deploy_main_password_encrypted")
|
||||
private val DEPLOY_SETUP_COMPLETED = booleanPreferencesKey("deploy_setup_completed")
|
||||
private val DEPLOY_INSTALLATION_PRESENT = booleanPreferencesKey("deploy_installation_present")
|
||||
private val DEPLOY_INSTALLATION_HOST = stringPreferencesKey("deploy_installation_host")
|
||||
private val DEPLOY_INSTALLATION_SSH_PORT = intPreferencesKey("deploy_installation_ssh_port")
|
||||
private val DEPLOY_SETUP_RESULT_PENDING = booleanPreferencesKey("deploy_setup_result_pending")
|
||||
private val DEPLOY_SETUP_TUNNEL_PREPARED = booleanPreferencesKey("deploy_setup_tunnel_prepared")
|
||||
private val DEPLOY_DTLS_PORT = intPreferencesKey("deploy_dtls_port")
|
||||
private val DEPLOY_WG_PORT = intPreferencesKey("deploy_wg_port")
|
||||
private val DEPLOY_LOCAL_PORT = intPreferencesKey("deploy_local_port")
|
||||
private val DEPLOY_ADMIN_ID = stringPreferencesKey("deploy_admin_id")
|
||||
private val DEPLOY_ADMIN_ID_ENCRYPTED = stringPreferencesKey("deploy_admin_id_encrypted")
|
||||
private val DEPLOY_BOT_TOKEN = stringPreferencesKey("deploy_bot_token")
|
||||
@@ -764,6 +804,7 @@ class SettingsStore(context: Context) {
|
||||
|
||||
// ═══ Captcha Solve Mode ═══
|
||||
private val VKCALLS_PREFLIGHT = booleanPreferencesKey("vkcalls_preflight")
|
||||
private val TRANSPORT_EXPERIMENT = stringPreferencesKey("transport_experiment")
|
||||
private val RT_NETWORK = booleanPreferencesKey("rt_network")
|
||||
private val RT_MASQUE = booleanPreferencesKey("rt_masque")
|
||||
private val RT_MASQUE_SERVER_BOOTSTRAP = booleanPreferencesKey("rt_masque_server_bootstrap")
|
||||
@@ -826,7 +867,8 @@ class SettingsStore(context: Context) {
|
||||
private val PERMISSION_ONBOARDING_COMPLETE = booleanPreferencesKey("permission_onboarding_complete")
|
||||
private const val VPN_PROFILE_COUNT = 3
|
||||
|
||||
private val PROFILE_STRING_KEYS = listOf(
|
||||
private val PROFILE_STRING_KEYS: List<Preferences.Key<String>> = listOf(
|
||||
TRANSPORT_EXPERIMENT,
|
||||
PROFILE_NAME,
|
||||
PEER,
|
||||
VK_HASHES,
|
||||
@@ -859,6 +901,7 @@ class SettingsStore(context: Context) {
|
||||
ACCESS_ACTION_MESSAGE,
|
||||
ACCESS_TITLE,
|
||||
ACCESS_MESSAGE,
|
||||
PROFILE_TRANSFER_MESSAGE,
|
||||
ACCESS_DETAIL_LABEL,
|
||||
ACCESS_DETAIL_VALUE,
|
||||
ACCESS_ACTION_ICON,
|
||||
@@ -871,6 +914,7 @@ class SettingsStore(context: Context) {
|
||||
VPN_DNS_CUSTOM,
|
||||
USER_AGENT,
|
||||
DEPLOY_IP,
|
||||
DEPLOY_INSTALLATION_HOST,
|
||||
DEPLOY_LOGIN,
|
||||
DEPLOY_PASSWORD,
|
||||
DEPLOY_PASSWORD_ENCRYPTED,
|
||||
@@ -917,7 +961,11 @@ class SettingsStore(context: Context) {
|
||||
CUSTOM_VK_CLIENT_SECRET,
|
||||
CUSTOM_VK_CLIENT_SECRET_ENCRYPTED
|
||||
)
|
||||
private val PROFILE_INT_KEYS = listOf(
|
||||
// Device-local profile identity is never part of exported settings.
|
||||
private val PROFILE_LOCAL_STRING_KEYS: List<Preferences.Key<String>> = listOf(
|
||||
LOCAL_CONTINUATION_ID,
|
||||
)
|
||||
private val PROFILE_INT_KEYS: List<Preferences.Key<Int>> = listOf(
|
||||
WORKERS_PER_HASH,
|
||||
PROFILE_MAX_WORKERS,
|
||||
PROFILE_WORKER_LIMIT_SEEN,
|
||||
@@ -925,16 +973,21 @@ class SettingsStore(context: Context) {
|
||||
LISTEN_PORT,
|
||||
SERVER_DTLS_PORT,
|
||||
SERVER_WG_PORT,
|
||||
PROXY_PORT
|
||||
PROXY_PORT,
|
||||
DEPLOY_INSTALLATION_SSH_PORT,
|
||||
DEPLOY_DTLS_PORT,
|
||||
DEPLOY_WG_PORT,
|
||||
DEPLOY_LOCAL_PORT,
|
||||
SERVER_MIGRATION_COMPLETED_LEVEL,
|
||||
)
|
||||
private val PROFILE_LONG_KEYS = listOf(
|
||||
private val PROFILE_LONG_KEYS: List<Preferences.Key<Long>> = listOf(
|
||||
ACCESS_CHECKED_AT,
|
||||
ACCESS_LAST_ATTEMPT_AT,
|
||||
ACCESS_PROFILE_REVISION,
|
||||
ACCESS_ACTION_LAUNCHED_AT,
|
||||
ACCESS_CONTINUATION_EXPIRES_AT,
|
||||
)
|
||||
private val PROFILE_BOOLEAN_KEYS = listOf(
|
||||
private val PROFILE_BOOLEAN_KEYS: List<Preferences.Key<Boolean>> = listOf(
|
||||
MANUAL_PORTS_ENABLED,
|
||||
NO_DTLS,
|
||||
NO_DNS,
|
||||
@@ -958,24 +1011,55 @@ class SettingsStore(context: Context) {
|
||||
PROXY_LAN_ENABLED,
|
||||
PROXY_AUTH_ENABLED,
|
||||
PROXY_MODE_ACTIVATED,
|
||||
DEPLOY_INSTALLATION_PRESENT,
|
||||
DEPLOY_SETUP_COMPLETED,
|
||||
DEPLOY_SETUP_TUNNEL_PREPARED,
|
||||
DEPLOY_SETUP_RESULT_PENDING,
|
||||
)
|
||||
|
||||
internal fun resettableProfilePreferenceNames(): Set<String> =
|
||||
(PROFILE_STRING_KEYS + PROFILE_INT_KEYS + PROFILE_LONG_KEYS + PROFILE_BOOLEAN_KEYS)
|
||||
(PROFILE_STRING_KEYS + PROFILE_LOCAL_STRING_KEYS + PROFILE_INT_KEYS +
|
||||
PROFILE_LONG_KEYS + PROFILE_BOOLEAN_KEYS)
|
||||
.mapTo(linkedSetOf()) { it.name }
|
||||
|
||||
internal fun profilePreferenceKeys(profile: Int): List<Preferences.Key<*>> =
|
||||
(PROFILE_STRING_KEYS + PROFILE_LOCAL_STRING_KEYS + PROFILE_INT_KEYS +
|
||||
PROFILE_LONG_KEYS + PROFILE_BOOLEAN_KEYS).map { getProfileKey(it, profile) }
|
||||
|
||||
internal fun resetProfilePreferences(prefs: MutablePreferences, profile: Int) {
|
||||
profilePreferenceKeys(profile).forEach { prefs.remove(it) }
|
||||
}
|
||||
|
||||
private fun <T> getProfileKey(baseKey: Preferences.Key<T>, profile: Int): Preferences.Key<T> {
|
||||
require(profile in 0 until VPN_PROFILE_COUNT)
|
||||
if (profile == 0) return baseKey
|
||||
val newName = "${baseKey.name}_$profile"
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return when {
|
||||
PROFILE_STRING_KEYS.any { it.name == baseKey.name } -> stringPreferencesKey(newName) as Preferences.Key<T>
|
||||
PROFILE_STRING_KEYS.any { it.name == baseKey.name } ||
|
||||
PROFILE_LOCAL_STRING_KEYS.any { it.name == baseKey.name } ->
|
||||
stringPreferencesKey(newName) as Preferences.Key<T>
|
||||
PROFILE_INT_KEYS.any { it.name == baseKey.name } -> intPreferencesKey(newName) as Preferences.Key<T>
|
||||
PROFILE_LONG_KEYS.any { it.name == baseKey.name } -> longPreferencesKey(newName) as Preferences.Key<T>
|
||||
PROFILE_BOOLEAN_KEYS.any { it.name == baseKey.name } -> booleanPreferencesKey(newName) as Preferences.Key<T>
|
||||
else -> throw IllegalArgumentException("Unsupported key type: ${baseKey.name}")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun resolveLocalContinuationProfile(
|
||||
prefs: MutablePreferences,
|
||||
profileIndex: Int,
|
||||
): LocalContinuationProfile {
|
||||
val key = getProfileKey(LOCAL_CONTINUATION_ID, profileIndex)
|
||||
val local = prefs[key]?.takeIf { it.isNotBlank() } ?: UUID.randomUUID().toString()
|
||||
prefs[key] = local
|
||||
val binding = prefs[getProfileKey(REMOTE_DOCUMENT_BINDING, profileIndex)].orEmpty()
|
||||
.ifBlank { prefs[getProfileKey(ACCESS_LIFECYCLE_BINDING, profileIndex)].orEmpty() }
|
||||
val identity = java.security.MessageDigest.getInstance("SHA-256")
|
||||
.digest("$profileIndex\n$local\n$binding".toByteArray(Charsets.UTF_8))
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
return LocalContinuationProfile(profileIndex, identity)
|
||||
}
|
||||
}
|
||||
|
||||
private val dataStore = appContext.dataStore
|
||||
@@ -1047,6 +1131,7 @@ class SettingsStore(context: Context) {
|
||||
profile
|
||||
),
|
||||
vkCallsPreflight = it[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true,
|
||||
transportExperiment = normalizeTransportExperiment(it[getProfileKey(TRANSPORT_EXPERIMENT, profile)]),
|
||||
rtNetwork = it[getProfileKey(RT_NETWORK, profile)] ?: false,
|
||||
rtMasque = it[getProfileKey(RT_MASQUE, profile)] ?: false,
|
||||
rtMasqueServerBootstrap =
|
||||
@@ -1188,7 +1273,7 @@ class SettingsStore(context: Context) {
|
||||
val showSystemApps: Flow<Boolean> = preferencesFlow.map { it[SHOW_SYSTEM_APPS] ?: false }
|
||||
val loggingEnabled: Flow<Boolean> = preferencesFlow.map { it[LOGGING_ENABLED] ?: true }
|
||||
val floatingToolbarYFraction: Flow<Float> = preferencesFlow.map { prefs ->
|
||||
prefs[FLOATING_TOOLBAR_Y_FRACTION]?.coerceIn(0f, 1f) ?: -1f
|
||||
prefs[FLOATING_TOOLBAR_Y_FRACTION]?.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: -1f
|
||||
}
|
||||
val trustedWifiEnabled: Flow<Boolean> = preferencesFlow.map { it[TRUSTED_WIFI_ENABLED] ?: false }
|
||||
val trustedWifiSsids: Flow<List<String>> = preferencesFlow.map { prefs ->
|
||||
@@ -1470,6 +1555,72 @@ class SettingsStore(context: Context) {
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile)
|
||||
}.distinctUntilChanged().flowOn(Dispatchers.IO)
|
||||
private fun serverSetupPorts(prefs: Preferences, profile: Int): Triple<Int, Int, Int> {
|
||||
val manual = prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] == true
|
||||
return Triple(
|
||||
prefs[getProfileKey(DEPLOY_DTLS_PORT, profile)] ?: if (manual) prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000 else 56000,
|
||||
prefs[getProfileKey(DEPLOY_WG_PORT, profile)] ?: if (manual) prefs[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001 else 56001,
|
||||
prefs[getProfileKey(DEPLOY_LOCAL_PORT, profile)] ?: if (manual) prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000 else 9000,
|
||||
)
|
||||
}
|
||||
|
||||
private fun readServerSetupSettings(prefs: Preferences, profile: Int) = ServerSetupSettings(
|
||||
profile, prefs[getProfileKey(DEPLOY_IP, profile)].orEmpty(),
|
||||
prefs[getProfileKey(DEPLOY_LOGIN, profile)].orEmpty(),
|
||||
readSecret(prefs, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile),
|
||||
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] ?: "22",
|
||||
prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)]?.takeIf { it == "key" || it == "password" }
|
||||
?: if (readSecret(prefs, DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, profile).isNotBlank()) "key" else "password",
|
||||
readSecret(prefs, DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, profile),
|
||||
readSecret(prefs, DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, DEPLOY_SSH_KEY_PASSPHRASE, profile),
|
||||
readSecret(prefs, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile),
|
||||
readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile),
|
||||
readSecret(prefs, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile),
|
||||
prefs[getProfileKey(DEPLOY_DNS1, profile)] ?: "1.1.1.1",
|
||||
prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1",
|
||||
serverSetupPorts(prefs, profile).first,
|
||||
serverSetupPorts(prefs, profile).second,
|
||||
serverSetupPorts(prefs, profile).third,
|
||||
(serverSetupPorts(prefs, profile).first) != 56000 ||
|
||||
(serverSetupPorts(prefs, profile).second) != 56001 ||
|
||||
(serverSetupPorts(prefs, profile).third) != 9000,
|
||||
prefs[getProfileKey(DEPLOY_SETUP_COMPLETED, profile)] ?: false,
|
||||
)
|
||||
|
||||
val serverSetupSettings: Flow<ServerSetupSettings> = preferencesFlow.map { prefs ->
|
||||
readServerSetupSettings(prefs, prefs[ACTIVE_PROFILE] ?: 0)
|
||||
}.distinctUntilChanged().flowOn(Dispatchers.IO)
|
||||
|
||||
suspend fun readServerSetupSettings(profileIndex: Int): ServerSetupSettings {
|
||||
require(profileIndex in 0 until VPN_PROFILE_COUNT)
|
||||
return readServerSetupSettings(dataStore.data.first(), profileIndex)
|
||||
}
|
||||
|
||||
val deploySetupCompleted: Flow<Boolean> = preferencesFlow.map { prefs ->
|
||||
prefs[getProfileKey(DEPLOY_SETUP_COMPLETED, prefs[ACTIVE_PROFILE] ?: 0)] ?: false
|
||||
}
|
||||
|
||||
val deploySetupCompletion: Flow<ServerSetupCompletion?> = preferencesFlow.map { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
if (prefs[getProfileKey(DEPLOY_SETUP_RESULT_PENDING, profile)] != true) null
|
||||
else ServerSetupCompletion(
|
||||
profile, prefs[getProfileKey(DEPLOY_IP, profile)].orEmpty(),
|
||||
prefs[getProfileKey(DEPLOY_LOGIN, profile)].orEmpty().ifBlank { "root" },
|
||||
readSecret(prefs, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile),
|
||||
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] ?: "22",
|
||||
prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] ?: "password",
|
||||
readSecret(prefs, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile),
|
||||
serverSetupPorts(prefs, profile).first,
|
||||
serverSetupPorts(prefs, profile).second,
|
||||
serverSetupPorts(prefs, profile).third,
|
||||
prefs[getProfileKey(DEPLOY_DNS1, profile)] ?: "1.1.1.1",
|
||||
prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1",
|
||||
readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile),
|
||||
readSecret(prefs, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile),
|
||||
prefs[getProfileKey(DEPLOY_SETUP_TUNNEL_PREPARED, profile)] ?: false,
|
||||
)
|
||||
}.distinctUntilChanged().flowOn(Dispatchers.IO)
|
||||
|
||||
val deployMainPassword: Flow<String> = preferencesFlow.map { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
readSecret(prefs, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile)
|
||||
@@ -1636,7 +1787,15 @@ class SettingsStore(context: Context) {
|
||||
ServerMigrationState(
|
||||
pendingLevel = prefs[SERVER_MIGRATION_PENDING_LEVEL] ?: 0,
|
||||
acknowledgedLevel = prefs[SERVER_MIGRATION_NOTICE_ACK_LEVEL] ?: 0,
|
||||
completedLevel = prefs[serverMigrationCompletedKey(profile)] ?: 0
|
||||
completedLevel = prefs[serverMigrationCompletedKey(profile)] ?: 0,
|
||||
profileIndex = profile,
|
||||
installationPresent = resolveServerInstallationPresence(
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_PRESENT, profile)],
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_HOST, profile)],
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_SSH_PORT, profile)],
|
||||
prefs[getProfileKey(DEPLOY_IP, profile)].orEmpty(),
|
||||
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)]?.toIntOrNull() ?: 22,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1833,10 +1992,23 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun markProfileServerMigrationComplete(profile: Int, level: Int) {
|
||||
if (level <= 0) return
|
||||
suspend fun recordProfileServerInstallation(profile: Int, host: String, sshPort: Int, present: Boolean) {
|
||||
require(profile in 0 until VPN_PROFILE_COUNT && host.isNotBlank() && sshPort in 1..65535)
|
||||
dataStore.edit { prefs ->
|
||||
val key = serverMigrationCompletedKey(profile.coerceIn(0, VPN_PROFILE_COUNT - 1))
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_PRESENT, profile)] = present
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_HOST, profile)] = host.trim()
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_SSH_PORT, profile)] = sshPort
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun markProfileServerMigrationComplete(profile: Int, level: Int, host: String, sshPort: Int) {
|
||||
if (level <= 0) return
|
||||
require(profile in 0 until VPN_PROFILE_COUNT && host.isNotBlank() && sshPort in 1..65535)
|
||||
dataStore.edit { prefs ->
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_PRESENT, profile)] = true
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_HOST, profile)] = host.trim()
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_SSH_PORT, profile)] = sshPort
|
||||
val key = serverMigrationCompletedKey(profile)
|
||||
prefs[key] = maxOf(prefs[key] ?: 0, level)
|
||||
}
|
||||
}
|
||||
@@ -1877,9 +2049,13 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveFloatingToolbarYFraction(fraction: Float) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[FLOATING_TOOLBAR_Y_FRACTION] = fraction.coerceIn(0f, 1f)
|
||||
fun saveFloatingToolbarYFraction(fraction: Float) {
|
||||
if (!fraction.isFinite()) return
|
||||
// Finish persistence even if the UI leaves composition or the activity is recreated.
|
||||
storeScope.launch {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[FLOATING_TOOLBAR_Y_FRACTION] = fraction.coerceIn(0f, 1f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1937,19 +2113,7 @@ class SettingsStore(context: Context) {
|
||||
suspend fun resetProfile(profile: Int) {
|
||||
val index = profile.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
dataStore.edit { prefs ->
|
||||
PROFILE_STRING_KEYS.forEach { key ->
|
||||
prefs.remove(getProfileKey(key, index))
|
||||
}
|
||||
PROFILE_INT_KEYS.forEach { key ->
|
||||
prefs.remove(getProfileKey(key, index))
|
||||
}
|
||||
PROFILE_LONG_KEYS.forEach { key ->
|
||||
prefs.remove(getProfileKey(key, index))
|
||||
}
|
||||
PROFILE_BOOLEAN_KEYS.forEach { key ->
|
||||
prefs.remove(getProfileKey(key, index))
|
||||
}
|
||||
prefs.remove(serverMigrationCompletedKey(index))
|
||||
resetProfilePreferences(prefs, index)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2158,6 +2322,7 @@ class SettingsStore(context: Context) {
|
||||
prefs[getProfileKey(VPN_DNS_CUSTOM, profile)].orEmpty()
|
||||
),
|
||||
vkCallsPreflight = prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true,
|
||||
transportExperiment = normalizeTransportExperiment(prefs[getProfileKey(TRANSPORT_EXPERIMENT, profile)]),
|
||||
rtNetwork = prefs[getProfileKey(RT_NETWORK, profile)] ?: false,
|
||||
rtMasque = prefs[getProfileKey(RT_MASQUE, profile)] ?: false,
|
||||
rtMasqueServerBootstrap =
|
||||
@@ -2212,6 +2377,9 @@ class SettingsStore(context: Context) {
|
||||
suspend fun connectionLinkForProfile(profileIndex: Int): String {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
return appContext.dataStore.data.map { prefs ->
|
||||
require(prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] != true) {
|
||||
"Этот профиль переносится через сервис, где он был получен."
|
||||
}
|
||||
val storedLink = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty()
|
||||
val storedParts = WdttDeepLink.parse(storedLink)
|
||||
val parts = storedParts ?: WdttLinkParts(
|
||||
@@ -2365,6 +2533,11 @@ class SettingsStore(context: Context) {
|
||||
suspend fun exportAdminSettings(): String = appContext.dataStore.data.map { prefs ->
|
||||
val profiles = JSONArray()
|
||||
repeat(VPN_PROFILE_COUNT) { profile ->
|
||||
if (prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true) {
|
||||
// Keep the slot index without serializing any connection or administrative secret.
|
||||
profiles.put(JSONObject().put("omitted", true))
|
||||
return@repeat
|
||||
}
|
||||
profiles.put(JSONObject().apply {
|
||||
put("wdttLink", prefs[getProfileKey(WDTT_LINK, profile)].orEmpty())
|
||||
put("wdttLinkMode", prefs[getProfileKey(WDTT_LINK_MODE, profile)] ?: false)
|
||||
@@ -2405,7 +2578,10 @@ class SettingsStore(context: Context) {
|
||||
put("deployLogin", prefs[getProfileKey(DEPLOY_LOGIN, profile)].orEmpty())
|
||||
put("deployPassword", readSecret(prefs, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile))
|
||||
put("deploySshPort", prefs[getProfileKey(DEPLOY_SSH_PORT, profile)].orEmpty())
|
||||
put("deployDns1", prefs[getProfileKey(DEPLOY_DNS1, profile)] ?: "1.1.1.1")
|
||||
put("deployDtlsPort", serverSetupPorts(prefs, profile).first)
|
||||
put("deployWgPort", serverSetupPorts(prefs, profile).second)
|
||||
put("deployLocalPort", serverSetupPorts(prefs, profile).third)
|
||||
put("deployDns1", prefs[getProfileKey(DEPLOY_DNS1, profile)] ?: "1.1.1.1")
|
||||
put("deployDns2", prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1")
|
||||
put("deployMainPassword", readSecret(prefs, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile))
|
||||
put("deployAdminId", readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile))
|
||||
@@ -2432,6 +2608,7 @@ class SettingsStore(context: Context) {
|
||||
truncateSocks5Credential(readProtectedSecret(prefs, PROXY_PASSWORD_ENCRYPTED, profile)),
|
||||
)
|
||||
put("vkCallsPreflight", prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true)
|
||||
put("transportExperiment", normalizeTransportExperiment(prefs[getProfileKey(TRANSPORT_EXPERIMENT, profile)]))
|
||||
put("rtNetwork", prefs[getProfileKey(RT_NETWORK, profile)] ?: false)
|
||||
put("rtMasque", prefs[getProfileKey(RT_MASQUE, profile)] ?: false)
|
||||
put(
|
||||
@@ -2487,6 +2664,8 @@ class SettingsStore(context: Context) {
|
||||
dataStore.edit { prefs ->
|
||||
repeat(VPN_PROFILE_COUNT) { profile ->
|
||||
val item = profiles.getJSONObject(profile)
|
||||
// An omitted slot must not erase an existing local profile on import.
|
||||
if (item.optBoolean("omitted", false)) return@repeat
|
||||
prefs.putSecret(
|
||||
REMOTE_ACTION_KEY_ENCRYPTED,
|
||||
REMOTE_ACTION_KEY,
|
||||
@@ -2581,6 +2760,9 @@ class SettingsStore(context: Context) {
|
||||
prefs.putSecret(WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED, WG_EXIT_SSH_KEY_PASSPHRASE, "", profile)
|
||||
prefs[getProfileKey(WG_EXIT_SSH_AUTH_MODE, profile)] = "password"
|
||||
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] = item.optString("deploySshPort")
|
||||
prefs[getProfileKey(DEPLOY_DTLS_PORT, profile)] = item.safePort("deployDtlsPort", item.safePort("serverDtlsPort", 56000))
|
||||
prefs[getProfileKey(DEPLOY_WG_PORT, profile)] = item.safePort("deployWgPort", item.safePort("serverWgPort", 56001))
|
||||
prefs[getProfileKey(DEPLOY_LOCAL_PORT, profile)] = item.safePort("deployLocalPort", item.safePort("listenPort", 9000))
|
||||
prefs[getProfileKey(DEPLOY_DNS1, profile)] = item.optString("deployDns1", "1.1.1.1")
|
||||
prefs[getProfileKey(DEPLOY_DNS2, profile)] = item.optString("deployDns2", "1.0.0.1")
|
||||
prefs.putSecret(DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, item.optString("deployMainPassword"), profile)
|
||||
@@ -2610,6 +2792,7 @@ class SettingsStore(context: Context) {
|
||||
profile,
|
||||
)
|
||||
prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] = item.optBoolean("vkCallsPreflight", true)
|
||||
prefs[getProfileKey(TRANSPORT_EXPERIMENT, profile)] = normalizeTransportExperiment(item.optString("transportExperiment"))
|
||||
prefs[getProfileKey(RT_NETWORK, profile)] = item.optBoolean("rtNetwork", false)
|
||||
prefs[getProfileKey(RT_MASQUE, profile)] = item.optBoolean("rtMasque", false)
|
||||
prefs[getProfileKey(RT_MASQUE_SERVER_BOOTSTRAP, profile)] =
|
||||
@@ -2966,6 +3149,7 @@ class SettingsStore(context: Context) {
|
||||
remove(seenLimitKey)
|
||||
}
|
||||
if (!preserveConnectionSettings) {
|
||||
remove(getProfileKey(TRANSPORT_EXPERIMENT, profile))
|
||||
val importedProfileName = vpnProfileRestorableName(parts.profileName)
|
||||
if (importedProfileName.isNotBlank()) {
|
||||
this[getProfileKey(PROFILE_NAME, profile)] = importedProfileName
|
||||
@@ -3105,7 +3289,8 @@ class SettingsStore(context: Context) {
|
||||
connectionPassword: String,
|
||||
dtlsPort: Int,
|
||||
wgPort: Int,
|
||||
ownerProfile: ServerAdminProfileInfo
|
||||
ownerProfile: ServerAdminProfileInfo,
|
||||
deployAccess: ServerConnectionAccess? = null,
|
||||
) {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
require(host.isNotBlank()) { "Адрес импортированного сервера пустой." }
|
||||
@@ -3125,6 +3310,29 @@ class SettingsStore(context: Context) {
|
||||
importedVpnDnsSelection
|
||||
}
|
||||
dataStore.edit { prefs ->
|
||||
deployAccess?.let { access ->
|
||||
require(access.port in 1..65535 && access.authMode in setOf("password", "key"))
|
||||
prefs[getProfileKey(DEPLOY_IP, profile)] = host.trim()
|
||||
prefs[getProfileKey(DEPLOY_LOGIN, profile)] = access.user
|
||||
prefs.putSecret(DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, access.password, profile)
|
||||
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] = access.port.toString()
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_PRESENT, profile)] = true
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_HOST, profile)] = host.trim()
|
||||
prefs[getProfileKey(DEPLOY_INSTALLATION_SSH_PORT, profile)] = access.port
|
||||
prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] = access.authMode
|
||||
if (access.authMode == "key") {
|
||||
prefs.putSecret(DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, normalizeSshPrivateKey(access.privateKey), profile)
|
||||
prefs.putSecret(DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, DEPLOY_SSH_KEY_PASSPHRASE, access.keyPassphrase, profile)
|
||||
}
|
||||
prefs.putSecret(DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, connectionPassword, profile)
|
||||
prefs.putSecret(DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, access.adminId, profile)
|
||||
prefs.putSecret(DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, access.botToken, profile)
|
||||
prefs[getProfileKey(DEPLOY_DNS1, profile)] = access.dns1
|
||||
prefs[getProfileKey(DEPLOY_DNS2, profile)] = access.dns2
|
||||
prefs[getProfileKey(DEPLOY_DTLS_PORT, profile)] = dtlsPort
|
||||
prefs[getProfileKey(DEPLOY_WG_PORT, profile)] = wgPort
|
||||
prefs[getProfileKey(DEPLOY_LOCAL_PORT, profile)] = ownerProfile.listenPort
|
||||
}
|
||||
prefs[getProfileKey(WDTT_LINK_MODE, profile)] = false
|
||||
prefs.remove(getProfileKey(WDTT_LINK, profile))
|
||||
prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = "manual"
|
||||
@@ -3192,6 +3400,34 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
fun profileTransferState(profile: Int): Flow<ProfileTransferState> {
|
||||
require(profile in 0 until VPN_PROFILE_COUNT)
|
||||
return preferencesFlow.map { prefs ->
|
||||
val lifecycle = readStoredAccessLifecycle(prefs, profile)
|
||||
ProfileTransferState(
|
||||
managed = prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true,
|
||||
capability = lifecycle.capability,
|
||||
revision = lifecycle.appliedProfileRevision,
|
||||
message = prefs[getProfileKey(PROFILE_TRANSFER_MESSAGE, profile)].orEmpty(),
|
||||
)
|
||||
}.distinctUntilChanged()
|
||||
}
|
||||
|
||||
suspend fun saveProfileTransferMessage(
|
||||
profile: Int,
|
||||
expected: ProfileTransferState,
|
||||
message: String,
|
||||
) {
|
||||
require(profile in 0 until VPN_PROFILE_COUNT)
|
||||
dataStore.edit { prefs ->
|
||||
if (prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true &&
|
||||
readStoredAccessLifecycle(prefs, profile).capability == expected.capability
|
||||
) {
|
||||
prefs[getProfileKey(PROFILE_TRANSFER_MESSAGE, profile)] = message.take(2400)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun accessLifecycleForProfile(profileIndex: Int): StoredAccessLifecycle {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
return preferencesFlow.map { prefs ->
|
||||
@@ -3283,6 +3519,16 @@ class SettingsStore(context: Context) {
|
||||
}.first()
|
||||
}
|
||||
|
||||
/** Local-only identity, stable across edits but different after reset or binding replacement. */
|
||||
suspend fun localContinuationProfile(profileIndex: Int): LocalContinuationProfile {
|
||||
require(profileIndex in 0 until VPN_PROFILE_COUNT)
|
||||
lateinit var profile: LocalContinuationProfile
|
||||
dataStore.edit { prefs ->
|
||||
profile = resolveLocalContinuationProfile(prefs, profileIndex)
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
suspend fun remoteAccessBindingForProfile(profileIndex: Int): String {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
return preferencesFlow.map { prefs ->
|
||||
@@ -3547,6 +3793,103 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveServerAccess(profileIndex: Int, host: String, user: String, password: String, port: String) {
|
||||
require(profileIndex in 0 until VPN_PROFILE_COUNT)
|
||||
dataStore.edit { prefs ->
|
||||
prefs[getProfileKey(DEPLOY_IP, profileIndex)] = host
|
||||
prefs[getProfileKey(DEPLOY_LOGIN, profileIndex)] = user
|
||||
prefs.putSecret(DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, password, profileIndex)
|
||||
prefs[getProfileKey(DEPLOY_SSH_PORT, profileIndex)] = port
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveServerParameters(
|
||||
profileIndex: Int, mainPassword: String, adminId: String, botToken: String,
|
||||
dns1: String? = null, dns2: String? = null, dtlsPort: Int? = null, wgPort: Int? = null,
|
||||
) {
|
||||
require(profileIndex in 0 until VPN_PROFILE_COUNT && mainPassword.isNotBlank())
|
||||
require((dtlsPort == null) == (wgPort == null))
|
||||
require(dtlsPort == null || (dtlsPort in 1..65535 && wgPort != null && wgPort in 1..65535 && dtlsPort != wgPort))
|
||||
dataStore.edit { prefs ->
|
||||
prefs.putSecret(DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, mainPassword, profileIndex)
|
||||
prefs.putSecret(DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, adminId, profileIndex)
|
||||
prefs.putSecret(DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, botToken, profileIndex)
|
||||
dns1?.let { prefs[getProfileKey(DEPLOY_DNS1, profileIndex)] = it }
|
||||
dns2?.let { prefs[getProfileKey(DEPLOY_DNS2, profileIndex)] = it }
|
||||
if (dtlsPort != null && wgPort != null) {
|
||||
prefs[getProfileKey(DEPLOY_DTLS_PORT, profileIndex)] = dtlsPort
|
||||
prefs[getProfileKey(DEPLOY_WG_PORT, profileIndex)] = wgPort
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveServerSetup(
|
||||
profileIndex: Int, host: String, user: String, sshPassword: String, sshPort: Int,
|
||||
privateKey: String, keyPassphrase: String, authMode: String, mainPassword: String,
|
||||
adminId: String, botToken: String, dns1: String, dns2: String,
|
||||
dtlsPort: Int, wgPort: Int, localPort: Int, completeFirstInstallation: Boolean = false,
|
||||
) {
|
||||
require(profileIndex in 0 until VPN_PROFILE_COUNT)
|
||||
require(authMode in setOf("password", "key") && mainPassword.isNotBlank())
|
||||
require(listOf(sshPort, dtlsPort, wgPort, localPort).all { it in 1..65535 } && dtlsPort != wgPort)
|
||||
dataStore.edit { prefs ->
|
||||
val profile = profileIndex
|
||||
prefs[getProfileKey(DEPLOY_IP, profile)] = host
|
||||
prefs[getProfileKey(DEPLOY_LOGIN, profile)] = user
|
||||
prefs.putSecret(DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, sshPassword, profile)
|
||||
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] = sshPort.toString()
|
||||
prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] = authMode
|
||||
if (!completeFirstInstallation || authMode == "key") {
|
||||
prefs.putSecret(DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, normalizeSshPrivateKey(privateKey), profile)
|
||||
prefs.putSecret(DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, DEPLOY_SSH_KEY_PASSPHRASE, keyPassphrase, profile)
|
||||
}
|
||||
prefs.putSecret(DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, mainPassword, profile)
|
||||
prefs.putSecret(DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, adminId, profile)
|
||||
prefs.putSecret(DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, botToken, profile)
|
||||
prefs[getProfileKey(DEPLOY_DNS1, profile)] = dns1
|
||||
prefs[getProfileKey(DEPLOY_DNS2, profile)] = dns2
|
||||
prefs[getProfileKey(DEPLOY_DTLS_PORT, profile)] = dtlsPort
|
||||
prefs[getProfileKey(DEPLOY_WG_PORT, profile)] = wgPort
|
||||
prefs[getProfileKey(DEPLOY_LOCAL_PORT, profile)] = localPort
|
||||
if (completeFirstInstallation) {
|
||||
val prepareTunnel = shouldPrepareInitialServerTunnel(
|
||||
prefs[getProfileKey(PEER, profile)].orEmpty(),
|
||||
readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile),
|
||||
prefs[getProfileKey(WDTT_LINK, profile)].orEmpty(),
|
||||
prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true,
|
||||
prefs[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty(),
|
||||
)
|
||||
if (prepareTunnel) {
|
||||
prefs[getProfileKey(PEER, profile)] = host.trim()
|
||||
prefs.putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, mainPassword, profile)
|
||||
prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = "manual"
|
||||
prefs[getProfileKey(WDTT_LINK_MODE, profile)] = false
|
||||
prefs.remove(getProfileKey(WDTT_LINK, profile))
|
||||
prefs[getProfileKey(SERVER_DTLS_PORT, profile)] = dtlsPort
|
||||
prefs[getProfileKey(SERVER_WG_PORT, profile)] = wgPort
|
||||
prefs[getProfileKey(LISTEN_PORT, profile)] = localPort
|
||||
prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = dtlsPort != 56000 || wgPort != 56001 || localPort != 9000
|
||||
}
|
||||
prefs[getProfileKey(DEPLOY_SETUP_TUNNEL_PREPARED, profile)] = prepareTunnel
|
||||
prefs[getProfileKey(DEPLOY_SETUP_RESULT_PENDING, profile)] = true
|
||||
prefs[getProfileKey(DEPLOY_SETUP_COMPLETED, profile)] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun finishServerSetup(profileIndex: Int) {
|
||||
require(profileIndex in 0 until VPN_PROFILE_COUNT)
|
||||
dataStore.edit { prefs ->
|
||||
prefs[getProfileKey(DEPLOY_SETUP_COMPLETED, profileIndex)] = true
|
||||
prefs[getProfileKey(DEPLOY_SETUP_RESULT_PENDING, profileIndex)] = false
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun dismissServerSetupCompletion(profileIndex: Int) {
|
||||
require(profileIndex in 0 until VPN_PROFILE_COUNT)
|
||||
dataStore.edit { it[getProfileKey(DEPLOY_SETUP_RESULT_PENDING, profileIndex)] = false }
|
||||
}
|
||||
|
||||
suspend fun saveDeploy(ip: String, login: String, pass: String, sshPort: String, dns1: String, dns2: String) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
@@ -3559,10 +3902,11 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveDeploySshKey(privateKey: String, passphrase: String) {
|
||||
suspend fun saveDeploySshKey(privateKey: String, passphrase: String, profileIndex: Int? = null) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
val profile = profileIndex ?: prefs[ACTIVE_PROFILE] ?: 0
|
||||
val normalizedKey = normalizeSshPrivateKey(privateKey)
|
||||
if (normalizedKey.isNotBlank()) prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] = "key"
|
||||
prefs.putSecret(
|
||||
DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED,
|
||||
DEPLOY_SSH_PRIVATE_KEY,
|
||||
@@ -3578,10 +3922,10 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveDeploySshAuthMode(mode: String) {
|
||||
suspend fun saveDeploySshAuthMode(mode: String, profileIndex: Int? = null) {
|
||||
require(mode == "password" || mode == "key")
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
val profile = profileIndex ?: prefs[ACTIVE_PROFILE] ?: 0
|
||||
prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] = mode
|
||||
}
|
||||
}
|
||||
@@ -3883,6 +4227,27 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveTransportExperiment(value: String, profileIndex: Int) {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
dataStore.edit { prefs ->
|
||||
prefs[getProfileKey(TRANSPORT_EXPERIMENT, profile)] = normalizeTransportExperiment(value)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveConnectionMode(streamOnly: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
prefs[getProfileKey(RT_NETWORK, profile)] = streamOnly
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveConnectionSni(turnSni: String, profileIndex: Int) {
|
||||
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
dataStore.edit { prefs ->
|
||||
prefs[getProfileKey(RT_TURN_SNI, profile)] = turnSni
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveRtNetwork(enabled: Boolean, turnSni: String? = null) {
|
||||
dataStore.edit { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
@@ -4242,6 +4607,11 @@ class SettingsStore(context: Context) {
|
||||
putCachedRemoteAction(status.cachedAction, profile)
|
||||
}
|
||||
status.exchange?.let { putProfileExchange(it, profile) }
|
||||
status.profileAction?.takeIf {
|
||||
it.binding == this[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)]
|
||||
}?.let {
|
||||
this[getProfileKey(PROFILE_TRANSFER_MESSAGE, profile)] = it.action.message.take(2400)
|
||||
}
|
||||
this[getProfileKey(ACCESS_ALLOW_CONNECT, profile)] = status.allowConnect
|
||||
this[getProfileKey(ACCESS_CHECKED_AT, profile)] = status.checkedAtMillis.coerceAtLeast(0)
|
||||
this[getProfileKey(ACCESS_ACTION_AVAILABLE, profile)] = status.actionAvailable
|
||||
@@ -4424,6 +4794,7 @@ class SettingsStore(context: Context) {
|
||||
remove(getProfileKey(ACCESS_ACTION_MESSAGE, profile))
|
||||
remove(getProfileKey(ACCESS_TITLE, profile))
|
||||
remove(getProfileKey(ACCESS_MESSAGE, profile))
|
||||
remove(getProfileKey(PROFILE_TRANSFER_MESSAGE, profile))
|
||||
remove(getProfileKey(ACCESS_DETAIL_LABEL, profile))
|
||||
remove(getProfileKey(ACCESS_DETAIL_VALUE, profile))
|
||||
remove(getProfileKey(ACCESS_ACTION_ICON, profile))
|
||||
|
||||
@@ -51,20 +51,20 @@ internal fun sshProfileAccessStatus(
|
||||
if (host.isBlank()) {
|
||||
return SshProfileAccessStatus(
|
||||
available = false,
|
||||
unavailableReason = "укажите адрес сервера в разделе «Деплой»",
|
||||
unavailableReason = "укажите адрес сервера в «Деплой → SSH»",
|
||||
)
|
||||
}
|
||||
if (authMode == "key") {
|
||||
if (privateKey.isBlank()) {
|
||||
return SshProfileAccessStatus(
|
||||
available = false,
|
||||
unavailableReason = "добавьте приватный SSH-ключ в разделе «Деплой»",
|
||||
unavailableReason = "добавьте приватный SSH-ключ в «Деплой → SSH»",
|
||||
)
|
||||
}
|
||||
sshPrivateKeyIssue(privateKey)?.let {
|
||||
return SshProfileAccessStatus(
|
||||
available = false,
|
||||
unavailableReason = "исправьте приватный SSH-ключ в разделе «Деплой»: ${it.removeSuffix(".")}",
|
||||
unavailableReason = "исправьте приватный SSH-ключ в «Деплой → SSH»: ${it.removeSuffix(".")}",
|
||||
)
|
||||
}
|
||||
return SshProfileAccessStatus(available = true)
|
||||
@@ -72,7 +72,7 @@ internal fun sshProfileAccessStatus(
|
||||
if (password.isBlank()) {
|
||||
return SshProfileAccessStatus(
|
||||
available = false,
|
||||
unavailableReason = "укажите SSH-пароль в разделе «Деплой»",
|
||||
unavailableReason = "укажите SSH-пароль в «Деплой → SSH»",
|
||||
)
|
||||
}
|
||||
return SshProfileAccessStatus(available = true)
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.net.IDN
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Process-local, non-persistent destination-routing lease for optional build
|
||||
* extensions. The public client does not assign provider or commercial
|
||||
* meaning to the exact domains supplied by an installed local extension.
|
||||
*/
|
||||
internal object TemporaryDirectRouteRegistry {
|
||||
private val lock = Any()
|
||||
private val leases = linkedMapOf<String, Set<String>>()
|
||||
private var resolvedDomains: Set<String> = emptySet()
|
||||
|
||||
fun currentDomains(): Set<String> = synchronized(lock) {
|
||||
leases.values.flatten().toSet()
|
||||
}
|
||||
|
||||
fun add(domains: Set<String>): String = synchronized(lock) {
|
||||
resolvedDomains = emptySet()
|
||||
UUID.randomUUID().toString().also { token -> leases[token] = domains }
|
||||
}
|
||||
|
||||
fun remove(token: String): Boolean = synchronized(lock) {
|
||||
val removed = leases.remove(token) != null
|
||||
if (removed) resolvedDomains = emptySet()
|
||||
removed
|
||||
}
|
||||
|
||||
fun recordResolvedDomains(domains: Set<String>) = synchronized(lock) {
|
||||
resolvedDomains = domains.intersect(leases.values.flatten().toSet())
|
||||
}
|
||||
|
||||
fun allResolved(domains: Set<String>): Boolean = synchronized(lock) {
|
||||
domains.isNotEmpty() && resolvedDomains.containsAll(domains)
|
||||
}
|
||||
}
|
||||
|
||||
internal class TemporaryDirectRouteLease private constructor(
|
||||
private val context: Context,
|
||||
private val token: String?,
|
||||
) {
|
||||
private var released = false
|
||||
|
||||
suspend fun release() {
|
||||
if (released) return
|
||||
released = true
|
||||
val currentToken = token ?: return
|
||||
withContext(NonCancellable) {
|
||||
operationMutex.withLock {
|
||||
if (!TemporaryDirectRouteRegistry.remove(currentToken)) return@withLock
|
||||
if (TunnelManager.running.value && TunnelManager.activeMode.value == TUNNEL_MODE_VPN) {
|
||||
WireGuardHelper(context).reloadTunnel()
|
||||
delay(ROUTE_SETTLE_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val operationMutex = Mutex()
|
||||
private const val ROUTE_SETTLE_MS = 350L
|
||||
private const val MAX_DOMAINS = 16
|
||||
|
||||
suspend fun acquire(context: Context, domains: Collection<String>): TemporaryDirectRouteLease =
|
||||
operationMutex.withLock {
|
||||
val appContext = context.applicationContext
|
||||
val normalized = normalizeTemporaryDirectDomains(domains)
|
||||
if (
|
||||
normalized.isEmpty() ||
|
||||
!TunnelManager.running.value ||
|
||||
TunnelManager.activeMode.value != TUNNEL_MODE_VPN ||
|
||||
!WireGuardHelper(appContext).isTunnelUp()
|
||||
) {
|
||||
return@withLock TemporaryDirectRouteLease(appContext, null)
|
||||
}
|
||||
|
||||
val token = TemporaryDirectRouteRegistry.add(normalized)
|
||||
val helper = WireGuardHelper(appContext)
|
||||
if (!helper.reloadTunnel() || !TemporaryDirectRouteRegistry.allResolved(normalized)) {
|
||||
TemporaryDirectRouteRegistry.remove(token)
|
||||
helper.reloadTunnel()
|
||||
throw IllegalStateException(
|
||||
"Не удалось подготовить прямое соединение с внешним сервисом. VPN восстановлен без временных маршрутов."
|
||||
)
|
||||
}
|
||||
delay(ROUTE_SETTLE_MS)
|
||||
TemporaryDirectRouteLease(appContext, token)
|
||||
}
|
||||
|
||||
private fun normalizeTemporaryDirectDomains(domains: Collection<String>): Set<String> {
|
||||
require(domains.size <= MAX_DOMAINS) { "Получено слишком много адресов продолжения." }
|
||||
return domains.asSequence()
|
||||
.map(String::trim)
|
||||
.filter(String::isNotEmpty)
|
||||
.map { value ->
|
||||
val ascii = IDN.toASCII(value.trimEnd('.'), IDN.USE_STD3_ASCII_RULES)
|
||||
.lowercase()
|
||||
require(
|
||||
ascii.length in 3..253 &&
|
||||
'.' in ascii &&
|
||||
ascii.split('.').all { label ->
|
||||
label.length in 1..63 &&
|
||||
label.first().isLetterOrDigit() &&
|
||||
label.last().isLetterOrDigit() &&
|
||||
label.all { it.isLetterOrDigit() || it == '-' }
|
||||
}
|
||||
) { "Адрес прямого продолжения повреждён." }
|
||||
ascii
|
||||
}
|
||||
.toSet()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
internal const val TRANSPORT_AUTO = "auto"
|
||||
|
||||
// All profile generations use one adaptive transport. Native negotiation keeps
|
||||
// compatibility with servers that only support ordinary WireGuard forwarding.
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
internal fun normalizeTransportExperiment(value: String?): String = TRANSPORT_AUTO
|
||||
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
internal fun effectiveTransportExperiment(value: String?, tunnelMode: String): String = TRANSPORT_AUTO
|
||||
@@ -345,6 +345,7 @@ internal fun boundedVkCallsPreflightCooldownUntil(
|
||||
enum class ConnectionIssueKind {
|
||||
GENERAL,
|
||||
ACCESS,
|
||||
PROXY_PORT_IN_USE,
|
||||
}
|
||||
|
||||
@Stable
|
||||
@@ -355,6 +356,46 @@ data class ConnectionIssue(
|
||||
val kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL,
|
||||
)
|
||||
|
||||
internal data class ProxyErrorPresentation(
|
||||
val issue: ConnectionIssue,
|
||||
val logMessage: String,
|
||||
val readyAddress: String? = null,
|
||||
val readyAddresses: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
internal fun proxyErrorPresentation(payload: String): ProxyErrorPresentation {
|
||||
val parts = payload.split('|', limit = 3)
|
||||
if (parts.firstOrNull() == "port_in_use") {
|
||||
val address = parts.getOrNull(1).orEmpty().trim()
|
||||
val port = address.substringAfterLast(':', "").toIntOrNull()?.takeIf { it in 1..65535 }
|
||||
val safeAddress = address.takeIf {
|
||||
port != null && Regex("^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}:[0-9]{1,5}$").matches(it)
|
||||
}
|
||||
val endpointText = safeAddress?.let { "$it уже занят. " }.orEmpty()
|
||||
return ProxyErrorPresentation(
|
||||
issue = ConnectionIssue(
|
||||
title = "Порт прокси уже занят",
|
||||
action = endpointText +
|
||||
"Порт ${port ?: "прокси"} уже используется другим приложением или предыдущим процессом WDTT Plus. " +
|
||||
"Выберите другой порт в настройках прокси.",
|
||||
kind = ConnectionIssueKind.PROXY_PORT_IN_USE,
|
||||
),
|
||||
logMessage = "[ПРОКСИ] Порт занят: ${safeAddress ?: "адрес не определён"}",
|
||||
)
|
||||
}
|
||||
val reason = when (parts.firstOrNull()) {
|
||||
"startup" -> parts.drop(1).joinToString("|")
|
||||
else -> payload
|
||||
}.ifBlank { "неизвестная ошибка" }
|
||||
return ProxyErrorPresentation(
|
||||
issue = ConnectionIssue(
|
||||
title = "Прокси не запустился",
|
||||
action = "Проверьте порт, сеть и настройки аутентификации. Причина: $reason",
|
||||
),
|
||||
logMessage = "[ПРОКСИ] $reason",
|
||||
)
|
||||
}
|
||||
|
||||
internal val ConnectionIssue.isStandaloneUiIssue: Boolean
|
||||
get() = kind != ConnectionIssueKind.ACCESS
|
||||
|
||||
@@ -677,21 +718,19 @@ internal const val WRAP_HANDSHAKE_RETRY_MESSAGE =
|
||||
|
||||
internal fun wrapHandshakeTerminalMessage(rtNetwork: Boolean): String =
|
||||
if (rtNetwork) {
|
||||
"\uD83C\uDF10 Через сеть РТ не получен ответ WRAP. Обычно сеть не пропустила выбранный TURN/SNI; реже причина в пароле или совместимости WRAP. Воркеры остановлены."
|
||||
"\uD83C\uDF10 Сервер не ответил на WRAP через выбранный способ подключения. Возможны ограничения сети, недоступность сервера, неверный пароль или несовместимость WRAP. Каналы остановлены."
|
||||
} else {
|
||||
"\uD83D\uDD0C Сервер не ответил на WRAP. Возможны проблемы с сервером или маршрутом, блокировка UDP/TURN, неверный пароль либо несовместимость WRAP. Воркеры остановлены."
|
||||
}
|
||||
|
||||
internal const val RT_MASQUE_CONFIG_FILE_NAME = "rt-masque-v1.json"
|
||||
|
||||
internal fun shouldUseRtMasque(rtNetwork: Boolean, rtMasque: Boolean): Boolean =
|
||||
rtNetwork && rtMasque
|
||||
internal fun shouldUseRtMasque(rtMasque: Boolean): Boolean = rtMasque
|
||||
|
||||
internal fun shouldUseRtMasqueServerBootstrap(
|
||||
rtNetwork: Boolean,
|
||||
rtMasque: Boolean,
|
||||
serverBootstrap: Boolean,
|
||||
): Boolean = rtNetwork && rtMasque && serverBootstrap
|
||||
): Boolean = rtMasque && serverBootstrap
|
||||
|
||||
internal data class MasqueLogPresentation(
|
||||
val key: String,
|
||||
@@ -923,13 +962,15 @@ internal fun classifyMasqueLog(line: String): MasqueLogPresentation? {
|
||||
text.contains("конфигурация WARP подготовлена", ignoreCase = true) ->
|
||||
MasqueLogPresentation("masque_config_ready", "[MASQUE] Сохранённая регистрация WARP готова ✓")
|
||||
text.contains("Включён резерв", ignoreCase = true) ->
|
||||
MasqueLogPresentation("masque_enabled", "[MASQUE] Резерв включён: HTTP/2 (TCP/443), затем HTTP/3 (QUIC/443)")
|
||||
MasqueLogPresentation("masque_enabled", if (text.contains("только HTTP/2"))
|
||||
"[MASQUE] Резерв включён: HTTP/2 (TCP/443); HTTP/3 отключён режимом TCP/TLS"
|
||||
else "[MASQUE] Резерв включён: доступны HTTP/2 и HTTP/3")
|
||||
text.contains("Прямые TCP/TLS-пути", ignoreCase = true) ->
|
||||
MasqueLogPresentation("masque_fallback_start", "[MASQUE] Прямые TCP/TLS-пути РТ не ответили — запускаем CONNECT-IP до попытки UDP")
|
||||
MasqueLogPresentation("masque_fallback_start", "[MASQUE] Прямые TLS/TCP-подключения не удались — пробуем резерв через Cloudflare")
|
||||
text.contains("Последний резерв после MASQUE", ignoreCase = true) ->
|
||||
MasqueLogPresentation(
|
||||
"masque_udp_fallback",
|
||||
"[MASQUE] HTTP/2 и HTTP/3 не дали рабочий TURN — пробуем прямой UDP последним резервом",
|
||||
"[MASQUE] MASQUE не дал рабочего подключения — пробуем разрешённый резерв UDP",
|
||||
warning = true,
|
||||
)
|
||||
text.contains("Relay:", ignoreCase = true) && h2 ->
|
||||
@@ -951,13 +992,13 @@ internal fun classifyMasqueLog(line: String): MasqueLogPresentation? {
|
||||
(text.contains("не сработал", ignoreCase = true) || text.contains("потерян", ignoreCase = true)) && h2 ->
|
||||
MasqueLogPresentation(
|
||||
"masque_h2_failed",
|
||||
"[MASQUE] Путь HTTP/2/TCP/443 не сработал ($pathFailureReason); проверяем другие TURN-адреса и HTTP/3",
|
||||
"[MASQUE] Путь HTTP/2/TCP/443 не сработал ($pathFailureReason); остаются другие разрешённые варианты подключения",
|
||||
warning = true,
|
||||
)
|
||||
(text.contains("не сработал", ignoreCase = true) || text.contains("потерян", ignoreCase = true)) && h3 ->
|
||||
MasqueLogPresentation(
|
||||
"masque_h3_failed",
|
||||
"[MASQUE] Путь HTTP/3/QUIC/443 не сработал ($pathFailureReason); проверяем другие TURN-адреса и прямой UDP",
|
||||
"[MASQUE] Путь HTTP/3/QUIC/443 не сработал ($pathFailureReason); остаются другие разрешённые варианты подключения",
|
||||
warning = true,
|
||||
)
|
||||
else -> MasqueLogPresentation("masque_status", "[MASQUE] $text")
|
||||
@@ -985,6 +1026,13 @@ object TunnelManager {
|
||||
@Volatile
|
||||
private var process: Process? = null
|
||||
private val processInputLock = Any()
|
||||
private val processLifecycleLock = Any()
|
||||
@Volatile private var connectionRecoveryNetwork: Pair<Long, String?> = 0L to null
|
||||
@Volatile private var recoveryNetworkKey: String? = null
|
||||
@Volatile private var connectionRecoveryRestarts = 0
|
||||
@Volatile private var connectionRecoveryPaused = false
|
||||
@Volatile private var connectionRecoveryOffline = false
|
||||
private var connectionRecoveryJob: Job? = null
|
||||
private var readerJob: Job? = null
|
||||
private var watchdogJob: Job? = null
|
||||
private var wireGuardReloadJob: Job? = null
|
||||
@@ -1048,6 +1096,7 @@ object TunnelManager {
|
||||
@Volatile
|
||||
var isLoggingEnabled = true
|
||||
|
||||
val connectionPath = MutableStateFlow("")
|
||||
val running = MutableStateFlow(false)
|
||||
val transition = MutableStateFlow(TunnelTransition.IDLE)
|
||||
val activeTunnelProfile = MutableStateFlow<Int?>(null)
|
||||
@@ -1347,6 +1396,7 @@ object TunnelManager {
|
||||
|
||||
fun pollNetworkRecoveryAction(now: Long = System.currentTimeMillis()): NetworkRecoveryAction? {
|
||||
if (!running.value) return null
|
||||
if (process?.isAlive == true) return null
|
||||
if (isWakeRecoveryGraceActive(now)) return null
|
||||
if (AMNEZIA_STYLE_RECOVERY) {
|
||||
return pollStableNetworkRecoveryAction(now)
|
||||
@@ -1534,6 +1584,12 @@ object TunnelManager {
|
||||
updateLog("deploy_err_$hash", "[ДЕПЛОЙ] $message", 99, true)
|
||||
}
|
||||
|
||||
fun addDeployMessageLog(message: String, warning: Boolean = false) {
|
||||
val key = "deploy_${if (warning) "warning" else "info"}_${message.hashCode()}"
|
||||
val text = "[ДЕПЛОЙ] $message"
|
||||
if (warning) updateWarningLog(key, text, 20) else updateLog(key, text, 20, false)
|
||||
}
|
||||
|
||||
fun addDeploySuccessLog(message: String) {
|
||||
val hash = message.hashCode().toString() + System.currentTimeMillis()
|
||||
updateLog("deploy_ok_$hash", message, 2, false)
|
||||
@@ -1745,14 +1801,14 @@ object TunnelManager {
|
||||
activeHashIndex = 0
|
||||
currentParams = params
|
||||
activeMode.value = requestedMode
|
||||
proxyReadyAddress.value = null
|
||||
proxyReadyAddresses.value = emptyList()
|
||||
lastContext = appContext
|
||||
accessRefreshRequestedForProcess = false
|
||||
forceRegenerateUA = false
|
||||
currentCaptchaMode = params.captchaMode
|
||||
currentCaptchaSolveMethod = params.captchaSolveMethod
|
||||
}
|
||||
proxyReadyAddress.value = null
|
||||
proxyReadyAddresses.value = emptyList()
|
||||
|
||||
wgHelper = if (requestedMode == TUNNEL_MODE_VPN) WireGuardHelper(appContext) else null
|
||||
|
||||
@@ -1888,6 +1944,10 @@ object TunnelManager {
|
||||
"-n", totalWorkers.toString(),
|
||||
"-listen", "127.0.0.1:${params.port}"
|
||||
)
|
||||
val experiment = effectiveTransportExperiment(params.transportExperiment, requestedMode)
|
||||
cmd.add("-transport-experiment")
|
||||
cmd.add(experiment)
|
||||
if (BuildConfig.TRANSPORT_DIAGNOSTICS) cmd.add("-transport-metrics=true")
|
||||
cmd.add("-mode")
|
||||
cmd.add(requestedMode)
|
||||
if (tunnelModeUsesLocalProxy(requestedMode)) {
|
||||
@@ -1952,7 +2012,22 @@ object TunnelManager {
|
||||
)
|
||||
}
|
||||
cmd.add("-turn-stream-first=${params.rtNetwork}")
|
||||
if (params.rtNetwork) {
|
||||
updateLog(
|
||||
"connection_mode",
|
||||
"[Подключение] ${connectionModeTitle(params.rtNetwork)}" +
|
||||
(if (params.rtMasque) " · MASQUE разрешён" else " · MASQUE выключен"),
|
||||
3,
|
||||
)
|
||||
connectionRecoveryNetwork = 0L to ConnectionNetwork.cacheKey(appContext, params)
|
||||
connectionPath.value = ""
|
||||
connectionRecoveryPaused = false
|
||||
connectionRecoveryOffline = false
|
||||
if (!isSwitching) {
|
||||
connectionRecoveryRestarts = 0
|
||||
recoveryNetworkKey = connectionRecoveryNetwork.second
|
||||
}
|
||||
cmd.add("-connection-udp-backoff=${ConnectionNetwork.udpBackoffSeconds(appContext, connectionRecoveryNetwork.second)}")
|
||||
run {
|
||||
val turnSni = normalizeRtTurnSni(params.rtTurnSni)
|
||||
if (turnSni != null) {
|
||||
cmd.add("-turn-sni")
|
||||
@@ -1960,12 +2035,12 @@ object TunnelManager {
|
||||
} else if (params.rtTurnSni.isNotBlank()) {
|
||||
updateWarningLog(
|
||||
"rt_sni_invalid",
|
||||
"[TURN] SNI режима «Сеть РТ» имеет неверный формат; запускаем TCP/TLS без подмены SNI",
|
||||
"[TURN] Внешний SNI имеет неверный формат; запускаем TCP/TLS без подмены SNI",
|
||||
20,
|
||||
)
|
||||
}
|
||||
}
|
||||
val useRtMasque = shouldUseRtMasque(params.rtNetwork, params.rtMasque)
|
||||
val useRtMasque = shouldUseRtMasque(params.rtMasque)
|
||||
cmd.add("-rt-masque=$useRtMasque")
|
||||
if (useRtMasque) {
|
||||
val masqueConfig = File(appContext.filesDir, RT_MASQUE_CONFIG_FILE_NAME)
|
||||
@@ -1975,7 +2050,6 @@ object TunnelManager {
|
||||
if (
|
||||
!masqueConfig.exists() &&
|
||||
shouldUseRtMasqueServerBootstrap(
|
||||
rtNetwork = params.rtNetwork,
|
||||
rtMasque = params.rtMasque,
|
||||
serverBootstrap = params.rtMasqueServerBootstrap,
|
||||
)
|
||||
@@ -1995,7 +2069,7 @@ object TunnelManager {
|
||||
WarpApiSshRelayStartResult.MissingProfileAccess -> {
|
||||
updateWarningLog(
|
||||
"masque_server_bootstrap_missing",
|
||||
"[MASQUE] «Через сервер» недоступен: в «Деплой» нет адреса сервера или выбранного SSH-доступа (пароль/приватный ключ); пробуем прямую регистрацию",
|
||||
"[MASQUE] «Регистрация по SSH» недоступна: в «Деплой → SSH» нет адреса сервера или выбранного SSH-доступа (пароль/приватный ключ); пробуем прямую регистрацию",
|
||||
20,
|
||||
)
|
||||
}
|
||||
@@ -2038,7 +2112,7 @@ object TunnelManager {
|
||||
env.remove("WDTT_CUSTOM_VK_CLIENT_ID")
|
||||
env.remove("WDTT_CUSTOM_VK_CLIENT_SECRET")
|
||||
|
||||
process = pb.start()
|
||||
process = startNativeProcess(pb)
|
||||
peerDnsWaitStartedAtMs = 0L
|
||||
val startupLine = nativeClientStartupConfigLine(
|
||||
NativeClientStartupSecrets(
|
||||
@@ -2066,6 +2140,7 @@ object TunnelManager {
|
||||
// Передаём сохранённое состояние после запуска процесса.
|
||||
sendTransportLifecycleCommand("DEVICE_SLEEP")
|
||||
}
|
||||
startConnectionMonitor(appContext, params)
|
||||
startWatchdog(appContext, params)
|
||||
|
||||
} catch (e: Exception) {
|
||||
@@ -2111,6 +2186,36 @@ object TunnelManager {
|
||||
// Output buffered by a process that has just been replaced must
|
||||
// not poison the recovery state of the new transport generation.
|
||||
if (!isActive || process !== observedProcess) return@forEachLine
|
||||
if (line.contains("[CONNECTION]")) {
|
||||
val event = line.substringAfter("[CONNECTION] ")
|
||||
if (event.startsWith("READY ")) {
|
||||
val parts = event.split(' ')
|
||||
val network = connectionRecoveryNetwork
|
||||
if (parts.size == 3 && parts[1].toLongOrNull() == network.first) {
|
||||
lastContext?.let { ConnectionNetwork.noteReady(it, network.second, parts[2]) }
|
||||
connectionPath.value = connectionPathTitle(parts[2]).orEmpty()
|
||||
connectionRecoveryPaused = false
|
||||
}
|
||||
} else if (event.startsWith("UDP_BACKOFF ")) {
|
||||
val epoch = event.substringAfter("UDP_BACKOFF ").toLongOrNull()
|
||||
val network = connectionRecoveryNetwork
|
||||
if (epoch == network.first) lastContext?.let { ConnectionNetwork.noteUdpFailure(it, network.second) }
|
||||
} else if (event.startsWith("PAUSED ")) {
|
||||
connectionRecoveryPaused = true
|
||||
setConnectionIssue("Попытки приостановлены", "Не удалось найти рабочий путь. Смените сеть или подключитесь заново. Ручной выбор — в разделе «Подключение».")
|
||||
}
|
||||
connectionEventLog(event, connectionRecoveryNetwork.first)?.let { entry ->
|
||||
if (entry.warning) {
|
||||
updateWarningLog("connection_policy_${entry.key}", "[Подключение] ${entry.message}", 10)
|
||||
} else {
|
||||
if (entry.key.startsWith("ready_")) {
|
||||
logs.update { entries -> entries.filterNot { it.key == "connection_policy_paused" } }
|
||||
}
|
||||
updateLog("connection_policy_${entry.key}", "[Подключение] ${entry.message}", 10)
|
||||
}
|
||||
}
|
||||
return@forEachLine
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - lastResetTime > 60000) {
|
||||
refusedCount = 0
|
||||
@@ -2279,6 +2384,27 @@ object TunnelManager {
|
||||
stop(TunnelStopReason.CriticalError)
|
||||
return@forEachLine
|
||||
}
|
||||
if (lineTrim.contains("[ОТДАЧА]")) {
|
||||
if (BuildConfig.TRANSPORT_DIAGNOSTICS) {
|
||||
val text = lineTrim.substringAfter("[ОТДАЧА]").trim()
|
||||
val channel = Regex("Канал #(\\d+)").find(text)?.groupValues?.get(1)
|
||||
updateLog("uplink_delivery_${channel ?: "status"}", "[ОТДАЧА] $text", 20, false)
|
||||
}
|
||||
return@forEachLine
|
||||
}
|
||||
if (lineTrim.startsWith("TRANSPORT_METRIC|") || lineTrim.startsWith("TRANSPORT_ORDER|")) {
|
||||
if (BuildConfig.TRANSPORT_DIAGNOSTICS) android.util.Log.i("WDTTTransport", lineTrim)
|
||||
return@forEachLine
|
||||
}
|
||||
if (lineTrim.contains("FATAL_TRANSPORT:")) {
|
||||
setConnectionIssue(
|
||||
"Адаптивный транспорт недоступен",
|
||||
"Переподключите туннель. Если ошибка повторяется, обновите сервер.",
|
||||
)
|
||||
updateLog("transport_error", "[ТРАНСПОРТ] Адаптивный режим не запущен", 99, true)
|
||||
stop(TunnelStopReason.CriticalError)
|
||||
return@forEachLine
|
||||
}
|
||||
if (lineTrim.startsWith("PROXY_READY|")) {
|
||||
val parts = lineTrim.substringAfter("PROXY_READY|").split('|')
|
||||
val readyMode = normalizeTunnelMode(parts.getOrNull(0))
|
||||
@@ -2309,15 +2435,13 @@ object TunnelManager {
|
||||
return@forEachLine
|
||||
}
|
||||
if (lineTrim.startsWith("PROXY_ERROR|")) {
|
||||
val reason = lineTrim.substringAfter("PROXY_ERROR|")
|
||||
.ifBlank { "неизвестная ошибка" }
|
||||
proxyReadyAddress.value = null
|
||||
proxyReadyAddresses.value = emptyList()
|
||||
setConnectionIssue(
|
||||
"Прокси не запустился",
|
||||
"Проверьте порт, сеть и настройки аутентификации. Причина: $reason",
|
||||
val presentation = proxyErrorPresentation(
|
||||
lineTrim.substringAfter("PROXY_ERROR|"),
|
||||
)
|
||||
updateLog("proxy_error", "[ПРОКСИ] $reason", 99, true)
|
||||
proxyReadyAddress.value = presentation.readyAddress
|
||||
proxyReadyAddresses.value = presentation.readyAddresses
|
||||
connectionIssue.value = presentation.issue
|
||||
updateLog("proxy_error", presentation.logMessage, 99, true)
|
||||
stop(TunnelStopReason.CriticalError)
|
||||
return@forEachLine
|
||||
}
|
||||
@@ -3113,7 +3237,7 @@ object TunnelManager {
|
||||
setConnectionIssue("Системная ошибка туннеля", "Попробуйте подключиться снова. Причина: $message")
|
||||
}
|
||||
} finally {
|
||||
if (process === observedProcess) {
|
||||
if (process === observedProcess && !observedProcess.isAlive) {
|
||||
process = null
|
||||
failPendingUpdateMetadataRequests()
|
||||
failPendingOpaqueHttpsRequests("Соединение WDTT остановлено")
|
||||
@@ -3157,6 +3281,50 @@ object TunnelManager {
|
||||
}
|
||||
}
|
||||
|
||||
private fun startConnectionMonitor(context: Context, params: TunnelParams) {
|
||||
connectionRecoveryJob?.cancel()
|
||||
val observedProcess = process ?: return
|
||||
connectionRecoveryJob = scope.launch(Dispatchers.IO) {
|
||||
var reachability = ConnectionReachability()
|
||||
var lastCheck = 0L
|
||||
var baselineChecked = false
|
||||
while (isActive && process === observedProcess && observedProcess.isAlive) {
|
||||
val key = ConnectionNetwork.cacheKey(context, params)
|
||||
if (key != connectionRecoveryNetwork.second) {
|
||||
connectionRecoveryNetwork = (connectionRecoveryNetwork.first + 1L) to key
|
||||
reachability = ConnectionReachability()
|
||||
baselineChecked = false
|
||||
connectionRecoveryPaused = false
|
||||
connectionRecoveryRestarts = 0
|
||||
sendTransportLifecycleCommand("CONNECTION_NETWORK")
|
||||
}
|
||||
val network = ConnectionNetwork.underlying(context)
|
||||
var offline = network == null
|
||||
val now = System.currentTimeMillis()
|
||||
if (network != null && !deviceSleeping &&
|
||||
(!baselineChecked || activeWorkers.value == 0) && now - lastCheck >= 30_000L
|
||||
) {
|
||||
lastCheck = now
|
||||
val first = ConnectionNetwork.reachable(network, "vk.com")
|
||||
val second = ConnectionNetwork.reachable(network, "max.ru")
|
||||
if (process !== observedProcess || key != ConnectionNetwork.cacheKey(context, params)) continue
|
||||
baselineChecked = true
|
||||
offline = reachability.observe(first, second)
|
||||
} else if (network != null) {
|
||||
offline = connectionRecoveryOffline && activeWorkers.value == 0
|
||||
}
|
||||
if (offline != connectionRecoveryOffline) {
|
||||
connectionRecoveryOffline = offline
|
||||
sendTransportLifecycleCommand(if (offline) "CONNECTION_OFFLINE" else "CONNECTION_ONLINE")
|
||||
if (offline) {
|
||||
setConnectionIssue("Ожидание сети", "Новые попытки приостановлены: базовое соединение недоступно. Проверка продолжится автоматически.")
|
||||
}
|
||||
}
|
||||
delay(5_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun startWatchdog(context: Context, params: TunnelParams) {
|
||||
watchdogJob?.cancel()
|
||||
watchdogJob = scope.launch {
|
||||
@@ -3205,6 +3373,10 @@ object TunnelManager {
|
||||
processDeadSince = 0L
|
||||
}
|
||||
|
||||
if (proc?.isAlive == true) {
|
||||
delay(5_000)
|
||||
continue
|
||||
}
|
||||
val workers = activeWorkers.value
|
||||
if (workers <= 0) {
|
||||
if (zeroWorkersSince == 0L) {
|
||||
@@ -3259,6 +3431,16 @@ object TunnelManager {
|
||||
): Boolean {
|
||||
val params = currentParams ?: return false
|
||||
val context = lastContext ?: return false
|
||||
run {
|
||||
val key = ConnectionNetwork.cacheKey(context, params)
|
||||
if (key != recoveryNetworkKey) {
|
||||
recoveryNetworkKey = key
|
||||
connectionRecoveryRestarts = 0
|
||||
connectionRecoveryPaused = false
|
||||
connectionRecoveryOffline = key == null
|
||||
}
|
||||
if (connectionRecoveryPaused || connectionRecoveryOffline || connectionRecoveryRestarts >= 1) return false
|
||||
}
|
||||
if (resetNetworkRecovery) {
|
||||
// Wake rescue is already the decision taken for the previous
|
||||
// transport generation. Its delayed health lines must not trigger
|
||||
@@ -3277,6 +3459,7 @@ object TunnelManager {
|
||||
return false
|
||||
}
|
||||
lastSoftRestartAtMs = now
|
||||
connectionRecoveryRestarts++
|
||||
softRestartCount++
|
||||
updateLog("network_restart", reason, 50, false)
|
||||
activeWorkers.value = 0
|
||||
@@ -3747,33 +3930,59 @@ object TunnelManager {
|
||||
watchdogJob?.cancel()
|
||||
}
|
||||
readerJob?.cancel()
|
||||
val proc = process
|
||||
process = null
|
||||
failPendingUpdateMetadataRequests()
|
||||
failPendingOpaqueHttpsRequests("Соединение WDTT остановлено")
|
||||
failPendingUpdateApkRequests()
|
||||
failPendingDeploySafeRequests("Соединение WDTT остановлено")
|
||||
if (proc != null) {
|
||||
try {
|
||||
synchronized(processInputLock) {
|
||||
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(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) {}
|
||||
if (tunnelModeUsesLocalProxy(activeMode.value)) {
|
||||
proxyReadyAddress.value = null
|
||||
proxyReadyAddresses.value = emptyList()
|
||||
}
|
||||
synchronized(processLifecycleLock) {
|
||||
val stopped = process?.let(::stopNativeProcessLocked) ?: true
|
||||
if (stopped) {
|
||||
process = null
|
||||
} else {
|
||||
// Keep ownership and let a later recovery retry. Never crash
|
||||
// the application or overlap two transport generations.
|
||||
updateWarningLog("native_stop_pending", "[СВЯЗЬ] Завершение предыдущего транспорта задержалось; повторное подключение ожидает его остановки.", 50)
|
||||
}
|
||||
}
|
||||
closeWarpApiSshRelay()
|
||||
resetWakeRecoveryState()
|
||||
}
|
||||
|
||||
private fun startNativeProcess(builder: ProcessBuilder): Process =
|
||||
synchronized(processLifecycleLock) {
|
||||
// A recovery/resume request can arrive while the previous reader is
|
||||
// still unwinding. Never overlap two libclient processes: retain the
|
||||
// Process handle until the OS confirms exit, then start the new one.
|
||||
check(process?.let(::stopNativeProcessLocked) != false) {
|
||||
"предыдущий нативный процесс ещё завершает работу"
|
||||
}
|
||||
builder.start().also { process = it }
|
||||
}
|
||||
|
||||
private fun stopNativeProcessLocked(proc: Process): Boolean {
|
||||
if (!proc.isAlive) return true
|
||||
try {
|
||||
synchronized(processInputLock) {
|
||||
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(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) {}
|
||||
}
|
||||
return !proc.isAlive
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun closeWarpApiSshRelay() {
|
||||
val relay = warpApiSshRelay
|
||||
@@ -4420,6 +4629,7 @@ object TunnelManager {
|
||||
}
|
||||
|
||||
data class TunnelParams(
|
||||
val transportExperiment: String = TRANSPORT_AUTO,
|
||||
val peer: String,
|
||||
val vkHashes: String,
|
||||
val secondaryVkHash: String = "",
|
||||
|
||||
@@ -649,6 +649,7 @@ class TunnelService : Service() {
|
||||
connectionPassword = intent.getStringExtra("connection_password") ?: "",
|
||||
protocol = intent.getStringExtra("protocol") ?: "udp",
|
||||
vkCallsPreflight = intent.getBooleanExtra("vkcalls_preflight", true),
|
||||
transportExperiment = effectiveTransportExperiment(intent.getStringExtra("transport_experiment"), requestedMode),
|
||||
rtNetwork = intent.getBooleanExtra("rt_network", false),
|
||||
rtMasque = intent.getBooleanExtra("rt_masque", false),
|
||||
rtMasqueServerBootstrap =
|
||||
@@ -3273,7 +3274,6 @@ class TunnelService : Service() {
|
||||
TunnelManager.transition.value == TunnelTransition.STARTING &&
|
||||
lastStartParams?.let { params ->
|
||||
shouldUseRtMasqueServerBootstrap(
|
||||
rtNetwork = params.rtNetwork,
|
||||
rtMasque = params.rtMasque,
|
||||
serverBootstrap = params.rtMasqueServerBootstrap,
|
||||
)
|
||||
|
||||
@@ -232,6 +232,7 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
||||
connectionPassword = linkParts.password,
|
||||
protocol = saved.protocol,
|
||||
vkCallsPreflight = saved.vkCallsPreflight,
|
||||
transportExperiment = effectiveTransportExperiment(saved.transportExperiment, normalizeTunnelMode(saved.proxyMode)),
|
||||
rtNetwork = saved.rtNetwork,
|
||||
rtMasque = saved.rtMasque,
|
||||
rtMasqueServerBootstrap =
|
||||
@@ -276,6 +277,7 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
||||
connectionPassword = password,
|
||||
protocol = saved.protocol,
|
||||
vkCallsPreflight = saved.vkCallsPreflight,
|
||||
transportExperiment = effectiveTransportExperiment(saved.transportExperiment, normalizeTunnelMode(saved.proxyMode)),
|
||||
rtNetwork = saved.rtNetwork,
|
||||
rtMasque = saved.rtMasque,
|
||||
rtMasqueServerBootstrap =
|
||||
@@ -319,6 +321,7 @@ suspend fun buildTunnelStartIntentFromSettings(
|
||||
putExtra("connection_password", params.connectionPassword)
|
||||
putExtra("protocol", params.protocol)
|
||||
putExtra("vkcalls_preflight", params.vkCallsPreflight)
|
||||
putExtra("transport_experiment", params.transportExperiment)
|
||||
putExtra("rt_network", params.rtNetwork)
|
||||
putExtra("rt_masque", params.rtMasque)
|
||||
putExtra("rt_masque_server_bootstrap", params.rtMasqueServerBootstrap)
|
||||
|
||||
@@ -46,6 +46,13 @@ object VkJoinLink {
|
||||
return values.map(::extractHash).distinct().joinToString(",")
|
||||
}
|
||||
|
||||
/** True only when the profile already contains four distinct valid call hashes. */
|
||||
fun hasCompleteHashSet(input: String): Boolean =
|
||||
normalizeHashes(input)
|
||||
?.split(',')
|
||||
?.filter(String::isNotBlank)
|
||||
?.size == 4
|
||||
|
||||
fun extractValidHash(input: String): String =
|
||||
extractHash(input).takeIf { isValidInput(input) }.orEmpty()
|
||||
}
|
||||
@@ -62,6 +62,34 @@ internal fun effectiveWireGuardAllowedIps(
|
||||
}
|
||||
}.distinct()
|
||||
|
||||
/**
|
||||
* Removes a bounded set of exact IPv4 destinations from the routes captured by
|
||||
* Android's VPN interface. This is used by an optional local continuation to
|
||||
* keep the normal WDTT route alive while selected external HTTPS destinations
|
||||
* use the phone's underlying network. User routing settings are not mutated.
|
||||
*/
|
||||
internal fun applyTemporaryDirectIpv4Addresses(
|
||||
allowedIps: List<String>,
|
||||
directAddresses: Collection<String>,
|
||||
): List<String> {
|
||||
val excluded = directAddresses
|
||||
.mapNotNull(::parseIpv4)
|
||||
.distinct()
|
||||
.map { address -> Ipv4Prefix(address, IPV4_BITS) }
|
||||
if (excluded.isEmpty()) return allowedIps.distinct()
|
||||
|
||||
val ipv4Routes = allowedIps.mapNotNull(::parseIpv4Prefix)
|
||||
val nonIpv4Routes = allowedIps.filter { parseIpv4Prefix(it) == null }
|
||||
val routedIpv4 = subtractIpv4Prefixes(ipv4Routes, excluded)
|
||||
.sortedWith(compareBy<Ipv4Prefix> { it.network }.thenBy { it.length })
|
||||
.map(Ipv4Prefix::toCidr)
|
||||
return (routedIpv4 + nonIpv4Routes).distinct().also { routes ->
|
||||
require(routes.size <= MAX_WIREGUARD_ALLOWED_IPS) {
|
||||
"Временная прямая маршрутизация создаёт слишком много маршрутов (${routes.size})."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class VpnRoutingDocument(
|
||||
val isWhitelist: Boolean,
|
||||
val blacklistApps: List<String>,
|
||||
|
||||
@@ -23,6 +23,7 @@ class WdttApplication : Application() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
if (LocalBuildExtensions.initializeAuxiliaryProcess(this)) return
|
||||
DeployManager.init(this)
|
||||
|
||||
val settingsStore = SettingsStore(this)
|
||||
|
||||
@@ -122,7 +122,16 @@ class WireGuardHelper(context: Context) {
|
||||
.toSet()
|
||||
val isWhitelist = routingSettings.isWhitelist
|
||||
val addressRules = routingSettings.addressRules
|
||||
val resolvedDomains = resolveAddressRuleDomains(addressRules)
|
||||
val temporaryDirectDomains = TemporaryDirectRouteRegistry.currentDomains()
|
||||
val temporaryDirectRules = temporaryDirectDomains.map { domain ->
|
||||
VpnAddressRule(VpnAddressType.DOMAIN, domain)
|
||||
}
|
||||
val resolvedDomains = resolveAddressRuleDomains(addressRules + temporaryDirectRules)
|
||||
TemporaryDirectRouteRegistry.recordResolvedDomains(
|
||||
temporaryDirectDomains.filterTo(linkedSetOf()) { domain ->
|
||||
resolvedDomains[domain].orEmpty().any(::isIpv4Literal)
|
||||
}
|
||||
)
|
||||
val addressRouting = runCatching {
|
||||
resolveVpnAddressRouting(
|
||||
isWhitelist = isWhitelist,
|
||||
@@ -167,9 +176,14 @@ class WireGuardHelper(context: Context) {
|
||||
} else if (routing.excluded.isNotEmpty()) {
|
||||
builder.excludeApplications(routing.excluded)
|
||||
}
|
||||
val routedAllowedIps = applyVpnAppRoutingToAllowedIps(
|
||||
routing = routing,
|
||||
allowedIps = effectiveAllowedIps,
|
||||
val routedAllowedIps = applyTemporaryDirectIpv4Addresses(
|
||||
allowedIps = applyVpnAppRoutingToAllowedIps(
|
||||
routing = routing,
|
||||
allowedIps = effectiveAllowedIps,
|
||||
),
|
||||
directAddresses = temporaryDirectDomains.flatMap { domain ->
|
||||
resolvedDomains[domain].orEmpty()
|
||||
},
|
||||
)
|
||||
|
||||
val routingMode = if (isWhitelist) "белый список" else "чёрный список"
|
||||
@@ -183,6 +197,9 @@ class WireGuardHelper(context: Context) {
|
||||
append("«$profileLabel»: $routingMode; правил приложений: $appRuleCount, ")
|
||||
append("правил адресов: ${addressRules.size}, маршрутов VPN: ${routedAllowedIps.size}; ")
|
||||
append(if (fullIpv4Tunnel) "IPv4 идёт через VPN полностью" else "действует раздельная маршрутизация")
|
||||
if (temporaryDirectDomains.isNotEmpty()) {
|
||||
append("; временных прямых назначений: ${temporaryDirectDomains.size}")
|
||||
}
|
||||
if (routing.blocksAllApps) append("; пустой белый список блокирует пользовательский трафик")
|
||||
},
|
||||
)
|
||||
@@ -282,9 +299,9 @@ class WireGuardHelper(context: Context) {
|
||||
)
|
||||
Log.d("WG", "WireGuard tunnel started successfully")
|
||||
} catch (e: Exception) {
|
||||
val stillUp = sharedTunnel?.let { tunnel ->
|
||||
val stillUp = (sharedTunnel?.let { tunnel ->
|
||||
runCatching { backend.getState(tunnel) == Tunnel.State.UP }.getOrDefault(false)
|
||||
} ?: false
|
||||
} ?: false)
|
||||
TunnelManager.noteVpnInterfaceState(stillUp)
|
||||
val detailed = "WireGuard start failed: ${e.readableMessage()}; ${configString.describeWireGuardConfig()}"
|
||||
Log.e("WG", detailed)
|
||||
@@ -293,19 +310,21 @@ class WireGuardHelper(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun reloadTunnel() = wgMutex.withLock {
|
||||
suspend fun reloadTunnel(): Boolean = wgMutex.withLock {
|
||||
withContext(Dispatchers.IO) {
|
||||
if (sharedTunnel == null) return@withContext
|
||||
if (sharedTunnel == null) return@withContext false
|
||||
try {
|
||||
val configFlow = TunnelManager.config.first() ?: return@withContext
|
||||
val configFlow = TunnelManager.config.first() ?: return@withContext false
|
||||
startTunnelLocked(configFlow)
|
||||
Log.d("WG", "WireGuard tunnel reloaded for updated profile settings")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e("WG", "Failed to reload WireGuard: ${e.readableMessage()}")
|
||||
TunnelManager.noteVpnInterfaceReloadWarning(
|
||||
message = "Новые настройки маршрутизации или DNS не применились: ${e.readableMessage()}. " +
|
||||
"Рабочая конфигурация сохранена, если Android смог её восстановить.",
|
||||
)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -363,9 +382,9 @@ class WireGuardHelper(context: Context) {
|
||||
}
|
||||
TunnelManager.noteVpnInterfaceState(false)
|
||||
} catch (e: Exception) {
|
||||
val stillUp = sharedTunnel?.let { tunnel ->
|
||||
val stillUp = (sharedTunnel?.let { tunnel ->
|
||||
runCatching { backend.getState(tunnel) == Tunnel.State.UP }.getOrDefault(false)
|
||||
} ?: false
|
||||
} ?: false)
|
||||
TunnelManager.noteVpnInterfaceState(stillUp)
|
||||
Log.e("WG", "Failed to stop WireGuard: ${e.readableMessage()}")
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Update
|
||||
@@ -28,7 +30,6 @@ import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
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 com.wdtt.plus.AppReleaseInfo
|
||||
import com.wdtt.plus.AppReleaseAsset
|
||||
@@ -74,7 +75,7 @@ fun AppUpdateDialog(
|
||||
else -> "Открыть"
|
||||
}
|
||||
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = {},
|
||||
properties = DialogProperties(
|
||||
usePlatformDefaultWidth = false,
|
||||
@@ -92,7 +93,8 @@ fun AppUpdateDialog(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 22.dp, vertical = 20.dp),
|
||||
.padding(horizontal = 22.dp, vertical = 20.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/** Shared check/cancel control without a rectangular pressed background. */
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
internal fun CheckActionIcon(
|
||||
checking: Boolean,
|
||||
enabled: Boolean = true,
|
||||
idleIcon: ImageVector,
|
||||
description: String,
|
||||
cancelDescription: String,
|
||||
onClick: () -> Unit,
|
||||
onLongClick: (() -> Unit)? = null,
|
||||
) {
|
||||
val showHint = rememberIconHint(description)
|
||||
Box(
|
||||
modifier = Modifier.size(40.dp).clip(CircleShape)
|
||||
.remoteIconButtonFocus(enabled = enabled)
|
||||
.combinedClickable(
|
||||
interactionSource = remember { MutableInteractionSource() },
|
||||
indication = null,
|
||||
enabled = enabled,
|
||||
role = Role.Button,
|
||||
onClick = onClick,
|
||||
onLongClick = if (checking) null else onLongClick ?: showHint,
|
||||
),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
val color = MaterialTheme.colorScheme.primary.copy(alpha = if (enabled) 1f else 0.42f)
|
||||
if (checking) {
|
||||
CircularProgressIndicator(Modifier.size(28.dp), color = color, strokeWidth = 2.dp)
|
||||
}
|
||||
Icon(
|
||||
if (checking) Icons.Default.Close else idleIcon,
|
||||
contentDescription = if (checking) cancelDescription else description,
|
||||
modifier = Modifier.size(if (checking) 15.dp else 21.dp),
|
||||
tint = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,32 +2,24 @@ package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
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.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
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.Error
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.FilledTonalIconButton
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -40,8 +32,6 @@ import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
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 com.wdtt.plus.DeviceCheckAction
|
||||
import com.wdtt.plus.DeviceCheckItem
|
||||
import com.wdtt.plus.DeviceCheckSeverity
|
||||
@@ -58,156 +48,91 @@ fun DeviceCompatibilityDialog(
|
||||
onCopy: (() -> Unit)? = null,
|
||||
onAction: ((DeviceCheckAction) -> Unit)? = null
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
val visibleItems = remember(report) {
|
||||
report.items.ifEmpty {
|
||||
listOf(
|
||||
DeviceCheckItem(
|
||||
title = "Проверка устройства",
|
||||
status = "замечаний нет",
|
||||
details = "Архитектурных проблем для запуска WDTT Plus не найдено.",
|
||||
severity = DeviceCheckSeverity.Ok
|
||||
)
|
||||
)
|
||||
listOf(DeviceCheckItem("Проверка", "замечаний нет",
|
||||
"Проблем для запуска WDTT Plus не найдено."))
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
SettingsDialogLayout(
|
||||
title = title,
|
||||
onDismiss = onDismiss,
|
||||
footer = onCopy?.let { copy ->
|
||||
{
|
||||
Button(
|
||||
onClick = copy,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
|
||||
) {
|
||||
Icon(Icons.Default.ContentCopy, null, Modifier.size(18.dp))
|
||||
Spacer(Modifier.size(8.dp))
|
||||
FlexibleButtonText("Скопировать отчёт", fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
BoxWithConstraints(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(8.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.46f),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 8.dp,
|
||||
shadowElevation = 18.dp,
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.heightIn(max = maxHeight * 0.92f)
|
||||
.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp)
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
val summarySeverity = if (report.hasErrors) {
|
||||
DeviceCheckSeverity.Error
|
||||
} else if (report.problemItems.isNotEmpty()) {
|
||||
DeviceCheckSeverity.Warning
|
||||
} else {
|
||||
DeviceCheckSeverity.Ok
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.Top
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = when (summarySeverity) {
|
||||
DeviceCheckSeverity.Error -> Icons.Default.Error
|
||||
DeviceCheckSeverity.Warning -> Icons.Default.Warning
|
||||
else -> Icons.Default.CheckCircle
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = severityColor(summarySeverity),
|
||||
modifier = Modifier
|
||||
.padding(top = 2.dp)
|
||||
.size(22.dp)
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(
|
||||
title,
|
||||
modifier = Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
"Итог: ${report.overallStatus}",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
FilledTonalIconButton(onClick = onDismiss) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 18.sp
|
||||
)
|
||||
}
|
||||
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.46f),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
val summarySeverity = if (report.hasErrors) {
|
||||
DeviceCheckSeverity.Error
|
||||
} else if (report.problemItems.isNotEmpty()) {
|
||||
DeviceCheckSeverity.Warning
|
||||
} else {
|
||||
DeviceCheckSeverity.Ok
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.Top
|
||||
) {
|
||||
Icon(
|
||||
imageVector = when (summarySeverity) {
|
||||
DeviceCheckSeverity.Error -> Icons.Default.Error
|
||||
DeviceCheckSeverity.Warning -> Icons.Default.Warning
|
||||
else -> Icons.Default.CheckCircle
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = severityColor(summarySeverity),
|
||||
modifier = Modifier
|
||||
.padding(top = 2.dp)
|
||||
.size(22.dp)
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(
|
||||
"Итог: ${report.overallStatus}",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 18.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
note,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 18.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
visibleItems.forEach { item ->
|
||||
DeviceCheckItemCard(item = item, onAction = onAction)
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
if (onCopy != null) {
|
||||
OutlinedButton(
|
||||
onClick = onCopy,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(modifier = Modifier.size(8.dp))
|
||||
Text("Скопировать отчёт")
|
||||
}
|
||||
}
|
||||
Button(
|
||||
onClick = onDismiss,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text("Понятно", fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
}
|
||||
Text(
|
||||
note,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 18.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
visibleItems.forEach { item ->
|
||||
DeviceCheckItemCard(item = item, onAction = onAction)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,6 @@ import androidx.compose.material.icons.filled.Hub
|
||||
import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material.icons.filled.SettingsEthernet
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CheckboxDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
@@ -759,14 +758,14 @@ private fun RoutingTitleRow(
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
disabledContentColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),
|
||||
)
|
||||
IconButton(
|
||||
HintIconButton(hint = "Импорт маршрутизации",
|
||||
onClick = onImport,
|
||||
enabled = enabled,
|
||||
colors = iconButtonColors,
|
||||
) {
|
||||
Icon(Icons.Default.FileDownload, contentDescription = "Импорт маршрутизации")
|
||||
}
|
||||
IconButton(
|
||||
HintIconButton(hint = "Экспорт маршрутизации",
|
||||
onClick = onExport,
|
||||
enabled = enabled,
|
||||
colors = iconButtonColors,
|
||||
@@ -799,7 +798,7 @@ private fun RoutingModeCard(
|
||||
Column(modifier = Modifier.weight(1f).padding(end = 8.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Режим списка", fontWeight = FontWeight.SemiBold)
|
||||
IconButton(
|
||||
HintIconButton(hint = "Инструкция по режиму списка",
|
||||
onClick = onHelp,
|
||||
modifier = Modifier.size(30.dp).remoteHelpFocus(),
|
||||
) {
|
||||
@@ -874,7 +873,7 @@ private fun AppsRoutingHeader(
|
||||
onClick = onQuickExclusions,
|
||||
enabled = !isWhitelist && !isLoading,
|
||||
contentPadding = PaddingValues(horizontal = 2.dp),
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
) {
|
||||
if (quickExcludeStatus.isBlank()) {
|
||||
Text(
|
||||
@@ -900,7 +899,7 @@ private fun AppsRoutingHeader(
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(
|
||||
HintIconButton(hint = "Инструкция по быстрым исключениям",
|
||||
onClick = onQuickHelp,
|
||||
modifier = Modifier.size(38.dp).remoteHelpFocus(),
|
||||
) {
|
||||
@@ -1046,7 +1045,14 @@ private fun AddressesRoutingHeader(
|
||||
)
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f).padding(horizontal = 12.dp)) {
|
||||
Text("Добавить адрес", fontWeight = FontWeight.SemiBold)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Добавить адрес", fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.weight(1f, fill = false))
|
||||
HintIconButton(hint = "Инструкция по адресам", onClick = onHelp, modifier = Modifier.size(30.dp).remoteHelpFocus()) {
|
||||
Icon(Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Инструкция по адресам", modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Домен, URL, IPv4, CIDR или диапазон",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
@@ -1055,15 +1061,7 @@ private fun AddressesRoutingHeader(
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = onHelp,
|
||||
modifier = Modifier.remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Инструкция по адресам",
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1112,7 +1110,7 @@ private fun AddAddressDialog(
|
||||
}
|
||||
val previewRules = previewResult?.getOrNull()
|
||||
val validationError = previewResult?.exceptionOrNull()?.message.orEmpty()
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = {
|
||||
Row(
|
||||
@@ -1190,8 +1188,6 @@ private fun AddAddressDialog(
|
||||
|
||||
@Composable
|
||||
private fun RoutingHelpDialog(help: RoutingHelp, onDismiss: () -> Unit) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
val title: String
|
||||
val body: String
|
||||
when (help) {
|
||||
@@ -1212,41 +1208,12 @@ private fun RoutingHelpDialog(help: RoutingHelp, onDismiss: () -> Unit) {
|
||||
body = "В ЧС выбранные адреса идут напрямую, в БС — только выбранные адреса идут через VPN. Можно вставить несколько строк: точные домены, ссылки, домены или IPv4 с портом, отдельные IPv4, подсети CIDR и диапазоны IPv4. Порт удаляется, а диапазон преобразуется в минимальный набор подсетей. Домен при запуске VPN преобразуется в его текущие IPv4-адреса, поэтому после смены DNS-адресов перезапустите VPN. Значение ru обозначает доменную зону, а не все сайты .ru. Доменные зоны и маски *.example.org требуют отдельного DNS-перехватчика; обычный WireGuard принимает только IP-маршруты, поэтому такие правила и IPv6 сейчас не применяются. Если в БС заполнены приложения и адреса, через VPN пойдёт трафик выбранных приложений к выбранным адресам."
|
||||
}
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
modifier = Modifier.televisionDialogWidth(television),
|
||||
title = {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
title,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = "Закрыть инструкцию",
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
text = {
|
||||
Text(
|
||||
body,
|
||||
modifier = Modifier
|
||||
.heightIn(max = if (television) 520.dp else 360.dp)
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
)
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text("Понятно") } },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = !television),
|
||||
)
|
||||
SettingsDialogLayout(
|
||||
title = title,
|
||||
onDismiss = onDismiss,
|
||||
) {
|
||||
Text(body)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
/** Keep the error marker and its details even after a long install/progress log. */
|
||||
internal fun rootScriptErrorExcerpt(output: String): String {
|
||||
val marker = Regex("(?m)^WDTT_ERROR=").findAll(output).lastOrNull()
|
||||
return if (marker != null) output.substring(marker.range.first).take(1600)
|
||||
else output.takeLast(1600)
|
||||
}
|
||||
|
||||
internal fun externalProxyFailureMessage(output: String): String {
|
||||
val code = Regex("(?m)^WDTT_PROXY_CURL_EXIT=(\\d+)").find(output)?.groupValues?.get(1)?.toIntOrNull()
|
||||
val reason = when (code) {
|
||||
5, 6 -> "Сервер не смог определить адрес проверочного сайта через DNS."
|
||||
7 -> "Не удалось установить TCP-соединение через перенаправление."
|
||||
22 -> "Проверочные сайты вернули ошибку HTTP."
|
||||
28 -> "Истекло время ожидания ответа через прокси."
|
||||
35, 60 -> "Не прошла проверка защищённого HTTPS-соединения."
|
||||
45 -> "Не удалось отправить проверку с адреса интерфейса WDTT."
|
||||
0 -> "Проверочные сайты не вернули корректный IPv4-адрес."
|
||||
else -> "Не удалось получить ответ проверочного сайта через прокси."
|
||||
}
|
||||
return "$reason Включение внешнего TCP-прокси отменено, восстановлен прямой выход WDTT. " +
|
||||
"Кнопка «Проверить» проверяет сам прокси отдельно от перенаправления через redsocks."
|
||||
}
|
||||
|
||||
internal fun externalProxyProbeFunctions(): String = """
|
||||
wdtt_valid_proxy_test_ip() {
|
||||
printf '%s\n' "${'$'}1" | awk -F. '
|
||||
NR != 1 || NF != 4 { exit 1 }
|
||||
{ for (i = 1; i <= 4; i++) if (${'$'}i !~ /^[0-9]+$/ || ${'$'}i > 255) exit 1 }
|
||||
'
|
||||
}
|
||||
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"
|
||||
if ! iptables -I INPUT -i lo -s "${'$'}test_source" -d 127.0.0.1 -p tcp --dport 12345 -m comment --comment WDTT_PROXY_TEST -j ACCEPT ||
|
||||
! iptables -t nat -N 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 ||
|
||||
! iptables -t nat -I OUTPUT -s "${'$'}test_source" -p tcp -j WDTT_PROXY_TEST; then
|
||||
wdtt_cleanup_proxy_test
|
||||
echo WDTT_ERROR=external_proxy_test_rule_failed
|
||||
return 1
|
||||
fi
|
||||
test_error_file="${'$'}(mktemp /tmp/wdtt-proxy-check.XXXXXX)" || {
|
||||
wdtt_cleanup_proxy_test
|
||||
echo WDTT_ERROR=external_proxy_test_temp_failed
|
||||
return 1
|
||||
}
|
||||
test_ok=0
|
||||
test_code=0
|
||||
for test_url in https://api.ipify.org https://checkip.amazonaws.com; do
|
||||
test_code=0
|
||||
# Ignore curlrc and environment proxies: only our transparent route is under test.
|
||||
test_ip="${'$'}(curl -q --proxy '' --noproxy '*' --interface "${'$'}test_source" \
|
||||
-4fsS --connect-timeout 5 --max-time 12 "${'$'}test_url" 2>"${'$'}test_error_file")" || test_code=${'$'}?
|
||||
if [ "${'$'}test_code" = 0 ] && wdtt_valid_proxy_test_ip "${'$'}test_ip"; then
|
||||
test_ok=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
# A successful direct request must never masquerade as a working transparent proxy.
|
||||
test_packets="${'$'}(iptables -t nat -L WDTT_PROXY_TEST -n -v -x 2>/dev/null |
|
||||
awk '${'$'}3 == "REDIRECT" { total += ${'$'}1 } END { print total + 0 }')"
|
||||
wdtt_cleanup_proxy_test
|
||||
rm -f "${'$'}test_error_file"
|
||||
if [ "${'$'}test_ok" != 1 ]; then
|
||||
echo WDTT_ERROR=external_proxy_apply_failed
|
||||
echo "WDTT_PROXY_CURL_EXIT=${'$'}test_code"
|
||||
return 1
|
||||
fi
|
||||
if [ "${'$'}test_packets" -eq 0 ]; then
|
||||
echo WDTT_ERROR=external_proxy_test_not_redirected
|
||||
return 1
|
||||
fi
|
||||
echo "Проверка перенаправления через redsocks успешна. IP через прокси: ${'$'}test_ip"
|
||||
}
|
||||
""".trimIndent()
|
||||
@@ -0,0 +1,477 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.os.PersistableBundle
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
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 com.wdtt.plus.sshCredentialsForMode
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
import java.security.SecureRandom
|
||||
|
||||
internal enum class ServerSetupKind { FRESH, EXISTING, PRESERVED, INCOMPLETE, RECOVERY, STANDALONE }
|
||||
|
||||
internal data class ServerSetupReview(
|
||||
val changes: List<String> = emptyList(),
|
||||
val notes: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
internal fun ServerSetupDraft.sameServerAccess(other: ServerSetupDraft): Boolean =
|
||||
host.trim() == other.host.trim() && user.trim() == other.user.trim() &&
|
||||
sshPassword == other.sshPassword && sshPort.ifBlank { "22" } == other.sshPort.ifBlank { "22" } &&
|
||||
authMode == other.authMode && privateKey == other.privateKey && keyPassphrase == other.keyPassphrase
|
||||
|
||||
internal fun classifyFirstServerSetup(hasAnyTrace: Boolean, ownership: DeploymentOwnership, hasRollback: Boolean): ServerSetupKind? = when {
|
||||
ownership == DeploymentOwnership.StandaloneInstaller -> ServerSetupKind.STANDALONE
|
||||
hasRollback -> ServerSetupKind.RECOVERY
|
||||
!hasAnyTrace && ownership in setOf(DeploymentOwnership.UnknownExisting, DeploymentOwnership.NoInstall) -> ServerSetupKind.FRESH
|
||||
!hasAnyTrace -> null
|
||||
ownership == DeploymentOwnership.AndroidDeploy || ownership == DeploymentOwnership.LegacyAndroidDeploy -> ServerSetupKind.EXISTING
|
||||
ownership == DeploymentOwnership.PreservedAndroidData -> ServerSetupKind.PRESERVED
|
||||
ownership == DeploymentOwnership.IncompleteAndroidDeploy -> ServerSetupKind.INCOMPLETE
|
||||
else -> null
|
||||
}
|
||||
|
||||
internal fun offersServerUpdate(setupCompleted: Boolean, sshReady: Boolean, mainPassword: String): Boolean =
|
||||
setupCompleted || (sshReady && mainPassword.isNotBlank())
|
||||
|
||||
internal fun canOpenInitialServerTunnel(
|
||||
installedProfile: Int?, installedNavigationRevision: Int?, activeProfile: Int,
|
||||
navigationRevision: Int, visible: Boolean, navigationCancelled: Boolean,
|
||||
): Boolean = installedProfile == activeProfile && installedNavigationRevision == navigationRevision &&
|
||||
visible && !navigationCancelled
|
||||
|
||||
internal fun generateServerAdminPassword(): String {
|
||||
val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
||||
val random = SecureRandom()
|
||||
return buildString { repeat(24) { append(alphabet[random.nextInt(alphabet.length)]) } }
|
||||
}
|
||||
|
||||
internal data class ServerSetupDraft(
|
||||
val host: String = "", val user: String = "root", val sshPassword: String = "",
|
||||
val sshPort: String = "22", val authMode: String = "password",
|
||||
val privateKey: String = "", val keyPassphrase: String = "",
|
||||
val mainPassword: String = "", val dns1: String = "1.1.1.1", val dns2: String = "1.0.0.1",
|
||||
val dtlsPort: String = "56000", val wgPort: String = "56001", val localPort: String = "9000",
|
||||
val adminId: String = "", val botToken: String = "",
|
||||
) {
|
||||
fun accessIssue(): String? = primaryServerSshAccessIssue(
|
||||
host.trim(), host.trim().isValidPublicHost(), authMode, sshPassword, privateKey,
|
||||
sshPort.ifBlank { "22" }.toIntOrNull() ?: 0,
|
||||
)
|
||||
fun settingsIssue(): String? {
|
||||
if (!mainPassword.matches(Regex("^[a-zA-Z0-9_.!?:#/-]+$"))) return "Укажите пароль администратора: латинские буквы, цифры или _ . ! ? : # - /"
|
||||
val ports = listOf(dtlsPort, wgPort, localPort).map { it.toIntOrNull() ?: 0 }
|
||||
if (ports.any { it !in 1..65535 }) return "Порты должны быть числами от 1 до 65535."
|
||||
if (ports[0] == ports[1]) return "Порты WDTT и WireGuard должны отличаться."
|
||||
runCatching { normalizedDeployDns(dns1, dns2) }.exceptionOrNull()?.let { return it.message ?: "Проверьте DNS." }
|
||||
if ((adminId.isBlank()) != (botToken.isBlank())) return "Для Telegram-бота заполните оба поля или отключите настройку бота."
|
||||
if (adminId.isNotBlank() && adminId.toLongOrNull() == null) return "ID администратора должен быть числом."
|
||||
return null
|
||||
}
|
||||
fun request(): DeployRequest {
|
||||
require(accessIssue() == null && settingsIssue() == null)
|
||||
val credentials = sshCredentialsForMode(authMode, sshPassword, privateKey, keyPassphrase)
|
||||
return DeployRequest(host.trim(), user.ifBlank { "root" }, credentials.password,
|
||||
credentials.privateKey, credentials.privateKeyPassphrase, credentials.allowPasswordAuthentication,
|
||||
sshPort.ifBlank { "22" }.toInt(), mainPassword, adminId, botToken,
|
||||
dtlsPort.toInt(), wgPort.toInt(), localPort.toInt(), dns1.trim(), dns2.trim())
|
||||
}
|
||||
}
|
||||
|
||||
internal fun copyServerSecret(context: android.content.Context, label: String, value: String) {
|
||||
val clip = ClipData.newPlainText(label, value)
|
||||
clip.description.extras = PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) }
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(clip)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SetupSecretField(
|
||||
value: String, onChange: (String) -> Unit, label: String,
|
||||
enabled: Boolean = true, multiline: Boolean = false,
|
||||
onRegenerate: (() -> Unit)? = null, allowCopy: Boolean = false,
|
||||
) {
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val context = LocalContext.current
|
||||
OutlinedTextField(
|
||||
value = value, onValueChange = onChange, label = { Text(label) }, enabled = enabled,
|
||||
singleLine = !multiline, maxLines = if (multiline) 5 else 1,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, autoCorrectEnabled = false),
|
||||
visualTransformation = if (focused) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
modifier = Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused },
|
||||
shape = androidx.compose.foundation.shape.RoundedCornerShape(16.dp),
|
||||
trailingIcon = if (onRegenerate != null || allowCopy) ({
|
||||
Row {
|
||||
onRegenerate?.let { regenerate ->
|
||||
HintIconButton(hint = "Сгенерировать новый пароль", onClick = regenerate, enabled = enabled, modifier = Modifier.remoteIconButtonFocus(enabled)) {
|
||||
Icon(Icons.Default.Refresh, "Сгенерировать новый пароль")
|
||||
}
|
||||
}
|
||||
if (allowCopy) HintIconButton(hint = "Скопировать $label",
|
||||
onClick = { copyServerSecret(context, label, value) }, enabled = enabled && value.isNotBlank(),
|
||||
modifier = Modifier.remoteIconButtonFocus(enabled && value.isNotBlank()),
|
||||
) { Icon(Icons.Default.ContentCopy, "Скопировать $label") }
|
||||
}
|
||||
}) else null,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FirstServerSetupDialog(
|
||||
initial: ServerSetupDraft,
|
||||
onDismiss: () -> Unit,
|
||||
onProbe: suspend (ServerSetupDraft) -> ServerSetupKind,
|
||||
onReview: suspend (ServerSetupDraft, ServerSetupKind) -> ServerSetupReview,
|
||||
onInstall: suspend (ServerSetupDraft, ServerSetupKind) -> Unit,
|
||||
) {
|
||||
// Secrets are kept out of the saved-state Bundle. Saved credentials use SettingsStore encryption.
|
||||
var draft by remember { mutableStateOf(initial) }
|
||||
var step by remember { mutableIntStateOf(0) }
|
||||
var kind by remember { mutableStateOf(ServerSetupKind.FRESH) }
|
||||
var verifiedAccess by remember { mutableStateOf<ServerSetupDraft?>(null) }
|
||||
var review by remember { mutableStateOf<ServerSetupReview?>(null) }
|
||||
var reviewedDraft by remember { mutableStateOf<ServerSetupDraft?>(null) }
|
||||
val fresh = kind == ServerSetupKind.FRESH
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf("") }
|
||||
var customDns by remember { mutableStateOf(initial.dns1 != "1.1.1.1" || initial.dns2 != "1.0.0.1") }
|
||||
var customPorts by remember { mutableStateOf(initial.dtlsPort != "56000" || initial.wgPort != "56001" || initial.localPort != "9000") }
|
||||
var useBot by remember { mutableStateOf(initial.adminId.isNotBlank() || initial.botToken.isNotBlank()) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val shown = draft.copy(
|
||||
dns1 = if (customDns && kind != ServerSetupKind.STANDALONE) draft.dns1 else "1.1.1.1", dns2 = if (customDns && kind != ServerSetupKind.STANDALONE) draft.dns2 else "1.0.0.1",
|
||||
dtlsPort = if (customPorts && kind != ServerSetupKind.STANDALONE) draft.dtlsPort else "56000", wgPort = if (customPorts && kind != ServerSetupKind.STANDALONE) draft.wgPort else "56001",
|
||||
localPort = if (customPorts && kind != ServerSetupKind.STANDALONE) draft.localPort else "9000",
|
||||
adminId = if (useBot && kind != ServerSetupKind.STANDALONE) draft.adminId else "", botToken = if (useBot && kind != ServerSetupKind.STANDALONE) draft.botToken else "",
|
||||
)
|
||||
fun openStep(target: Int) {
|
||||
if (busy || target == step) return
|
||||
error = ""
|
||||
when (target) {
|
||||
0 -> step = 0
|
||||
1 -> {
|
||||
error = draft.accessIssue().orEmpty()
|
||||
if (error.isBlank() && verifiedAccess?.let { draft.sameServerAccess(it) } != true) {
|
||||
error = "На шаге «Доступ» нажмите «Далее», чтобы проверить VPS."
|
||||
}
|
||||
if (error.isBlank()) step = 1
|
||||
}
|
||||
2 -> {
|
||||
error = draft.accessIssue() ?: shown.settingsIssue().orEmpty()
|
||||
if (error.isBlank() && verifiedAccess?.let { draft.sameServerAccess(it) } != true) {
|
||||
error = "После изменения доступа проверьте VPS ещё раз."
|
||||
}
|
||||
if (error.isBlank() && (review == null || reviewedDraft != shown)) {
|
||||
error = "На шаге «Настройки» нажмите «Далее», чтобы перейти к итогу."
|
||||
}
|
||||
if (error.isBlank()) step = 2
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsDialogLayout(
|
||||
title = "Настройка сервера", secure = true, onDismiss = { if (!busy) onDismiss() },
|
||||
footer = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (error.isNotBlank()) Text(error, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (step > 0) OutlinedButton(onClick = { openStep(step - 1) }, enabled = !busy,
|
||||
contentPadding = PaddingValues(horizontal = 12.dp)) { Text("Назад", maxLines = 1) }
|
||||
Button(
|
||||
enabled = !busy, modifier = Modifier.weight(1f).heightIn(min = 48.dp),
|
||||
onClick = {
|
||||
error = ""
|
||||
when (step) {
|
||||
0 -> {
|
||||
error = draft.accessIssue().orEmpty()
|
||||
if (error.isBlank()) {
|
||||
busy = true
|
||||
scope.launch {
|
||||
try {
|
||||
val detected = onProbe(draft)
|
||||
val sameAccess = verifiedAccess?.let { draft.sameServerAccess(it) } == true
|
||||
val nextPassword = when {
|
||||
sameAccess && detected == kind -> draft.mainPassword
|
||||
detected == ServerSetupKind.FRESH -> generateServerAdminPassword()
|
||||
verifiedAccess == null -> initial.mainPassword
|
||||
else -> ""
|
||||
}
|
||||
kind = detected
|
||||
verifiedAccess = draft
|
||||
review = null
|
||||
reviewedDraft = null
|
||||
draft = draft.copy(mainPassword = nextPassword)
|
||||
step = 1
|
||||
} catch (e: CancellationException) { throw e }
|
||||
catch (e: Exception) { error = friendlyDeployError(e, "проверка сервера") }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
1 -> {
|
||||
error = draft.accessIssue() ?: shown.settingsIssue().orEmpty()
|
||||
if (error.isBlank() && verifiedAccess?.let { draft.sameServerAccess(it) } != true) {
|
||||
error = "После изменения доступа проверьте VPS ещё раз."
|
||||
}
|
||||
if (error.isBlank()) {
|
||||
busy = true
|
||||
scope.launch {
|
||||
try {
|
||||
val result = onReview(shown, kind)
|
||||
if (verifiedAccess?.let { draft.sameServerAccess(it) } != true) {
|
||||
error = "После изменения доступа проверьте VPS ещё раз."
|
||||
} else {
|
||||
review = result
|
||||
reviewedDraft = shown
|
||||
step = 2
|
||||
}
|
||||
} catch (e: CancellationException) { throw e }
|
||||
catch (e: Exception) { error = friendlyDeployError(e, "сравнение настроек") }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
if (reviewedDraft != shown || review == null || verifiedAccess?.let { draft.sameServerAccess(it) } != true) {
|
||||
error = "Настройки изменились. Повторите проверку на предыдущем шаге."
|
||||
return@Button
|
||||
}
|
||||
busy = true
|
||||
scope.launch {
|
||||
try { onInstall(shown, kind) }
|
||||
catch (e: CancellationException) { throw e }
|
||||
catch (e: Exception) { error = friendlyDeployError(e, "подготовка установки") }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (busy) { CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp, color = MaterialTheme.colorScheme.onPrimary); Spacer(Modifier.width(8.dp)) }
|
||||
Text(
|
||||
if (busy) when (step) {
|
||||
0 -> "Проверяю VPS…"
|
||||
1 -> if (fresh) "Проверяю настройки…" else "Сравниваю настройки…"
|
||||
else -> "Подготавливаю…"
|
||||
} else when (step) {
|
||||
0 -> "Далее"
|
||||
1 -> "Далее"
|
||||
else -> if (fresh) "Установить" else if (kind == ServerSetupKind.STANDALONE) "Продолжить" else "Продолжить"
|
||||
}, maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
SetupStepProgress(step = step, onSelect = ::openStep)
|
||||
when (step) {
|
||||
0 -> {
|
||||
Text("Доступ к вашему VPS", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("Адрес и данные входа предоставляет VPS-провайдер. Проверка ничего не устанавливает и не меняет на сервере.", style = MaterialTheme.typography.bodySmall)
|
||||
SetupTextField(draft.host, { draft = draft.copy(host = it.filterNot(Char::isWhitespace)) }, "IP-адрес или домен", enabled = !busy)
|
||||
SetupTextField(draft.user, { draft = draft.copy(user = it.filterNot(Char::isWhitespace)) }, "Пользователь SSH · обычно root", enabled = !busy)
|
||||
SetupChoice("Вход на VPS", listOf("Пароль", "SSH-ключ"), if (draft.authMode == "key") 1 else 0, !busy) {
|
||||
draft = draft.copy(authMode = if (it == 1) "key" else "password")
|
||||
}
|
||||
SetupSecretField(draft.sshPassword, { draft = draft.copy(sshPassword = it) },
|
||||
if (draft.authMode == "key") "Пароль sudo · если требуется" else "Пароль входа на VPS", enabled = !busy)
|
||||
if (draft.authMode == "key") {
|
||||
SetupSecretField(draft.privateKey, { draft = draft.copy(privateKey = it) }, "Приватный SSH-ключ", enabled = !busy, multiline = true)
|
||||
SetupSecretField(draft.keyPassphrase, { draft = draft.copy(keyPassphrase = it) }, "Пароль SSH-ключа · необязательно", enabled = !busy)
|
||||
}
|
||||
SetupTextField(draft.sshPort, { draft = draft.copy(sshPort = it.filter(Char::isDigit).take(5)) }, "Порт SSH · по умолчанию 22", numeric = true, enabled = !busy)
|
||||
}
|
||||
1 -> {
|
||||
AppSectionCard {
|
||||
Text(when (kind) {
|
||||
ServerSetupKind.FRESH -> "WDTT на VPS не найден"
|
||||
ServerSetupKind.EXISTING -> "WDTT уже установлен"
|
||||
ServerSetupKind.PRESERVED -> "Найдены сохранённые данные WDTT"
|
||||
ServerSetupKind.INCOMPLETE -> "Найдена незавершённая установка"
|
||||
ServerSetupKind.RECOVERY -> "Найдена страховочная копия обновления"
|
||||
ServerSetupKind.STANDALONE -> "Сервер установлен вручную"
|
||||
}, fontWeight = FontWeight.Bold)
|
||||
Text(if (fresh) "Доступ по SSH подтверждён. Пароль WDTT создан автоматически; при желании измените его."
|
||||
else when (kind) {
|
||||
ServerSetupKind.STANDALONE -> "Этот сервер обслуживается ручным установщиком. Здесь можно получить его настройки; установка и удаление из приложения запрещены. Нужен существующий пароль WDTT."
|
||||
ServerSetupKind.PRESERVED -> "Клиенты и настройки сохранены. Укажите прежний пароль WDTT; на следующем шаге можно восстановить сервер с сохранением данных."
|
||||
ServerSetupKind.INCOMPLETE -> "Повторная установка потребует отдельного подтверждения. Используйте ранее заданный пароль; если его ещё нет, создайте новый кнопкой генерации."
|
||||
ServerSetupKind.RECOVERY -> "Сначала нужно проверить и разрешить прерванное обновление. Введите существующий пароль; приложение откроет безопасное восстановление."
|
||||
else -> "Введите существующий пароль администратора WDTT. Перед обновлением приложение отдельно проверит установку и предложит сохранить данные."
|
||||
}, style = MaterialTheme.typography.bodySmall)
|
||||
SetupSecretField(draft.mainPassword, { draft = draft.copy(mainPassword = it.filterNot(Char::isWhitespace)) },
|
||||
"Пароль администратора WDTT", onRegenerate = if (fresh || kind == ServerSetupKind.INCOMPLETE) ({ draft = draft.copy(mainPassword = generateServerAdminPassword()) }) else null, allowCopy = true)
|
||||
Text("Это отдельный пароль WDTT, а не пароль VPS. Он даёт права администратора.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
if (kind != ServerSetupKind.STANDALONE) {
|
||||
AppSectionCard {
|
||||
SetupChoice("DNS сервера", listOf("По умолчанию", "Свой"), if (customDns) 1 else 0) { customDns = it == 1 }
|
||||
Text("По умолчанию: 1.1.1.1 и 1.0.0.1", style = MaterialTheme.typography.bodySmall)
|
||||
if (customDns) {
|
||||
SetupTextField(draft.dns1, { draft = draft.copy(dns1 = it) }, "Основной DNS")
|
||||
SetupTextField(draft.dns2, { draft = draft.copy(dns2 = it) }, "Резервный DNS · необязательно")
|
||||
}
|
||||
}
|
||||
AppSectionCard {
|
||||
SetupChoice("Порты", listOf("По умолчанию", "Свои"), if (customPorts) 1 else 0) { customPorts = it == 1 }
|
||||
Text("WDTT: 56000 · WireGuard: 56001 · локальный: 9000", style = MaterialTheme.typography.bodySmall)
|
||||
if (customPorts) {
|
||||
SetupTextField(draft.dtlsPort, { draft = draft.copy(dtlsPort = it.filter(Char::isDigit).take(5)) }, "Порт WDTT", true)
|
||||
SetupTextField(draft.wgPort, { draft = draft.copy(wgPort = it.filter(Char::isDigit).take(5)) }, "Порт WireGuard", true)
|
||||
SetupTextField(draft.localPort, { draft = draft.copy(localPort = it.filter(Char::isDigit).take(5)) }, "Локальный порт в приложении", true)
|
||||
}
|
||||
}
|
||||
AppSectionCard {
|
||||
SetupChoice("Telegram-бот · необязательно", listOf(if (fresh) "Пропустить" else "Не менять", "Настроить"), if (useBot) 1 else 0) { useBot = it == 1 }
|
||||
Text("Управление через приложение работает без бота.", style = MaterialTheme.typography.bodySmall)
|
||||
if (useBot) {
|
||||
SetupTextField(draft.adminId, { draft = draft.copy(adminId = it.trim()) }, "Telegram ID администратора", numeric = true)
|
||||
SetupSecretField(draft.botToken, { draft = draft.copy(botToken = it.trim()) }, "Токен бота")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
AppSectionCard {
|
||||
Text(if (fresh) "Первая установка" else if (kind == ServerSetupKind.STANDALONE) "Подключение к готовому серверу" else "Проверка существующей установки", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(shown.host, fontWeight = FontWeight.SemiBold)
|
||||
Text("SSH: ${shown.user.ifBlank { "root" }} · порт ${shown.sshPort.ifBlank { "22" }}\nWDTT: ${shown.dtlsPort}\nWireGuard: ${shown.wgPort}\nDNS: ${shown.dns1}${if (shown.dns2.isBlank()) "" else ", ${shown.dns2}"}\nTelegram-бот: ${if (shown.adminId.isNotBlank()) "настроен" else if (fresh) "пропущен" else "без изменений"}")
|
||||
}
|
||||
if (!fresh && kind != ServerSetupKind.STANDALONE && kind != ServerSetupKind.RECOVERY) {
|
||||
AppSectionCard {
|
||||
Text("Изменения настроек", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold)
|
||||
val changes = review?.changes.orEmpty()
|
||||
if (changes.isEmpty()) Text("Проверенные настройки совпадают. Серверная часть может обновиться.", style = MaterialTheme.typography.bodySmall)
|
||||
else changes.forEach { Text("• $it", style = MaterialTheme.typography.bodySmall) }
|
||||
review?.notes.orEmpty().forEach { Text("• $it", style = MaterialTheme.typography.bodySmall) }
|
||||
}
|
||||
}
|
||||
Text(if (fresh) "Приложение проверит совместимость, установит WDTT, настроит службу и необходимые правила сети. После установки покажет данные сервера и заполнит подключение в «Туннеле»."
|
||||
else if (kind == ServerSetupKind.STANDALONE) "Будут сохранены только локальные поля подключения. Затем получите настройки готового сервера; на VPS ничего не изменяется." else "Следующий шаг проверит текущие данные. Обновление или удаление данных потребует отдельного подтверждения; автоматически ничего не будет заменено.", style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SetupStepProgress(step: Int, onSelect: (Int) -> Unit) {
|
||||
LinearProgressIndicator(
|
||||
progress = { (step + 1) / 3f }, modifier = Modifier.fillMaxWidth().height(4.dp),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
trackColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
listOf("Доступ", "Настройки", "Итог").forEachIndexed { index, name ->
|
||||
val selected = index == step
|
||||
val done = index < step
|
||||
Column(
|
||||
modifier = Modifier.weight(1f).clickable(
|
||||
interactionSource = remember { MutableInteractionSource() }, indication = null,
|
||||
) { onSelect(index) }.padding(vertical = 4.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Surface(
|
||||
shape = CircleShape,
|
||||
color = when {
|
||||
selected -> MaterialTheme.colorScheme.primary
|
||||
done -> MaterialTheme.colorScheme.primaryContainer
|
||||
else -> MaterialTheme.colorScheme.surfaceVariant
|
||||
},
|
||||
) {
|
||||
Box(Modifier.size(28.dp), contentAlignment = Alignment.Center) {
|
||||
if (done) Icon(Icons.Default.Check, null, Modifier.size(17.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||
else Text("${index + 1}", style = MaterialTheme.typography.labelMedium,
|
||||
color = if (selected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SetupTextField(value: String, onChange: (String) -> Unit, label: String, numeric: Boolean = false, enabled: Boolean = true) {
|
||||
OutlinedTextField(value, onChange, label = { Text(label) }, modifier = Modifier.fillMaxWidth(), singleLine = true,
|
||||
enabled = enabled, shape = androidx.compose.foundation.shape.RoundedCornerShape(16.dp),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = if (numeric) KeyboardType.Number else KeyboardType.Text))
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun SetupChoice(title: String, labels: List<String>, selected: Int, enabled: Boolean = true, onSelect: (Int) -> Unit) {
|
||||
Text(title, fontWeight = FontWeight.SemiBold, style = MaterialTheme.typography.bodyMedium)
|
||||
SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {
|
||||
labels.forEachIndexed { index, label ->
|
||||
SegmentedButton(selected = selected == index, onClick = { onSelect(index) }, shape = SegmentedButtonDefaults.itemShape(index, labels.size),
|
||||
enabled = enabled, icon = { StableSegmentedButtonIcon(selected == index) }) { Text(label, style = MaterialTheme.typography.labelMedium) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FirstServerSetupResultDialog(draft: ServerSetupDraft, tunnelPrepared: Boolean, onFinish: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val report = buildString {
|
||||
append("Сервер WDTT\nАдрес: ${draft.host}\nSSH: ${draft.user.ifBlank { "root" }} · ${draft.sshPort}\n")
|
||||
if (draft.sshPassword.isNotBlank()) append("Пароль SSH/sudo: ${draft.sshPassword}\n")
|
||||
if (draft.adminId.isNotBlank()) append("Telegram ID администратора: ${draft.adminId}\nТокен бота: ${draft.botToken}\n")
|
||||
append("Пароль администратора WDTT: ${draft.mainPassword}\nWDTT: ${draft.dtlsPort}\nWireGuard: ${draft.wgPort}\nЛокальный порт: ${draft.localPort}\nDNS: ${draft.dns1}, ${draft.dns2}")
|
||||
}
|
||||
SettingsDialogLayout(title = "Сервер установлен", secure = true, onDismiss = onFinish, footer = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = { copyServerSecret(context, "Данные вашего сервера", report) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Icon(Icons.Default.ContentCopy, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text("Скопировать данные")
|
||||
}
|
||||
}
|
||||
}) {
|
||||
AppSectionCard {
|
||||
Text("Установка завершена", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("SSH-доступ, пароль администратора и выбранные параметры уже сохранены в «Деплое».")
|
||||
Text(if (tunnelPrepared)
|
||||
"Адрес, пароль и порты заполнены в «Туннеле → Вручную». Добавьте ВК-хеши в настройках и подключитесь."
|
||||
else "Прежние настройки «Туннеля» сохранены. Для подключения к новому серверу используйте отдельный пустой профиль или измените подключение вручную.")
|
||||
}
|
||||
AppSectionCard {
|
||||
Text("Данные администратора", fontWeight = FontWeight.Bold)
|
||||
Text(report, style = MaterialTheme.typography.bodyMedium)
|
||||
if (draft.authMode == "key") Text("Для входа по SSH используйте свой ключ.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Text("Сохраните данные администратора: после закрытия они не будут показаны вместе. Не передавайте их клиентам.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ServerWorkflowHelpDialog(onDismiss: () -> Unit) {
|
||||
SettingsDialogLayout(title = "Установка и подключение", onDismiss = onDismiss) {
|
||||
Text("Установить", fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
|
||||
Text("На пустом профиле «Установка сервера» откроет мастер. Когда SSH-доступ и пароль WDTT уже заполнены, «Обновить сервер» сразу проверит VPS, покажет отличия и предложит обновление с сохранением данных или переустановку. «Изменить настройки» откроет мастер с текущими значениями. Если WDTT не найден, приложение предложит первую установку. После успешной первой установки SSH и параметры сохраняются автоматически. Пустой «Туннель» заполняется в режиме «Вручную»; остаётся добавить ВК-хеши. После закрытия данных сервера и отсчёта таймера приложение перейдёт на вкладку «Туннель», если вы не перешли в другой раздел или окно. Такой переход отменяет только переключение вкладки — пустое подключение всё равно заполняется. Обновление и переустановка не меняют подключение и не переключают вкладку. Прежнее подключение сохраняется. Новый пароль создаётся только для чистого VPS; удаление данных требует отдельного подтверждения.")
|
||||
Text("Подключить", fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
|
||||
Text("Считывает настройки уже работающего WDTT-сервера. Нужны SSH-доступ и существующий главный пароль администратора. Приложение покажет отличия и запросит подтверждение перед заменой локальных полей. На сервер ничего не записывается, доступы клиентов не меняются.")
|
||||
Text("Настройки выходного IP загружаются отдельно в блоке «Выходной IP и прокси». Диагностика сервера доступна по лупе; удаление — по значку корзины и только после отдельного подтверждения.")
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,6 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
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
|
||||
@@ -84,6 +83,15 @@ internal fun floatingToolbarMaxOffset(
|
||||
parentHeightPx - safeBottomPx - navigationReservePx - toolbarHeightPx - bottomGapPx
|
||||
).coerceAtLeast(minOffsetY)
|
||||
|
||||
internal fun floatingToolbarOffset(fraction: Float, minOffset: Float, maxOffset: Float): Float {
|
||||
val normalized = if (fraction.isFinite() && fraction >= 0f) fraction.coerceIn(0f, 1f) else 1f
|
||||
return minOffset + (maxOffset - minOffset).coerceAtLeast(0f) * normalized
|
||||
}
|
||||
|
||||
internal fun floatingToolbarFraction(offset: Float, minOffset: Float, maxOffset: Float, previous: Float): Float =
|
||||
if (maxOffset > minOffset) ((offset - minOffset) / (maxOffset - minOffset)).coerceIn(0f, 1f)
|
||||
else previous
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun FloatingToolbar(
|
||||
@@ -106,6 +114,7 @@ fun FloatingToolbar(
|
||||
activeClientIds: String,
|
||||
onClientIdsChange: (String) -> Unit,
|
||||
onTransferRequested: () -> Unit,
|
||||
onOpened: () -> Unit = {},
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
@@ -140,8 +149,7 @@ fun FloatingToolbar(
|
||||
}
|
||||
var parentHeightPx by remember { mutableFloatStateOf(0f) }
|
||||
var tabHeightPx by remember { mutableFloatStateOf(0f) }
|
||||
var offsetY by remember { mutableFloatStateOf(-1f) }
|
||||
var toolbarPositionRestored by remember { mutableStateOf(false) }
|
||||
var toolbarYFraction by remember { mutableFloatStateOf(-2f) }
|
||||
var isExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var renamingProfile by remember { mutableStateOf<Int?>(null) }
|
||||
var resettingProfile by remember { mutableStateOf<Int?>(null) }
|
||||
@@ -191,32 +199,17 @@ fun FloatingToolbar(
|
||||
minOffsetY = minOffsetY,
|
||||
)
|
||||
|
||||
LaunchedEffect(savedToolbarYFraction, minOffsetY, maxOffsetY) {
|
||||
if (savedToolbarYFraction < -1f) return@LaunchedEffect
|
||||
offsetY = if (!toolbarPositionRestored || offsetY < 0f) {
|
||||
if (savedToolbarYFraction >= 0f && maxOffsetY > minOffsetY) {
|
||||
minOffsetY + (maxOffsetY - minOffsetY) * savedToolbarYFraction
|
||||
} else {
|
||||
// A new installation starts above the bottom navigation, as
|
||||
// shown in the main tunnel layout. The thumb remains freely
|
||||
// movable along the right edge and its chosen position is saved.
|
||||
maxOffsetY
|
||||
}
|
||||
} else {
|
||||
offsetY.coerceIn(minOffsetY, maxOffsetY)
|
||||
// Keep the relative position while window insets and measured height settle after startup.
|
||||
val toolbarPositionRestored = toolbarYFraction >= 0f
|
||||
val offsetY = floatingToolbarOffset(toolbarYFraction, minOffsetY, maxOffsetY)
|
||||
LaunchedEffect(savedToolbarYFraction) {
|
||||
if (!toolbarPositionRestored && savedToolbarYFraction >= -1f) {
|
||||
toolbarYFraction = if (savedToolbarYFraction >= 0f) savedToolbarYFraction else 1f
|
||||
}
|
||||
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) }
|
||||
if (toolbarYFraction >= 0f) settingsStore.saveFloatingToolbarYFraction(toolbarYFraction)
|
||||
}
|
||||
|
||||
val tabShape = RoundedCornerShape(topStart = 14.dp, bottomStart = 14.dp)
|
||||
@@ -229,21 +222,25 @@ fun FloatingToolbar(
|
||||
}
|
||||
) {
|
||||
Surface(
|
||||
onClick = { isExpanded = !isExpanded },
|
||||
onClick = { if (!isExpanded) onOpened(); isExpanded = !isExpanded },
|
||||
modifier = Modifier
|
||||
.iconHoldHint("Настройки приложения и профилей")
|
||||
.align(Alignment.TopEnd)
|
||||
.offset { IntOffset(0, offsetY.coerceAtLeast(minOffsetY).roundToInt()) }
|
||||
.remoteCompactFocus(tabShape)
|
||||
.onGloballyPositioned { coordinates ->
|
||||
tabHeightPx = coordinates.size.height.toFloat()
|
||||
}
|
||||
.pointerInput(minOffsetY, maxOffsetY) {
|
||||
.pointerInput(minOffsetY, maxOffsetY, toolbarPositionRestored) {
|
||||
detectDragGestures(
|
||||
onDragEnd = { persistToolbarPosition() },
|
||||
onDragCancel = { persistToolbarPosition() },
|
||||
onDrag = { change, dragAmount ->
|
||||
change.consume()
|
||||
offsetY = (offsetY + dragAmount.y).coerceIn(minOffsetY, maxOffsetY)
|
||||
if (toolbarYFraction >= 0f) {
|
||||
val movedOffset = floatingToolbarOffset(toolbarYFraction, minOffsetY, maxOffsetY) + dragAmount.y
|
||||
toolbarYFraction = floatingToolbarFraction(movedOffset, minOffsetY, maxOffsetY, toolbarYFraction)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
@@ -266,7 +263,7 @@ fun FloatingToolbar(
|
||||
}
|
||||
|
||||
if (isExpanded) {
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = { isExpanded = false },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
@@ -306,7 +303,7 @@ fun FloatingToolbar(
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
contentDescription = "Close",
|
||||
contentDescription = "Закрыть",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
@@ -694,15 +691,15 @@ fun FloatingToolbar(
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) {
|
||||
Text(
|
||||
"Клиенты VK",
|
||||
"Клиенты ВК",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Text(
|
||||
when {
|
||||
!customVkCredentialsEnabled -> "VKCalls → встроенный резерв"
|
||||
customVkCredentialsComplete -> "VKCalls → свой → встроенный резерв"
|
||||
!customVkCredentialsEnabled -> "ВК Звонки → встроенный резерв"
|
||||
customVkCredentialsComplete -> "ВК Звонки → свой → встроенный резерв"
|
||||
else -> "Заполните резервные реквизиты"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -895,7 +892,7 @@ private fun ProfileMenuDialog(
|
||||
onSave: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
@@ -982,7 +979,7 @@ private fun ProfileResetDialog(
|
||||
onConfirm: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = { if (!inProgress) onDismiss() },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
@@ -1032,7 +1029,7 @@ private fun ProfileResetDialog(
|
||||
style = MaterialTheme.typography.bodyLarge
|
||||
)
|
||||
Text(
|
||||
"Удалятся настройки подключения, VK-хеши, ссылки, пароли и SSH-ключи, параметры сервера, списки приложений и остальные данные этого профиля.",
|
||||
"Удалятся настройки подключения, ВК-хеши, ссылки, пароли и SSH-ключи, параметры сервера, списки приложений и остальные данные этого профиля.",
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
Text(
|
||||
@@ -1135,6 +1132,7 @@ private fun ThemeOption(
|
||||
else MaterialTheme.colorScheme.surface,
|
||||
modifier = modifier
|
||||
.height(42.dp)
|
||||
.iconHoldHint(contentDescription)
|
||||
.remoteFocusOutline(RoundedCornerShape(24.dp), focusedScale = 1.04f)
|
||||
) {
|
||||
Box(
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.ime
|
||||
import androidx.compose.foundation.layout.safeDrawing
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.IconButtonColors
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.FilledTonalIconButton
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.composed
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.semantics.onLongClick
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntRect
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupPositionProvider
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
|
||||
private data class IconHint(val owner: Any, val message: String, val occurrence: Any = Any())
|
||||
private val currentIconHint = MutableStateFlow<IconHint?>(null)
|
||||
|
||||
/** One notice at a time, rendered in the pressed icon's window, including dialogs. */
|
||||
@Composable
|
||||
internal fun rememberIconHint(message: String): () -> Unit {
|
||||
val owner = remember { Any() }
|
||||
val hint by currentIconHint.collectAsState()
|
||||
val haptic = LocalHapticFeedback.current
|
||||
val density = LocalDensity.current
|
||||
val bottomInset = maxOf(WindowInsets.safeDrawing.getBottom(density), WindowInsets.ime.getBottom(density))
|
||||
val gap = with(density) { 104.dp.roundToPx() }
|
||||
val sideGap = with(density) { 16.dp.roundToPx() }
|
||||
val maxWidth = (LocalConfiguration.current.screenWidthDp.dp - 32.dp).coerceAtLeast(1.dp)
|
||||
val position = remember(bottomInset, gap, sideGap) {
|
||||
object : PopupPositionProvider {
|
||||
override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize,
|
||||
layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset = IntOffset(
|
||||
((windowSize.width - popupContentSize.width) / 2).coerceAtLeast(sideGap),
|
||||
(windowSize.height - bottomInset - gap - popupContentSize.height).coerceAtLeast(sideGap),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (hint?.owner === owner) {
|
||||
Popup(popupPositionProvider = position,
|
||||
properties = PopupProperties(focusable = false, dismissOnBackPress = false, dismissOnClickOutside = false)) {
|
||||
WdttInlineNotice(hint!!.message, modifier = Modifier.widthIn(max = maxWidth))
|
||||
}
|
||||
LaunchedEffect(hint) {
|
||||
val shown = hint
|
||||
delay(2_500)
|
||||
currentIconHint.compareAndSet(shown, null)
|
||||
}
|
||||
}
|
||||
DisposableEffect(owner) {
|
||||
onDispose { currentIconHint.value?.takeIf { it.owner === owner }?.let { currentIconHint.compareAndSet(it, null) } }
|
||||
}
|
||||
return {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
currentIconHint.value = IconHint(owner, message)
|
||||
}
|
||||
}
|
||||
|
||||
/** Observe the hold before the button handles release; consume only a completed hold. */
|
||||
internal fun Modifier.iconHoldHint(message: String): Modifier = composed {
|
||||
val showHint by rememberUpdatedState(rememberIconHint(message))
|
||||
semantics {
|
||||
onLongClick(label = message) { showHint(); true }
|
||||
}.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
|
||||
val cancelled = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {
|
||||
var ended = false
|
||||
while (!ended) {
|
||||
val event = awaitPointerEvent(PointerEventPass.Initial)
|
||||
val change = event.changes.firstOrNull { it.id == down.id }
|
||||
ended = change == null || !change.pressed || change.isConsumed ||
|
||||
(change.position - down.position).getDistance() > viewConfiguration.touchSlop ||
|
||||
event.changes.any { it.id != down.id && it.pressed }
|
||||
}
|
||||
true
|
||||
}
|
||||
if (cancelled == null) {
|
||||
showHint()
|
||||
do {
|
||||
val event = awaitPointerEvent(PointerEventPass.Initial)
|
||||
event.changes.forEach { it.consume() }
|
||||
} while (event.changes.any { it.pressed })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun HintIconButton(
|
||||
hint: String,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
colors: IconButtonColors = IconButtonDefaults.iconButtonColors(),
|
||||
interactionSource: MutableInteractionSource? = null,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
IconButton(onClick = onClick, modifier = modifier.iconHoldHint(hint), enabled = enabled,
|
||||
colors = colors, interactionSource = interactionSource, content = content)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun HintFilledTonalIconButton(
|
||||
hint: String,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
colors: IconButtonColors = IconButtonDefaults.filledTonalIconButtonColors(),
|
||||
interactionSource: MutableInteractionSource? = null,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
FilledTonalIconButton(onClick = onClick, modifier = modifier.iconHoldHint(hint),
|
||||
enabled = enabled, colors = colors, interactionSource = interactionSource, content = content)
|
||||
}
|
||||
@@ -105,7 +105,6 @@ 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
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.wdtt.plus.BuildConfig
|
||||
@@ -261,6 +260,7 @@ fun InfoTab(
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val settingsStore = remember { SettingsStore(context) }
|
||||
val questionProfileSnapshot by settingsStore.activeTunnelProfileContentUiSnapshot.collectAsStateWithLifecycle()
|
||||
val infoScrollState = rememberRememberedScrollState(scrollPosition)
|
||||
val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() }
|
||||
var actionsSectionY by remember { mutableStateOf(0f) }
|
||||
@@ -281,6 +281,9 @@ fun InfoTab(
|
||||
var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) }
|
||||
var questionAction by remember { mutableStateOf<RemoteUiAction?>(null) }
|
||||
var questionActionLoading by remember { mutableStateOf(false) }
|
||||
var questionActionProfile by remember { mutableStateOf<Int?>(null) }
|
||||
var questionActionRetry by remember { mutableIntStateOf(0) }
|
||||
var questionActionGeneration by remember { mutableIntStateOf(0) }
|
||||
var isCheckingDevice by remember { mutableStateOf(false) }
|
||||
var deviceCheckReport by remember { mutableStateOf<com.wdtt.plus.DeviceCompatibilityReport?>(null) }
|
||||
var actionsExpanded by actionsExpandedState
|
||||
@@ -334,10 +337,22 @@ fun InfoTab(
|
||||
actionCatalog = RemoteActionCatalogGateway.fetch(force = true)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
questionActionLoading = true
|
||||
questionAction = RemoteActionCatalogGateway.fetchQuestionAction()
|
||||
LaunchedEffect(questionProfileSnapshot?.profileIndex, questionProfileSnapshot?.remoteManaged, questionActionRetry) {
|
||||
val generation = ++questionActionGeneration
|
||||
questionAction = null
|
||||
questionActionProfile = null
|
||||
questionActionLoading = false
|
||||
val profile = questionProfileSnapshot?.takeIf { it.remoteManaged } ?: return@LaunchedEffect
|
||||
questionActionLoading = true
|
||||
try {
|
||||
val action = RemoteActionCatalogGateway.fetchQuestionAction()
|
||||
if (generation == questionActionGeneration) {
|
||||
questionActionProfile = profile.profileIndex
|
||||
questionAction = action
|
||||
}
|
||||
} finally {
|
||||
if (generation == questionActionGeneration) questionActionLoading = false
|
||||
}
|
||||
}
|
||||
|
||||
fun requestDownloadedUpdateInstall(apkFile: File) {
|
||||
@@ -512,7 +527,10 @@ fun InfoTab(
|
||||
it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE ||
|
||||
it.title == "Сеть Android"
|
||||
} + listOfNotNull(
|
||||
tunnelProfile?.let { DeviceCompatibility.rtNetworkModeItem(context, it) },
|
||||
tunnelProfile?.let {
|
||||
com.wdtt.plus.connectionModeDiagnostic(it.rtNetwork)
|
||||
},
|
||||
tunnelProfile?.let { DeviceCompatibility.masqueModeItem(context, it) },
|
||||
sleepBatteryModeItem(
|
||||
enabled = sleepEnabled,
|
||||
screenOffMode = screenOffMode,
|
||||
@@ -585,6 +603,8 @@ fun InfoTab(
|
||||
}
|
||||
)
|
||||
|
||||
com.wdtt.plus.LocalBuildExtensions.Content()
|
||||
|
||||
ExpandableSectionCard(
|
||||
title = "Действия",
|
||||
itemCount = "4 пункта",
|
||||
@@ -614,12 +634,8 @@ fun InfoTab(
|
||||
subtitle = "Выбрать подходящий способ обращения",
|
||||
onClick = {
|
||||
showQuestionDialog = true
|
||||
if (questionAction == null && !questionActionLoading) {
|
||||
scope.launch {
|
||||
questionActionLoading = true
|
||||
questionAction = RemoteActionCatalogGateway.fetchQuestionAction()
|
||||
questionActionLoading = false
|
||||
}
|
||||
if (questionProfileSnapshot?.remoteManaged == true && questionAction == null && !questionActionLoading) {
|
||||
questionActionRetry++
|
||||
}
|
||||
},
|
||||
icon = {
|
||||
@@ -635,7 +651,7 @@ fun InfoTab(
|
||||
WideActionTile(
|
||||
title = "Проверить устройство",
|
||||
subtitle = if (isCheckingDevice) {
|
||||
"Проверяем Android, ABI, 16 КиБ, WireGuard, режим РТ и сеть..."
|
||||
"Проверяем Android, ABI, 16 КиБ, WireGuard, подключение и сеть..."
|
||||
} else {
|
||||
"Проверка совместимости и полный отчёт для диагностики"
|
||||
},
|
||||
@@ -669,7 +685,7 @@ fun InfoTab(
|
||||
|
||||
WideActionTile(
|
||||
title = "Справка",
|
||||
subtitle = "Коротко про режимы, цепочки, исключения и запуск",
|
||||
subtitle = "Коротко о подключении, настройках и проверках",
|
||||
onClick = { showHelpDialog = true },
|
||||
icon = {
|
||||
Icon(
|
||||
@@ -910,8 +926,10 @@ fun InfoTab(
|
||||
if (showHelpDialog) ImportantInfoDialog(onDismiss = { showHelpDialog = false })
|
||||
if (showQuestionDialog) {
|
||||
QuestionDestinationDialog(
|
||||
remoteAction = questionAction,
|
||||
remoteActionLoading = questionActionLoading,
|
||||
remoteAction = questionAction.takeIf {
|
||||
questionProfileSnapshot?.remoteManaged == true && questionActionProfile == questionProfileSnapshot?.profileIndex
|
||||
},
|
||||
remoteActionLoading = questionActionLoading && questionProfileSnapshot?.remoteManaged == true,
|
||||
onDismiss = { showQuestionDialog = false },
|
||||
onGitHubClick = {
|
||||
showQuestionDialog = false
|
||||
@@ -1023,7 +1041,7 @@ private fun QuestionDestinationDialog(
|
||||
onRemoteActionClick: (RemoteUiAction) -> Unit,
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
@@ -1043,7 +1061,8 @@ private fun QuestionDestinationDialog(
|
||||
}).heightIn(max = 560.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(20.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(20.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Row(
|
||||
@@ -1160,7 +1179,7 @@ private fun AdditionalActionsDialog(
|
||||
val supportScope = rememberCoroutineScope()
|
||||
val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() }
|
||||
var originalAuthorSectionY by remember { mutableStateOf(0f) }
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
@@ -1396,7 +1415,7 @@ private fun RemoteActionFormDialog(
|
||||
fallbackAvailable = false
|
||||
}
|
||||
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = { if (!busy) onDismiss() },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
@@ -1827,7 +1846,7 @@ private fun InfoHeroCard(
|
||||
color = colors.onSurface
|
||||
)
|
||||
Text(
|
||||
text = "Android-клиент для TURN/VK туннеля с WireGuard, капчей, управлением сервером и удобными сценариями подключения.",
|
||||
text = "Android-клиент для TURN/ВК-туннеля с WireGuard, капчей, управлением сервером и удобными сценариями подключения.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = colors.onSurfaceVariant,
|
||||
lineHeight = 21.sp
|
||||
@@ -2337,6 +2356,9 @@ private suspend fun buildSupportReportSummary(
|
||||
trustedWifiWaiting = trustedWifiWaiting,
|
||||
)
|
||||
}
|
||||
val diagnosticConnectionProfile = diagnosticProfileIndex?.let {
|
||||
runCatching { settingsStore.tunnelProfileSnapshot(it) }.getOrNull()
|
||||
}
|
||||
val activeProfile = diagnosticProfileIndex?.plus(1)
|
||||
val routingSettings = diagnosticProfileIndex?.let { profile ->
|
||||
runCatching { settingsStore.vpnRoutingSettingsForProfile(profile) }.getOrNull()
|
||||
@@ -2353,10 +2375,9 @@ private suspend fun buildSupportReportSummary(
|
||||
.count { it.isNotBlank() }
|
||||
.coerceAtMost(4)
|
||||
val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull()
|
||||
val rtNetworkEnabled = runCatching { settingsStore.rtNetwork.first() }.getOrNull()
|
||||
val rtMasqueEnabled = runCatching { settingsStore.rtMasque.first() }.getOrNull()
|
||||
val rtMasqueServerBootstrap =
|
||||
runCatching { settingsStore.rtMasqueServerBootstrap.first() }.getOrNull()
|
||||
val rtNetworkEnabled = diagnosticConnectionProfile?.rtNetwork
|
||||
val rtMasqueEnabled = diagnosticConnectionProfile?.rtMasque
|
||||
val rtMasqueServerBootstrap = diagnosticConnectionProfile?.rtMasqueServerBootstrap
|
||||
val rtMasqueEnrollment = runCatching {
|
||||
val config = File(context.filesDir, RT_MASQUE_CONFIG_FILE_NAME)
|
||||
when (inspectRtMasqueEnrollment(config)) {
|
||||
@@ -2494,18 +2515,24 @@ private suspend fun buildSupportReportSummary(
|
||||
}
|
||||
appendLine("Потоки: ${workers ?: "недоступно"}")
|
||||
appendLine(
|
||||
"VK-хеши: заполнено $hashCount, " +
|
||||
"ВК-хеши: заполнено $hashCount, " +
|
||||
"автоматический резерв между хешами=${if (hashCount > 1) "включён" else "недоступен"}"
|
||||
)
|
||||
appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}")
|
||||
appendLine("Сеть РТ (TURN stream-first): ${rtNetworkEnabled ?: "недоступно"}")
|
||||
appendLine("Быстрые ВК Звонки: ${vkCallsEnabled ?: "недоступно"}")
|
||||
appendLine("Подключение: " + if (rtNetworkEnabled != null) {
|
||||
com.wdtt.plus.connectionModeTitle(rtNetworkEnabled)
|
||||
} else "недоступно")
|
||||
appendLine("Внешний UDP запрещён: ${rtNetworkEnabled ?: "недоступно"}")
|
||||
if (TunnelManager.running.value && TunnelManager.activeTunnelProfile.value == diagnosticProfileIndex) {
|
||||
appendLine("Последний подтверждённый путь: ${TunnelManager.connectionPath.value.ifBlank { "ещё не выбран" }}")
|
||||
}
|
||||
appendLine(
|
||||
"MASQUE в Сети РТ (HTTP/2 → HTTP/3): ${rtMasqueEnabled ?: "недоступно"}, " +
|
||||
"MASQUE (настройка профиля): ${rtMasqueEnabled ?: "недоступно"}, " +
|
||||
"регистрация WARP=$rtMasqueEnrollment, " +
|
||||
"первая регистрация через сервер=${rtMasqueServerBootstrap ?: "недоступно"}"
|
||||
"регистрация по SSH=${rtMasqueServerBootstrap ?: "недоступно"}"
|
||||
)
|
||||
appendLine(
|
||||
"Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " +
|
||||
"Резерв ВК: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " +
|
||||
"заполнены=${customVkCredentialsComplete ?: "недоступно"}, встроенных=${builtInVkClientCount ?: "недоступно"}"
|
||||
)
|
||||
appendLine("Captcha mode (legacy): ${captchaMode ?: "недоступно"}")
|
||||
|
||||
@@ -6,6 +6,8 @@ import android.content.Context
|
||||
import android.widget.Toast
|
||||
import androidx.compose.animation.core.*
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
@@ -46,6 +48,10 @@ fun LogsTab(
|
||||
val scope = rememberCoroutineScope()
|
||||
val currentLogs by TunnelManager.logs.collectAsStateWithLifecycle()
|
||||
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
|
||||
var problemsOnly by rememberSaveable { mutableStateOf(false) }
|
||||
val visibleLogs = remember(currentLogs, problemsOnly) {
|
||||
if (problemsOnly) currentLogs.filter { it.severity != LogSeverity.Info } else currentLogs
|
||||
}
|
||||
val listState = rememberRememberedLazyListState(
|
||||
firstVisibleItemIndex,
|
||||
firstVisibleItemScrollOffset
|
||||
@@ -59,22 +65,22 @@ fun LogsTab(
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
"Лог событий",
|
||||
"Журнал событий",
|
||||
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Row {
|
||||
IconButton(onClick = { TunnelManager.clearLogs() }) {
|
||||
Icon(Icons.Default.Delete, contentDescription = "Clear", tint = MaterialTheme.colorScheme.primary)
|
||||
HintIconButton(hint = "Очистить журнал", enabled = currentLogs.isNotEmpty(), onClick = { TunnelManager.clearLogs() }) {
|
||||
Icon(Icons.Default.Delete, contentDescription = "Очистить журнал", tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
IconButton(onClick = {
|
||||
val text = currentLogs.joinToString("\n") { "${it.message} (x${it.count})" }
|
||||
HintIconButton(hint = "Копировать журнал", enabled = visibleLogs.isNotEmpty(), onClick = {
|
||||
val text = visibleLogs.joinToString("\n") { if (it.count > 1) "${it.message} (×${it.count})" else it.message }
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = ClipData.newPlainText("WDTT Logs", text)
|
||||
clipboard.setPrimaryClip(clip)
|
||||
Toast.makeText(context, "Скопировано", Toast.LENGTH_SHORT).show()
|
||||
}) {
|
||||
Icon(Icons.Default.ContentCopy, contentDescription = "Copy", tint = MaterialTheme.colorScheme.primary)
|
||||
Icon(Icons.Default.ContentCopy, contentDescription = "Копировать журнал", tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,7 +105,7 @@ fun LogsTab(
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
"Активное логирование",
|
||||
"Записывать события",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 14.sp,
|
||||
@@ -112,6 +118,14 @@ fun LogsTab(
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(bottom = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
FilterChip(selected = !problemsOnly, onClick = { problemsOnly = false }, label = { Text("Все") })
|
||||
FilterChip(selected = problemsOnly, onClick = { problemsOnly = true }, label = { Text("Предупреждения и ошибки") })
|
||||
}
|
||||
|
||||
// Нейтральный фон в светлой теме не спорит с цветами уровней лога.
|
||||
val isDark = MaterialTheme.colorScheme.background.luminance() < 0.5f
|
||||
val terminalBg = if (isDark) {
|
||||
@@ -131,7 +145,21 @@ fun LogsTab(
|
||||
modifier = Modifier.fillMaxSize().padding(12.dp),
|
||||
contentPadding = PaddingValues(bottom = 12.dp)
|
||||
) {
|
||||
items(currentLogs, key = { it.key }) { entry ->
|
||||
if (visibleLogs.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
when {
|
||||
!loggingEnabled -> "Запись событий выключена"
|
||||
problemsOnly -> "Предупреждений и ошибок нет"
|
||||
else -> "Здесь появятся события подключения и диагностики"
|
||||
},
|
||||
modifier = Modifier.padding(12.dp),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
items(visibleLogs, key = { it.key }) { entry ->
|
||||
LogLine(entry, sessionActive = tunnelRunning)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
internal data class OutboundActionFeedback(
|
||||
val summary: String,
|
||||
val category: RemoteLogCategory,
|
||||
val diagnostics: String,
|
||||
)
|
||||
|
||||
internal fun outboundResultSummary(output: String): String {
|
||||
val lines = output.lineSequence().map { it.trim() }.filter { line ->
|
||||
Regex("^[А-Яа-яЁё]").containsMatchIn(line) &&
|
||||
classifyRemoteCommandLine(line).category != RemoteLogCategory.Technical
|
||||
}.toList()
|
||||
return lines.take(10).joinToString("\n").ifBlank { "Действие выполнено. Технические подробности доступны ниже." }
|
||||
}
|
||||
|
||||
internal fun outboundErrorSummary(friendly: String): String {
|
||||
val text = friendly.substringBefore("Последние строки сервера:").trim()
|
||||
return if (Regex("^[А-Яа-яЁё]").containsMatchIn(text)) text
|
||||
else "Действие не выполнено. Откройте подробности для диагностики."
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun OutboundActionMessage(feedback: OutboundActionFeedback, modifier: Modifier = Modifier) {
|
||||
var expanded by remember(feedback) { mutableStateOf(false) }
|
||||
val context = LocalContext.current
|
||||
val error = feedback.category == RemoteLogCategory.Error
|
||||
val warning = feedback.category == RemoteLogCategory.Warning
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
color = when {
|
||||
error -> MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.55f)
|
||||
warning -> MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.55f)
|
||||
else -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f)
|
||||
},
|
||||
) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
when { error -> "Не выполнено"; warning -> "Требует внимания"; else -> "Результат" },
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Text(feedback.summary, style = MaterialTheme.typography.bodySmall)
|
||||
if (feedback.diagnostics.isNotBlank()) {
|
||||
TextButton(onClick = { expanded = !expanded }) {
|
||||
Text(if (expanded) "Скрыть подробности" else "Подробности")
|
||||
}
|
||||
if (expanded) {
|
||||
Text("Диагностический вывод. Секретные значения скрыты.", style = MaterialTheme.typography.labelSmall)
|
||||
TextButton(onClick = {
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(
|
||||
ClipData.newPlainText("Диагностика выходного IP", feedback.summary + "\n\n" + feedback.diagnostics)
|
||||
)
|
||||
}) { Text("Копировать лог") }
|
||||
SelectionContainer {
|
||||
Text(
|
||||
feedback.diagnostics,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = 280.dp).verticalScroll(rememberScrollState()),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
/** Read-only checks shared by installation, diagnostics and the WARP watchdog. */
|
||||
internal fun outboundProbeFunctions(): String = """
|
||||
wdtt_probe_ipv4() {
|
||||
printf '%s\n' "${'$'}1" | awk -F. '
|
||||
NR != 1 || NF != 4 { exit 1 }
|
||||
{ for (i=1; i<=4; i++) if (${'$'}i !~ /^[0-9]+$/ || ${'$'}i > 255) exit 1 }
|
||||
'
|
||||
}
|
||||
wdtt_routed_https() (
|
||||
source_ip="${'$'}1"
|
||||
expected_iface="${'$'}2"
|
||||
url="${'$'}3"
|
||||
[ -n "${'$'}source_ip" ] && [ -n "${'$'}expected_iface" ] || return 1
|
||||
host="${'$'}{url#https://}"
|
||||
host="${'$'}{host%%/*}"
|
||||
destination="${'$'}(getent ahostsv4 "${'$'}host" 2>/dev/null | awk '{print ${'$'}1; exit}')"
|
||||
wdtt_probe_ipv4 "${'$'}destination" || return 1
|
||||
route="${'$'}(ip -4 route get "${'$'}destination" from "${'$'}source_ip" 2>/dev/null)" || return 1
|
||||
printf '%s\n' "${'$'}route" | awk -v expected="${'$'}expected_iface" '
|
||||
{ for (i=1; i<NF; i++) if (${'$'}i == "dev" && ${'$'}(i+1) == expected) found=1 }
|
||||
END { exit found ? 0 : 1 }
|
||||
' || return 1
|
||||
# Pin the same destination whose route was checked. Do not use curlrc/env proxies.
|
||||
response="${'$'}(curl -q --proxy '' --noproxy '*' --interface "${'$'}source_ip" \
|
||||
--resolve "${'$'}host:443:${'$'}destination" -4fsS --connect-timeout 4 --max-time 10 \
|
||||
"${'$'}url" 2>/dev/null)" || return 1
|
||||
[ -n "${'$'}response" ] || return 1
|
||||
printf '%s\n' "${'$'}response"
|
||||
)
|
||||
wdtt_routed_public_ip() (
|
||||
for url in https://api.ipify.org https://checkip.amazonaws.com; do
|
||||
result="${'$'}(wdtt_routed_https "${'$'}1" "${'$'}2" "${'$'}url")" || continue
|
||||
if wdtt_probe_ipv4 "${'$'}result"; then printf '%s\n' "${'$'}result"; return 0; fi
|
||||
done
|
||||
return 1
|
||||
)
|
||||
""".trimIndent()
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
internal enum class RemoteLogCategory { Info, Warning, Error, Technical }
|
||||
internal data class RemoteLogEvent(val category: RemoteLogCategory, val message: String)
|
||||
|
||||
private val machineMarker = Regex("^[A-Z][A-Z0-9_]*=.*$")
|
||||
private val systemdLink = Regex("""^Created symlink .+ (?:→|->) .+\.$""")
|
||||
private val systemdRemoved = Regex("""^Removed ["']?.+["']?\.$""")
|
||||
private val warningMessage = Regex("""(?i)(^|\s)(warning:|warn:|W:|предупреждение:)|deprecated|deprecat(?:ion|ed)|The unit files have no installation config|not meant to be enabled|non-existent unit|debconf: delaying package configuration""")
|
||||
private val errorMessage = Regex("""(?i)^\s*(?:\[✗]|FAIL:|E:|error:|fatal:|ошибка:)|\b(?:error|failed|failure|fatal)\b|permission denied|access denied|not found|no such file|cannot |could not |не удалось|отказано в доступе""")
|
||||
|
||||
/** stderr is an output channel, not a severity. Unknown text follows the command result. */
|
||||
internal fun classifyRemoteCommandLine(line: String, exitStatus: Int = 0, stderr: Boolean = false): RemoteLogEvent {
|
||||
val clean = line.replace(Regex("\u001B\\[[;\\d]*[A-Za-z]"), "").trim()
|
||||
fun event(category: RemoteLogCategory, message: String = clean) = RemoteLogEvent(category, message)
|
||||
if (clean.isBlank() || machineMarker.matches(clean) || clean.startsWith("WDTT_PROGRESS|") ||
|
||||
clean.startsWith("[#] ") || clean.contains("2>/dev/null") || clean.contains("password for") ||
|
||||
Regex("""^\s*\d+(?:\.\d+)?%.*$""").matches(clean)
|
||||
) return event(RemoteLogCategory.Technical)
|
||||
if (systemdLink.matches(clean)) return event(RemoteLogCategory.Info, if (".wants/" in clean) "systemd: автозапуск службы включён." else "systemd: служебная ссылка создана.")
|
||||
if (systemdRemoved.matches(clean)) return event(RemoteLogCategory.Info, if (".wants/" in clean) "systemd: автозапуск службы отключён." else "systemd: служебная ссылка удалена.")
|
||||
if (warningMessage.containsMatchIn(clean)) return event(RemoteLogCategory.Warning)
|
||||
if (errorMessage.containsMatchIn(clean)) {
|
||||
val detail = clean.removePrefix("FAIL:").removePrefix("[✗]").trim()
|
||||
return event(RemoteLogCategory.Error, "Ошибка на сервере: $detail")
|
||||
}
|
||||
if (stderr && exitStatus != 0) return event(RemoteLogCategory.Error, "Ошибка на сервере: $clean")
|
||||
return event(RemoteLogCategory.Info)
|
||||
}
|
||||
|
||||
internal fun shouldWriteRemoteErrorToUserLog(line: String): Boolean =
|
||||
classifyRemoteCommandLine(line).category == RemoteLogCategory.Error
|
||||
|
||||
internal fun remoteErrorMessageForUserLog(line: String): String? =
|
||||
classifyRemoteCommandLine(line).takeIf { it.category == RemoteLogCategory.Error }?.message
|
||||
|
||||
/** Only command output is captured, never SSH commands, stdin or credentials. */
|
||||
internal val remoteCommandOutputCapture = ThreadLocal<RemoteCommandCapture?>()
|
||||
|
||||
internal class RemoteCommandCapture(private val secrets: List<String> = emptyList()) {
|
||||
fun sanitize(text: String): String = secrets.filter { it.isNotBlank() }.fold(redactRemoteDiagnostics(text)) { value, secret -> value.replace(secret, "[скрыто]") }
|
||||
private val output = StringBuilder()
|
||||
@Synchronized fun append(text: String) {
|
||||
if (text.isBlank()) return
|
||||
output.appendLine(sanitize(text))
|
||||
if (output.length > 256 * 1024) {
|
||||
output.delete(0, output.length - 256 * 1024)
|
||||
output.insert(0, "[Начало длинного вывода сокращено]\n")
|
||||
}
|
||||
}
|
||||
@Synchronized fun text(): String = output.toString().trim()
|
||||
}
|
||||
|
||||
internal fun redactRemoteDiagnostics(text: String): String {
|
||||
var result = text.replace(Regex("""(?is)-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----"""), "[приватный ключ скрыт]")
|
||||
result = result.replace(Regex("""(?i)([a-z][a-z0-9+.-]*://)[^\s/@]+:[^\s/@]+@"""), "$1[скрыто]@")
|
||||
result = result.replace(Regex("""(?im)^([^\n]*(?:password|passwd|token|secret|private[ _-]?key|preshared[ _-]?key|authorization)[^\n:=]*[:=])[^\n]*$"""), "$1 [скрыто]")
|
||||
result = result.replace(Regex("""(?m)^([A-Z][A-Z0-9_]*_B64=).*$"""), "$1[скрыто]")
|
||||
return result
|
||||
}
|
||||
|
||||
internal fun remoteEventUserText(event: RemoteLogEvent): String {
|
||||
val text = event.message
|
||||
if (Regex("^[А-Яа-яЁё]").containsMatchIn(text) &&
|
||||
!text.startsWith("Ошибка на сервере:")
|
||||
) return text
|
||||
val detail = text.removePrefix("Ошибка на сервере:").trim()
|
||||
if (Regex("^[А-Яа-яЁё]").containsMatchIn(detail)) return detail
|
||||
val lower = text.lowercase()
|
||||
return when {
|
||||
text.startsWith("systemd:") -> text
|
||||
"permission denied" in lower || "access denied" in lower -> "На сервере недостаточно прав для выполнения команды."
|
||||
"failed to enable" in lower || "failed to disable" in lower -> "Не удалось изменить автозапуск службы на сервере."
|
||||
"job for" in lower && "failed" in lower -> "Служба на сервере не запустилась. Подробности — в результате действия."
|
||||
"no installation config" in lower || "not meant to be enabled" in lower -> "Для этой службы не предусмотрено включение автозапуска."
|
||||
"non-existent unit" in lower -> "Служба ссылается на отсутствующую системную цель. Проверьте настройки автозапуска."
|
||||
"debconf:" in lower -> "Настройка пакета отложена до завершения установки."
|
||||
"deprecated" in lower -> "Сервер сообщил об устаревшем параметре. Подробности — в результате действия."
|
||||
event.category == RemoteLogCategory.Error -> "Сервер сообщил об ошибке. Подробности — в результате действия."
|
||||
event.category == RemoteLogCategory.Warning -> "Сервер сообщил о предупреждении. Подробности — в результате действия."
|
||||
else -> "Служебное сообщение сервера сохранено в подробностях действия."
|
||||
}
|
||||
}
|
||||
@@ -1,46 +1,34 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
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.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.selection.selectableGroup
|
||||
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.HelpOutline
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Cloud
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
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.material.icons.filled.ChevronRight
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.SettingsEthernet
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.wdtt.plus.DEFAULT_RT_TURN_SNI
|
||||
import com.wdtt.plus.SshProfileAccessStatus
|
||||
|
||||
@Composable
|
||||
internal fun RtNetworkSettingsDialog(
|
||||
rtNetwork: Boolean,
|
||||
connectionPath: String,
|
||||
onConnectionModeChange: (Boolean) -> Unit,
|
||||
turnSni: String,
|
||||
turnSniValid: Boolean,
|
||||
rtMasque: Boolean,
|
||||
@@ -55,247 +43,42 @@ internal fun RtNetworkSettingsDialog(
|
||||
onShowServerHelp: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val configuration = LocalConfiguration.current
|
||||
val dialogMaxHeight = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)
|
||||
val dialogMinHeight = 520.dp.coerceAtMost(dialogMaxHeight)
|
||||
val controlsEnabled = rtNetwork && !tunnelRunning
|
||||
val serverSupportingText = when {
|
||||
!rtNetwork -> "Сначала включите «Сеть РТ»"
|
||||
!rtMasque -> "Сначала включите MASQUE"
|
||||
!serverAccess.available -> "Недоступно: ${serverAccess.unavailableReason}"
|
||||
tunnelRunning -> "Остановите соединение, чтобы изменить настройку"
|
||||
else -> "Только первая регистрация WARP · SSH из «Деплой»"
|
||||
}
|
||||
val serverTextIsError = rtNetwork && rtMasque && !serverAccess.available
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.92f)
|
||||
.heightIn(min = dialogMinHeight, max = dialogMaxHeight),
|
||||
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),
|
||||
val controlsEnabled = !tunnelRunning
|
||||
var advancedExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
SettingsDialogLayout(title = "Подключение", onDismiss = onDismiss, onHelp = onShowRtHelp, animateSize = true) {
|
||||
if (tunnelRunning) {
|
||||
Text(
|
||||
"Остановите соединение, чтобы изменить режим.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Column(Modifier.selectableGroup(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
listOf("UDP" to false, "TCP/TLS" to true).forEach { (title, mode) ->
|
||||
val selected = rtNetwork == mode
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
Surface(
|
||||
shape = shape,
|
||||
color = if (selected) MaterialTheme.colorScheme.secondaryContainer
|
||||
else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.remoteFocusOutline(shape, enabled = controlsEnabled)
|
||||
.selectable(
|
||||
selected = selected,
|
||||
enabled = controlsEnabled,
|
||||
role = Role.RadioButton,
|
||||
onClick = { onConnectionModeChange(mode) },
|
||||
).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
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.Cloud,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(25.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Сеть РТ",
|
||||
modifier = Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
IconButton(
|
||||
onClick = onShowRtHelp,
|
||||
modifier = Modifier.remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Инструкция по режиму Сеть РТ",
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
if (!rtNetwork || tunnelRunning) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.outline.copy(alpha = 0.2f),
|
||||
),
|
||||
) {
|
||||
RadioButton(selected = selected, enabled = controlsEnabled, onClick = null)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
if (!rtNetwork) {
|
||||
"Включите «Сеть РТ» в основном окне, чтобы изменить эти параметры."
|
||||
} else {
|
||||
"Остановите соединение, чтобы изменить параметры режима."
|
||||
},
|
||||
modifier = Modifier.padding(14.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = turnSni,
|
||||
onValueChange = onTurnSniChange,
|
||||
label = { Text("SNI белого списка") },
|
||||
placeholder = { Text(DEFAULT_RT_TURN_SNI) },
|
||||
isError = !turnSniValid,
|
||||
enabled = controlsEnabled,
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
)
|
||||
Text(
|
||||
text = if (turnSniValid) {
|
||||
"Только для TURN/TLS и MASQUE; в TURN/TCP и UDP SNI нет"
|
||||
} else {
|
||||
"Укажите домен латиницей, например $DEFAULT_RT_TURN_SNI"
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (turnSniValid) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
} else {
|
||||
MaterialTheme.colorScheme.error
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("MASQUE", fontWeight = FontWeight.SemiBold)
|
||||
IconButton(
|
||||
onClick = onShowMasqueHelp,
|
||||
modifier = Modifier.size(32.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Инструкция по MASQUE",
|
||||
modifier = Modifier.size(19.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Резерв после TURN/TLS и TCP: HTTP/2, затем HTTP/3",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = rtMasque,
|
||||
enabled = controlsEnabled,
|
||||
onCheckedChange = onRtMasqueChange,
|
||||
modifier = Modifier.remoteSwitchFocus(enabled = controlsEnabled),
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Через сервер", fontWeight = FontWeight.SemiBold)
|
||||
IconButton(
|
||||
onClick = onShowServerHelp,
|
||||
modifier = Modifier.size(32.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Инструкция по регистрации через сервер",
|
||||
modifier = Modifier.size(19.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
serverSupportingText,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (serverTextIsError) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = rtMasqueServerBootstrap,
|
||||
enabled = controlsEnabled && rtMasque && serverAccess.available,
|
||||
onCheckedChange = onServerBootstrapChange,
|
||||
modifier = Modifier.remoteSwitchFocus(
|
||||
enabled = controlsEnabled && rtMasque && serverAccess.available,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.outline.copy(alpha = 0.2f),
|
||||
),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Text(
|
||||
"Когда включать",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
"Сеть РТ — если в мобильной сети Ростелекома открываются разрешённые сайты, но WDTT Plus не подключается.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
"MASQUE — если одной «Сети РТ» недостаточно: это дополнительный резерв после TURN/TLS и TCP.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
"Через сервер — только если первая регистрация WARP для MASQUE не проходит напрямую; нужен настроенный иностранный SSH-сервер в «Деплой».",
|
||||
if (mode) "Без внешнего UDP" else "UDP, при недоступности — TCP/TLS",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -304,5 +87,118 @@ internal fun RtNetworkSettingsDialog(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (connectionPath.isNotEmpty()) {
|
||||
Text("Последний рабочий способ: $connectionPath", style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
run {
|
||||
val extras = buildList {
|
||||
if (rtMasque) add("MASQUE")
|
||||
if (rtMasque && rtMasqueServerBootstrap) add("Регистрация по SSH")
|
||||
if (!turnSniValid) add("Проверьте SNI")
|
||||
else if (turnSni.isNotBlank() && turnSni != DEFAULT_RT_TURN_SNI) add("Свой SNI")
|
||||
}.joinToString(" · ").ifBlank { "Для сетей с ограничениями" }
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f),
|
||||
modifier = Modifier.fillMaxWidth().remoteFocusOutline(RoundedCornerShape(16.dp))
|
||||
.clickable { advancedExpanded = !advancedExpanded },
|
||||
) {
|
||||
Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Дополнительно", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(extras, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Icon(if (advancedExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
|
||||
contentDescription = if (advancedExpanded) "Свернуть настройки" else "Раскрыть настройки")
|
||||
}
|
||||
}
|
||||
}
|
||||
if (advancedExpanded) {
|
||||
OutlinedTextField(
|
||||
value = turnSni,
|
||||
onValueChange = onTurnSniChange,
|
||||
label = { Text("Внешний SNI") },
|
||||
placeholder = { Text(DEFAULT_RT_TURN_SNI) },
|
||||
isError = !turnSniValid,
|
||||
enabled = controlsEnabled,
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
supportingText = {
|
||||
Text(if (turnSniValid) "Для TURN/TLS и MASQUE"
|
||||
else "Укажите домен латиницей, например $DEFAULT_RT_TURN_SNI")
|
||||
},
|
||||
)
|
||||
ConnectionOptionRow(
|
||||
title = "MASQUE", subtitle = "Резерв через Cloudflare",
|
||||
checked = rtMasque, enabled = controlsEnabled,
|
||||
onCheckedChange = onRtMasqueChange, onHelp = onShowMasqueHelp,
|
||||
)
|
||||
if (rtMasque) {
|
||||
ConnectionOptionRow(
|
||||
title = "Регистрация по SSH",
|
||||
subtitle = if (serverAccess.available) "Если WARP не регистрируется напрямую"
|
||||
else "Недоступно: ${serverAccess.unavailableReason}",
|
||||
checked = rtMasqueServerBootstrap,
|
||||
enabled = controlsEnabled && serverAccess.available,
|
||||
isError = !serverAccess.available,
|
||||
onCheckedChange = onServerBootstrapChange, onHelp = onShowServerHelp,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConnectionOptionRow(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
checked: Boolean,
|
||||
enabled: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
onHelp: (() -> Unit)? = null,
|
||||
isError: Boolean = false,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(title, modifier = Modifier.weight(1f, fill = false),
|
||||
style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
|
||||
if (onHelp != null) {
|
||||
HintIconButton(hint = "Справка: $title", onClick = onHelp, modifier = Modifier.size(28.dp).remoteHelpFocus()) {
|
||||
Icon(Icons.AutoMirrored.Filled.HelpOutline, contentDescription = "Справка: $title",
|
||||
modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(subtitle, style = MaterialTheme.typography.bodySmall,
|
||||
color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Switch(checked = checked, enabled = enabled, onCheckedChange = onCheckedChange,
|
||||
modifier = Modifier.remoteSwitchFocus(enabled = enabled))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ConnectionSettingsCard(mode: String, onClick: () -> Unit) {
|
||||
AppSectionCard(
|
||||
modifier = Modifier.fillMaxWidth().remoteFocusOutline(RoundedCornerShape(16.dp)).clickable(onClick = onClick),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Icon(Icons.Default.SettingsEthernet, contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(22.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Подключение", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(mode, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Icon(Icons.Default.ChevronRight, contentDescription = "Открыть настройку подключения",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -95,7 +94,8 @@ internal fun ScreenOffModeDialog(
|
||||
),
|
||||
)
|
||||
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
scrollableText = false,
|
||||
onDismissRequest = onDismiss,
|
||||
text = {
|
||||
Column(
|
||||
|
||||
@@ -69,7 +69,6 @@ import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.SaveAlt
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.Smartphone
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
@@ -173,7 +172,7 @@ private data class ClientQrData(
|
||||
private fun vkHashInputError(value: String): String? {
|
||||
if (value.isBlank()) return null
|
||||
return if (VkJoinLink.normalizeHashes(value) == null) {
|
||||
"Проверьте VK-хеш: допустимы латинские буквы, цифры, _ и - либо ссылка VK-звонка."
|
||||
"Проверьте ВК-хеш: допустимы латинские буквы, цифры, _ и - либо ссылка ВК-звонка."
|
||||
} else {
|
||||
null
|
||||
}
|
||||
@@ -188,8 +187,8 @@ internal fun serverClientsAccessIssue(
|
||||
sshPrivateKey: String = "",
|
||||
allowPasswordAuthentication: Boolean = true
|
||||
): String? {
|
||||
if (host.isBlank()) return "Укажите IP-адрес или домен сервера в верхнем блоке «Деплой»."
|
||||
if (!hostValid) return "Проверьте IP-адрес или домен сервера в верхнем блоке «Деплой»."
|
||||
if (host.isBlank()) return "Укажите IP-адрес или домен сервера в настройках SSH."
|
||||
if (!hostValid) return "Проверьте IP-адрес или домен сервера в настройках SSH."
|
||||
val credentials = SshCredentials(
|
||||
password = sshPassword,
|
||||
privateKey = sshPrivateKey,
|
||||
@@ -202,10 +201,10 @@ internal fun serverClientsAccessIssue(
|
||||
privateKey = sshPrivateKey,
|
||||
passwordLabel = "SSH-пароль",
|
||||
privateKeyLabel = "приватный SSH-ключ"
|
||||
) ?: "Укажите SSH-пароль или приватный SSH-ключ в верхнем блоке «Деплой»."
|
||||
) ?: "Укажите SSH-пароль или приватный SSH-ключ в настройках SSH."
|
||||
}
|
||||
if (sshPort !in 1..65535) return "Укажите корректный SSH-порт от 1 до 65535."
|
||||
if (mainPassword.isBlank()) return "Откройте «Секреты» и укажите главный пароль администратора."
|
||||
if (mainPassword.isBlank()) return "Откройте параметры сервера и укажите главный пароль администратора."
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -652,8 +651,8 @@ fun ServerClientsSection(
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandVertically() + fadeIn(),
|
||||
exit = shrinkVertically() + fadeOut()
|
||||
enter = expandVertically(animationSpec = tween(300)) + fadeIn(tween(300)),
|
||||
exit = shrinkVertically(animationSpec = tween(225)) + fadeOut(tween(225))
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
@@ -766,6 +765,7 @@ fun ServerClientsSection(
|
||||
modifier = Modifier
|
||||
.width(if (activeFilterCount > 0) 72.dp else 56.dp)
|
||||
.requiredHeight(56.dp)
|
||||
.iconHoldHint("Фильтры списка клиентов")
|
||||
.remoteFocusOutline(RoundedCornerShape(18.dp))
|
||||
) {
|
||||
Row(
|
||||
@@ -1049,12 +1049,12 @@ fun ServerClientsSection(
|
||||
val transferResult = remember(client) { runCatching { ClientTransferCodec.encode(ClientTransferCodec.fromClient(client)) } }
|
||||
val transfer = transferResult.getOrNull()
|
||||
if (transfer == null) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = { exportClient = null },
|
||||
title = { DialogTitle("Экспорт невозможен", { exportClient = null }) },
|
||||
text = {
|
||||
Text(
|
||||
transferResult.exceptionOrNull()?.message ?: "Проверьте пароль и VK-хеши клиента.",
|
||||
transferResult.exceptionOrNull()?.message ?: "Проверьте пароль и ВК-хеши клиента.",
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
},
|
||||
@@ -1466,7 +1466,7 @@ private fun ServerClientCard(
|
||||
)
|
||||
if (client.vkHash.isBlank()) {
|
||||
Text(
|
||||
"VK-хеш не задан: доступ можно передать, но клиенту нужно добавить свой перед запуском.",
|
||||
"ВК-хеш не задан: доступ можно передать, но клиенту нужно добавить свой перед запуском.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
@@ -1488,7 +1488,8 @@ private fun ClientFiltersDialog(
|
||||
onClear: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
scrollableText = false,
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Фильтры клиентов", onDismiss) },
|
||||
text = {
|
||||
@@ -1560,7 +1561,7 @@ private fun ClientFiltersPanel(
|
||||
ClientFilterChip("Бессрочные", expiryFilter == ClientExpiryFilter.Unlimited) { onExpiryFilterChange(ClientExpiryFilter.Unlimited) }
|
||||
}
|
||||
|
||||
FilterGroupTitle("VK-хеш")
|
||||
FilterGroupTitle("ВК-хеш")
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
ClientFilterChip("Все", vkHashFilter == ClientVkHashFilter.All) { onVkHashFilterChange(ClientVkHashFilter.All) }
|
||||
ClientFilterChip("С хешем", vkHashFilter == ClientVkHashFilter.Present) { onVkHashFilterChange(ClientVkHashFilter.Present) }
|
||||
@@ -1765,7 +1766,7 @@ private fun AccessResultDialog(
|
||||
onQr: () -> Unit,
|
||||
onFile: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle(title, onDismiss) },
|
||||
text = {
|
||||
@@ -1793,9 +1794,9 @@ private fun AccessResultDialog(
|
||||
} else {
|
||||
Text(
|
||||
if (missingVkHashes) {
|
||||
"VK-хеш не задан. Передать можно, но клиенту нужно добавить свой перед запуском."
|
||||
"ВК-хеш не задан. Передать можно, но клиенту нужно добавить свой перед запуском."
|
||||
} else {
|
||||
"Ссылка содержит пароль и VK-хеш. Не публикуйте её."
|
||||
"Ссылка содержит пароль и ВК-хеш. Не публикуйте её."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
@@ -1840,7 +1841,8 @@ private fun ClientDetailsDialog(
|
||||
client.connectionLink(fallbackHost, publicHost, sourceProfileName)
|
||||
}
|
||||
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
scrollableText = false,
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle(client.displayName(), onDismiss, enabled = !busy) },
|
||||
text = {
|
||||
@@ -1878,7 +1880,7 @@ private fun ClientDetailsDialog(
|
||||
InfoLine("Статус", when (client.status) { "active" -> "активен"; "deactivated" -> "отключён"; "expired" -> "истёк"; else -> client.status })
|
||||
InfoLine("Срок", formatExpiry(client.expiresAt))
|
||||
InfoLine("Порты", client.ports)
|
||||
InfoLine("VK-хеш", client.vkHash.ifBlank { "не задан" })
|
||||
InfoLine("ВК-хеш", client.vkHash.ifBlank { "не задан" })
|
||||
HorizontalDivider()
|
||||
TrafficPeriodBlock(client.traffic)
|
||||
}
|
||||
@@ -1937,7 +1939,7 @@ private fun ClientDetailsDialog(
|
||||
OutlinedTextField(
|
||||
value = hash,
|
||||
onValueChange = { hash = it.take(4096) },
|
||||
label = { Text("VK-хеш или ссылка") },
|
||||
label = { Text("ВК-хеш или ссылка") },
|
||||
supportingText = { hashError?.let { Text(it) } },
|
||||
isError = hashError != null,
|
||||
minLines = 2,
|
||||
@@ -2018,7 +2020,8 @@ private fun ServerToolsDialog(
|
||||
val limit = limitText.toIntOrNull()
|
||||
val networkValid = dns.isNotBlank() && limit != null && limit in 1..500 && ports.isPortsSpec()
|
||||
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
scrollableText = false,
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Управление сервером", onDismiss, enabled = !busy) },
|
||||
text = {
|
||||
@@ -2062,8 +2065,8 @@ private fun ServerToolsDialog(
|
||||
HorizontalDivider()
|
||||
Text("Сохранено на сервере", fontWeight = FontWeight.Bold)
|
||||
InfoLine("Состояние", if (state.adminProfile.hasSavedFields) "сохранён ${formatDateTime(state.adminProfile.updatedAt)}" else "ещё не сохранён")
|
||||
InfoLine("VK-хеши владельца", secretPresenceLabel(state.adminProfile.vkHashes))
|
||||
InfoLine("Резервный VK-хеш", secretPresenceLabel(state.adminProfile.secondaryVkHash))
|
||||
InfoLine("ВК-хеши владельца", secretPresenceLabel(state.adminProfile.vkHashes))
|
||||
InfoLine("Резервный ВК-хеш", secretPresenceLabel(state.adminProfile.secondaryVkHash))
|
||||
InfoLine("Порты", state.adminProfile.ports)
|
||||
InfoLine("Потоки", state.adminProfile.workersPerHash.toString())
|
||||
InfoLine("Протокол", state.adminProfile.protocol)
|
||||
@@ -2072,8 +2075,8 @@ private fun ServerToolsDialog(
|
||||
InfoLine("DNS внутри VPN", state.adminProfile.vpnDnsDisplayLabel)
|
||||
HorizontalDivider()
|
||||
Text("Будет записано при установке", fontWeight = FontWeight.Bold)
|
||||
InfoLine("VK-хеши владельца", secretPresenceLabel(localAdminProfile.vkHashes))
|
||||
InfoLine("Резервный VK-хеш", secretPresenceLabel(localAdminProfile.secondaryVkHash))
|
||||
InfoLine("ВК-хеши владельца", secretPresenceLabel(localAdminProfile.vkHashes))
|
||||
InfoLine("Резервный ВК-хеш", secretPresenceLabel(localAdminProfile.secondaryVkHash))
|
||||
InfoLine("Порты", localAdminProfile.ports)
|
||||
InfoLine("Потоки", localAdminProfile.workersPerHash.toString())
|
||||
InfoLine("Протокол", localAdminProfile.protocol)
|
||||
@@ -2411,7 +2414,7 @@ private fun ClientImportMethodsDialog(
|
||||
onFile: () -> Unit,
|
||||
onPaste: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Импорт клиента", onDismiss) },
|
||||
text = {
|
||||
@@ -2457,13 +2460,13 @@ private fun ClientTransferExportDialog(
|
||||
onQr: () -> Unit,
|
||||
onFile: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Экспорт клиента", onDismiss) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("Клиент: ${client.displayName()}", fontWeight = FontWeight.Bold)
|
||||
Text("Переносятся пароль, название, VK-хеши, срок и состояние доступа.")
|
||||
Text("Переносятся пароль, название, ВК-хеши, срок и состояние доступа.")
|
||||
Text(
|
||||
"Не переносятся устройство, WireGuard-ключи, адрес, порты, трафик и история. На новом сервере используются его настройки, а устройство привяжется при первом подключении.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -2521,7 +2524,8 @@ private fun ClientImportConfirmDialog(
|
||||
if (targetHost.isBlank()) add("Не определён адрес нового сервера.")
|
||||
if (!targetPorts.isPortsSpec()) add("На новом сервере указаны некорректные порты.")
|
||||
}
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
scrollableText = false,
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Проверка импорта", onDismiss) },
|
||||
text = {
|
||||
@@ -2535,7 +2539,7 @@ private fun ClientImportConfirmDialog(
|
||||
InfoLine("Пароль", "${payload.password.take(3)}••••${payload.password.takeLast(3)}")
|
||||
InfoLine("Срок", formatExpiry(payload.expiresAt))
|
||||
InfoLine("Состояние", if (payload.deactivated) "Отключён" else "Активен")
|
||||
InfoLine("VK-хеши", if (payload.vkHash.isBlank()) "не заданы" else "заданы")
|
||||
InfoLine("ВК-хеши", if (payload.vkHash.isBlank()) "не заданы" else "заданы")
|
||||
HorizontalDivider()
|
||||
InfoLine("Новый сервер", targetHost.ifBlank { "не определён" })
|
||||
InfoLine("Порты нового сервера", targetPorts.ifBlank { "не заданы" })
|
||||
@@ -2572,7 +2576,8 @@ private fun ChangeClientPasswordDialog(
|
||||
value in existingPasswords -> "Клиент с таким паролем уже существует."
|
||||
else -> null
|
||||
}
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
scrollableText = false,
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Сменить пароль", onDismiss) },
|
||||
text = {
|
||||
@@ -2613,7 +2618,7 @@ private fun ChangeClientPasswordDialog(
|
||||
)
|
||||
}
|
||||
Text(
|
||||
"Старые ссылки перестанут работать, активное соединение этого клиента завершится. Название, срок, VK-хеши и привязка устройства сохранятся; остальные клиенты не затрагиваются.",
|
||||
"Старые ссылки перестанут работать, активное соединение этого клиента завершится. Название, срок, ВК-хеши и привязка устройства сохранятся; остальные клиенты не затрагиваются.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
@@ -2654,7 +2659,7 @@ private fun CreateClientWizardDialog(
|
||||
}
|
||||
val passwordValid = useAutoPassword || (customPassword.isNotEmpty() && passwordError == null)
|
||||
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Новый клиент", onDismiss, enabled = !busy) },
|
||||
text = {
|
||||
@@ -2712,13 +2717,13 @@ private fun CreateClientWizardDialog(
|
||||
ClientWizardStep.Hash -> {
|
||||
Text("Хеши клиентской ссылки", fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"VK-хеши владельца не наследуются. Лучше добавить хеши перед передачей. Без них доступ тоже можно отправить, но клиенту придётся добавить свои.",
|
||||
"ВК-хеши владельца не наследуются. Можно указать до 4 хешей или ссылок ВК Звонков: с новой строки, через пробел или запятую. Поле можно оставить пустым — тогда клиент добавит свои.",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = vkHash,
|
||||
onValueChange = { vkHash = it.take(4096) },
|
||||
label = { Text("Хеш или ссылка") },
|
||||
label = { Text("До 4 хешей или ссылок") },
|
||||
supportingText = { hashError?.let { Text(it) } },
|
||||
isError = hashError != null,
|
||||
minLines = 2,
|
||||
@@ -2781,12 +2786,12 @@ private fun CreateClientWizardDialog(
|
||||
Text("Проверка", fontWeight = FontWeight.Bold)
|
||||
Text("Срок: ${if (days == 0) "бессрочно" else "$days дн."}")
|
||||
Text("Название: ${label.ifBlank { "без имени" }}")
|
||||
Text("VK-хеш: ${if (vkHash.isBlank()) "не задан" else "задан"}")
|
||||
Text("ВК-хеш: ${if (vkHash.isBlank()) "не задан" else "задан"}")
|
||||
Text("Порты: $effectivePorts")
|
||||
Text("Пароль: ${if (useAutoPassword) "будет создан автоматически" else customPassword}")
|
||||
if (vkHash.isBlank()) {
|
||||
Text(
|
||||
"Без VK-хеша клиент добавит свой перед запуском.",
|
||||
"Без ВК-хеша клиент добавит свой перед запуском.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
@@ -2860,7 +2865,7 @@ private fun ConfirmClientActionDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle(action.confirmLabel, onDismiss) },
|
||||
text = { Text(action.message) },
|
||||
@@ -2887,7 +2892,7 @@ private fun ExtendClientDialog(
|
||||
) {
|
||||
var customDays by rememberSaveable { mutableStateOf("") }
|
||||
val parsedDays = customDays.toIntOrNull()?.takeIf { it in 1..365 }
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Продлить", onDismiss) },
|
||||
text = {
|
||||
@@ -2931,7 +2936,7 @@ private fun ClientQrDialog(
|
||||
if (granted) onSave()
|
||||
else Toast.makeText(context, "Без разрешения Android 9 не может сохранить QR-код.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
@@ -2950,9 +2955,9 @@ private fun ClientQrDialog(
|
||||
}
|
||||
Text(
|
||||
if (missingVkHashes) {
|
||||
"VK-хеш не задан. Клиенту нужно добавить свой перед запуском."
|
||||
"ВК-хеш не задан. Клиенту нужно добавить свой перед запуском."
|
||||
} else {
|
||||
"QR содержит пароль и VK-хеш. Не публикуйте изображение."
|
||||
"QR содержит пароль и ВК-хеш. Не публикуйте изображение."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import com.wdtt.plus.SettingsStore
|
||||
import com.wdtt.plus.ServerSetupCompletion
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
internal class ServerInstallCompletionNavigation(
|
||||
val showSuccessBanner: MutableState<Boolean>,
|
||||
val successCountdown: MutableIntState,
|
||||
val successProfile: MutableState<Int?>,
|
||||
val firstInstallTunnelProfile: MutableState<Int?>,
|
||||
val firstInstallationProfile: MutableState<Int?>,
|
||||
val firstInstallationNavigationRevision: MutableState<Int?>,
|
||||
val firstInstallationNavigationCancelled: MutableState<Boolean>,
|
||||
val navigationRevision: State<Int>,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun rememberServerInstallCompletionNavigation(
|
||||
activeProfile: Int,
|
||||
navigationRevision: Int,
|
||||
visible: Boolean,
|
||||
pendingCompletionProfile: Int?,
|
||||
otherServerWindowOpen: Boolean,
|
||||
onOpenTunnel: (Int, Int) -> Unit,
|
||||
): ServerInstallCompletionNavigation {
|
||||
val showSuccessBanner = rememberSaveable { mutableStateOf(false) }
|
||||
val successCountdown = rememberSaveable { mutableIntStateOf(5) }
|
||||
val successProfile = rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
val firstInstallTunnelProfile = rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
val firstInstallationProfile = rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
val firstInstallationNavigationRevision = rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
val firstInstallationNavigationCancelled = rememberSaveable { mutableStateOf(false) }
|
||||
val currentNavigationRevision = rememberUpdatedState(navigationRevision)
|
||||
val currentActiveProfile by rememberUpdatedState(activeProfile)
|
||||
val latestOnOpenTunnel by rememberUpdatedState(onOpenTunnel)
|
||||
val state = remember {
|
||||
ServerInstallCompletionNavigation(showSuccessBanner, successCountdown, successProfile,
|
||||
firstInstallTunnelProfile, firstInstallationProfile, firstInstallationNavigationRevision,
|
||||
firstInstallationNavigationCancelled, currentNavigationRevision)
|
||||
}
|
||||
LaunchedEffect(visible, activeProfile, navigationRevision, otherServerWindowOpen, firstInstallationProfile.value) {
|
||||
if (firstInstallationProfile.value != null &&
|
||||
(!canOpenInitialServerTunnel(firstInstallationProfile.value, firstInstallationNavigationRevision.value,
|
||||
activeProfile, navigationRevision, visible, firstInstallationNavigationCancelled.value) || otherServerWindowOpen)) {
|
||||
firstInstallationNavigationCancelled.value = true
|
||||
firstInstallTunnelProfile.value = null
|
||||
}
|
||||
}
|
||||
LaunchedEffect(showSuccessBanner.value, visible, activeProfile, pendingCompletionProfile, navigationRevision, otherServerWindowOpen) {
|
||||
if (showSuccessBanner.value && visible && successProfile.value == activeProfile && pendingCompletionProfile == null) {
|
||||
while (successCountdown.intValue > 0) {
|
||||
delay(1000)
|
||||
successCountdown.intValue--
|
||||
}
|
||||
showSuccessBanner.value = false
|
||||
if (firstInstallTunnelProfile.value == activeProfile && !otherServerWindowOpen &&
|
||||
canOpenInitialServerTunnel(firstInstallationProfile.value, firstInstallationNavigationRevision.value,
|
||||
currentActiveProfile, currentNavigationRevision.value, visible, firstInstallationNavigationCancelled.value)) {
|
||||
firstInstallTunnelProfile.value = null
|
||||
latestOnOpenTunnel(activeProfile, currentNavigationRevision.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ServerSetupCompletionSection(
|
||||
settingsStore: SettingsStore,
|
||||
completion: ServerSetupCompletion?,
|
||||
activeProfile: Int,
|
||||
visible: Boolean,
|
||||
isDeploying: Boolean,
|
||||
navigation: ServerInstallCompletionNavigation,
|
||||
otherServerWindowOpen: Boolean,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
val currentActiveProfile by rememberUpdatedState(activeProfile)
|
||||
completion?.takeIf { visible && !isDeploying && it.profileIndex == activeProfile }?.let { completed ->
|
||||
val draft = ServerSetupDraft(host = completed.host, user = completed.user,
|
||||
sshPassword = completed.sshPassword, sshPort = completed.sshPort, authMode = completed.authMode,
|
||||
mainPassword = completed.mainPassword, dns1 = completed.dns1, dns2 = completed.dns2,
|
||||
dtlsPort = completed.dtlsPort.toString(), wgPort = completed.wgPort.toString(), localPort = completed.localPort.toString(),
|
||||
adminId = completed.adminId, botToken = completed.botToken)
|
||||
FirstServerSetupResultDialog(draft, tunnelPrepared = completed.tunnelPrepared,
|
||||
onFinish = {
|
||||
scope.launch {
|
||||
settingsStore.dismissServerSetupCompletion(completed.profileIndex)
|
||||
if (currentActiveProfile != completed.profileIndex) return@launch
|
||||
navigation.successProfile.value = completed.profileIndex
|
||||
navigation.firstInstallTunnelProfile.value = completed.profileIndex.takeIf {
|
||||
!otherServerWindowOpen && canOpenInitialServerTunnel(navigation.firstInstallationProfile.value,
|
||||
navigation.firstInstallationNavigationRevision.value, currentActiveProfile, navigation.navigationRevision.value,
|
||||
visible, navigation.firstInstallationNavigationCancelled.value)
|
||||
}
|
||||
navigation.successCountdown.intValue = 5
|
||||
navigation.showSuccessBanner.value = true
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
internal fun ServerSetupIcon(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
description: String,
|
||||
needsAttention: Boolean,
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val showHint = rememberIconHint("$label — $description")
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val color = if (needsAttention) colors.error else colors.primary
|
||||
Box(
|
||||
modifier = Modifier.size(40.dp).clip(CircleShape)
|
||||
.graphicsLayer { alpha = if (enabled) 1f else 0.42f }
|
||||
.remoteIconButtonFocus(enabled = enabled)
|
||||
.combinedClickable(
|
||||
interactionSource = remember { MutableInteractionSource() },
|
||||
indication = null,
|
||||
enabled = enabled,
|
||||
role = Role.Button,
|
||||
onClick = onClick,
|
||||
onLongClick = showHint,
|
||||
)
|
||||
.semantics { stateDescription = if (needsAttention) "Нужно заполнить обязательные поля" else "Настроено" },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, contentDescription = "$label: $description", modifier = Modifier.size(20.dp), tint = color)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
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.Close
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
|
||||
/** Bound the native window before its content is measured. A full-height
|
||||
* WRAP_CONTENT Dialog can otherwise extend under Android's navigation bar.
|
||||
* Read insets in the caller, not inside the dialog where they may be zero. */
|
||||
@Composable
|
||||
internal fun BoundedAppDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
properties: DialogProperties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val availableHeight = availableDialogHeight()
|
||||
Dialog(onDismissRequest = onDismissRequest, properties = properties) {
|
||||
Box(Modifier.heightIn(max = availableHeight)) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun availableDialogHeight(): Dp {
|
||||
val configuration = LocalConfiguration.current
|
||||
val density = LocalDensity.current
|
||||
val safeInsets = WindowInsets.safeDrawing
|
||||
return with(density) {
|
||||
(configuration.screenHeightDp.dp - safeInsets.getTop(this).toDp() -
|
||||
safeInsets.getBottom(this).toDp() - 24.dp).coerceAtLeast(1.dp)
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep standard alert actions outside the scrollable information area. */
|
||||
@Composable
|
||||
internal fun BoundedAlertDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
confirmButton: @Composable () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
dismissButton: (@Composable () -> Unit)? = null,
|
||||
icon: (@Composable () -> Unit)? = null,
|
||||
title: (@Composable () -> Unit)? = null,
|
||||
text: (@Composable () -> Unit)? = null,
|
||||
shape: Shape = AlertDialogDefaults.shape,
|
||||
containerColor: Color = AlertDialogDefaults.containerColor,
|
||||
iconContentColor: Color = AlertDialogDefaults.iconContentColor,
|
||||
titleContentColor: Color = AlertDialogDefaults.titleContentColor,
|
||||
textContentColor: Color = AlertDialogDefaults.textContentColor,
|
||||
tonalElevation: Dp = AlertDialogDefaults.TonalElevation,
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
scrollableText: Boolean = true,
|
||||
) {
|
||||
val availableHeight = availableDialogHeight()
|
||||
val scrollState = rememberScrollState()
|
||||
val television = isTelevisionDevice()
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismissRequest,
|
||||
confirmButton = confirmButton,
|
||||
modifier = modifier.heightIn(max = availableHeight),
|
||||
dismissButton = dismissButton,
|
||||
icon = icon,
|
||||
title = title,
|
||||
text = text?.let { body ->
|
||||
{
|
||||
if (scrollableText) {
|
||||
Box(Modifier.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television)) { body() }
|
||||
} else {
|
||||
body()
|
||||
}
|
||||
}
|
||||
},
|
||||
shape = shape,
|
||||
containerColor = containerColor,
|
||||
iconContentColor = iconContentColor,
|
||||
titleContentColor = titleContentColor,
|
||||
textContentColor = textContentColor,
|
||||
tonalElevation = tonalElevation,
|
||||
properties = properties,
|
||||
)
|
||||
}
|
||||
|
||||
/** Uses the dialog's actual viewport, including system bars and the keyboard. */
|
||||
@Composable
|
||||
internal fun SettingsDialogLayout(
|
||||
title: String,
|
||||
onDismiss: () -> Unit,
|
||||
onHelp: (() -> Unit)? = null,
|
||||
animateSize: Boolean = false,
|
||||
secure: Boolean = false,
|
||||
footer: (@Composable () -> Unit)? = null,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(
|
||||
usePlatformDefaultWidth = false,
|
||||
decorFitsSystemWindows = true,
|
||||
securePolicy = if (secure) androidx.compose.ui.window.SecureFlagPolicy.SecureOn else androidx.compose.ui.window.SecureFlagPolicy.Inherit,
|
||||
),
|
||||
) {
|
||||
BoxWithConstraints(
|
||||
modifier = Modifier.fillMaxSize().padding(12.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.widthIn(max = if (television) 920.dp else 560.dp)
|
||||
.fillMaxWidth(if (television) 0.78f else 1f)
|
||||
// Center the animated bounds so expansion lifts the top edge
|
||||
// smoothly while revealing the additional content below.
|
||||
.then(if (animateSize) Modifier.animateContentSize(tween(250), alignment = Alignment.TopCenter) else Modifier)
|
||||
.heightIn(max = maxHeight),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp,
|
||||
) {
|
||||
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
title,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
if (onHelp != null) {
|
||||
HintIconButton(hint = "Справка: $title", onClick = onHelp, modifier = Modifier.remoteHelpFocus()) {
|
||||
Icon(Icons.AutoMirrored.Filled.HelpOutline, contentDescription = "Справка: $title")
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.remoteIconButtonFocus()) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.weight(1f, fill = false).fillMaxWidth()
|
||||
.verticalScroll(scrollState).tvDpadScrollable(scrollState, television),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
content = content,
|
||||
)
|
||||
if (footer != null) {
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
footer()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -62,7 +62,6 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
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 com.wdtt.plus.MAX_SLEEP_PAUSE_DELAY_MINUTES
|
||||
import com.wdtt.plus.SleepBatteryMode
|
||||
@@ -133,7 +132,7 @@ internal fun SleepTimerDialog(
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
|
||||
@@ -16,14 +16,11 @@ import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.CameraAlt
|
||||
@@ -33,7 +30,6 @@ import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.QrCode2
|
||||
import androidx.compose.material.icons.filled.SaveAlt
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
@@ -42,6 +38,8 @@ import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -55,17 +53,26 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.journeyapps.barcodescanner.ScanContract
|
||||
import com.journeyapps.barcodescanner.ScanOptions
|
||||
import com.wdtt.plus.ProfileTransferState
|
||||
import com.wdtt.plus.RemoteProfileAction
|
||||
import com.wdtt.plus.RemoteUiActionLauncher
|
||||
import com.wdtt.plus.fetchProfileTransferAction
|
||||
import com.wdtt.plus.isUsableFor
|
||||
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.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -75,6 +82,98 @@ import java.util.Locale
|
||||
|
||||
private enum class AdminExportAction { Qr, File }
|
||||
|
||||
@Composable
|
||||
private fun ManagedProfileTransferExplanation(
|
||||
settingsStore: SettingsStore,
|
||||
profile: Int,
|
||||
state: ProfileTransferState,
|
||||
) {
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
val networkAvailable = rememberUnderlyingNetworkAvailable()
|
||||
val scope = rememberCoroutineScope()
|
||||
val identity = state.copy(message = "")
|
||||
val latestIdentity by rememberUpdatedState(identity)
|
||||
val latestProfile by rememberUpdatedState(profile)
|
||||
var remote by remember(profile, identity) { mutableStateOf<RemoteProfileAction?>(null) }
|
||||
var opening by remember(profile, identity) { mutableStateOf(false) }
|
||||
var failure by remember(profile, identity) { mutableStateOf<String?>(null) }
|
||||
|
||||
LaunchedEffect(profile, identity, networkAvailable, lifecycle) {
|
||||
remote = null
|
||||
if (!networkAvailable) return@LaunchedEffect
|
||||
lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
|
||||
try {
|
||||
while (true) {
|
||||
remote = try {
|
||||
fetchProfileTransferAction(context, settingsStore, profile, identity)
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
delay(60_000)
|
||||
}
|
||||
} finally {
|
||||
remote = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text("Перенос на другое устройство", style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
remote?.action?.message ?: state.message.ifBlank {
|
||||
"Этот профиль управляется сервисом, где вы его получили. Копирование настроек " +
|
||||
"не переносит привязку к устройству.\n\n" +
|
||||
"Откройте этот сервис под своим аккаунтом, выберите нужный профиль и " +
|
||||
"воспользуйтесь сменой устройства. После подтверждения получите новую " +
|
||||
"ссылку и откройте её в WDTT Plus на новом устройстве."
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
val available = remote?.takeIf { networkAvailable && it.isUsableFor(state) }
|
||||
if (available != null) {
|
||||
OutlinedButton(
|
||||
enabled = !opening,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
onClick = {
|
||||
opening = true
|
||||
failure = null
|
||||
scope.launch {
|
||||
try {
|
||||
// Revalidate online, including the local slot, immediately before opening.
|
||||
val fresh = fetchProfileTransferAction(context, settingsStore, profile, identity)
|
||||
check(latestProfile == profile && latestIdentity == identity && fresh != null) {
|
||||
"Профиль изменился. Откройте это окно заново."
|
||||
}
|
||||
check(RemoteUiActionLauncher.open(context, fresh.action)) {
|
||||
"Не удалось открыть ссылку."
|
||||
}
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (_: Exception) {
|
||||
remote = null
|
||||
failure = "Ссылка сейчас недоступна. Выполните перенос по инструкции выше."
|
||||
} finally {
|
||||
opening = false
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
Text(if (opening) "Открываем…" else available.action.label)
|
||||
}
|
||||
} else {
|
||||
Text(
|
||||
"Ссылка на управление появится, когда сервис подтвердит доступ к этому профилю.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
failure?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun TransferCenterDialog(
|
||||
@@ -95,6 +194,9 @@ fun TransferCenterDialog(
|
||||
var adminAction by remember { mutableStateOf<AdminExportAction?>(null) }
|
||||
val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList())
|
||||
val activeProfileLabel = vpnProfileDisplayName(activeProfile, profileNames)
|
||||
val transferState by remember(settingsStore, activeProfile) {
|
||||
settingsStore.profileTransferState(activeProfile)
|
||||
}.collectAsStateWithLifecycle(initialValue = null)
|
||||
|
||||
fun runCatchingUi(block: suspend () -> Unit) {
|
||||
busy = true
|
||||
@@ -122,140 +224,125 @@ fun TransferCenterDialog(
|
||||
}
|
||||
}
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!busy) onDismiss() },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
modifier = Modifier.fillMaxWidth(0.94f),
|
||||
text = {
|
||||
Column(
|
||||
modifier = Modifier.verticalScroll(rememberScrollState()),
|
||||
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),
|
||||
SettingsDialogLayout(
|
||||
title = "Получить или передать",
|
||||
onDismiss = { if (!busy) onDismiss() },
|
||||
) {
|
||||
Text("Получить профиль", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
if (cameraAvailable) {
|
||||
"Добавьте профиль через камеру, изображение или файл. Через эти же кнопки можно получить защищённые настройки администратора: предварительно включать админ-режим не нужно. После ввода пароля приложение покажет подтверждение, импортирует настройки и активирует режим администратора."
|
||||
} else {
|
||||
"На этом устройстве нет доступной камеры. Добавьте профиль из изображения или файла. Защищённые настройки администратора поддерживаются теми же способами."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
if (cameraAvailable) {
|
||||
TransferButton("Камера", Icons.Default.CameraAlt, busy) {
|
||||
cameraLauncher.launch(
|
||||
ScanOptions()
|
||||
.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||
.setPrompt("Наведите камеру на QR-код WDTT Plus")
|
||||
.setBeepEnabled(false)
|
||||
.setCaptureActivity(QrCaptureActivity::class.java)
|
||||
.setOrientationLocked(false)
|
||||
)
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
enabled = !busy,
|
||||
modifier = Modifier.align(androidx.compose.ui.Alignment.CenterEnd).size(32.dp)
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
TransferButton("Галерея", Icons.Default.Image, busy) { galleryLauncher.launch("image/*") }
|
||||
TransferButton("Файл", Icons.Default.FileOpen, busy) {
|
||||
fileLauncher.launch(WdttDocument.acceptedMimeTypes())
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
if (transferState?.managed == true) {
|
||||
ManagedProfileTransferExplanation(
|
||||
settingsStore = settingsStore,
|
||||
profile = activeProfile,
|
||||
state = transferState!!,
|
||||
)
|
||||
} else if (transferState?.managed == false) {
|
||||
Text("Передать $activeProfileLabel", 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),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
TransferButton("QR", Icons.Default.QrCode2, busy) {
|
||||
runCatchingUi {
|
||||
val link = settingsStore.connectionLinkForProfile(activeProfile)
|
||||
val bitmap = withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) }
|
||||
qrData = activeProfileLabel to bitmap
|
||||
}
|
||||
}
|
||||
Text("Получить профиль", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
if (cameraAvailable) {
|
||||
"Добавьте профиль через камеру, изображение или файл. Через эти же кнопки можно получить защищённые настройки администратора: предварительно включать админ-режим не нужно. После ввода пароля приложение покажет подтверждение, импортирует настройки и активирует режим администратора."
|
||||
} else {
|
||||
"На этом устройстве нет доступной камеры. Добавьте профиль из изображения или файла. Защищённые настройки администратора поддерживаются теми же способами."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
if (cameraAvailable) {
|
||||
TransferButton("Камера", Icons.Default.CameraAlt, busy) {
|
||||
cameraLauncher.launch(
|
||||
ScanOptions()
|
||||
.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||
.setPrompt("Наведите камеру на QR-код WDTT Plus")
|
||||
.setBeepEnabled(false)
|
||||
.setCaptureActivity(QrCaptureActivity::class.java)
|
||||
.setOrientationLocked(false)
|
||||
TransferButton("Ссылка", Icons.Default.Share, busy) {
|
||||
runCatchingUi {
|
||||
shareText(context, settingsStore.connectionLinkForProfile(activeProfile))
|
||||
}
|
||||
}
|
||||
TransferButton("Файл", Icons.AutoMirrored.Filled.InsertDriveFile, busy) {
|
||||
runCatchingUi {
|
||||
val link = settingsStore.connectionLinkForProfile(activeProfile)
|
||||
val uri = withContext(Dispatchers.IO) {
|
||||
TransferFiles.writeTransferText(
|
||||
context,
|
||||
WdttDocument.fileName(
|
||||
"WDTT-Plus-${activeProfileLabel.safeTransferFileName()}"
|
||||
),
|
||||
link
|
||||
)
|
||||
}
|
||||
}
|
||||
TransferButton("Галерея", Icons.Default.Image, busy) { galleryLauncher.launch("image/*") }
|
||||
TransferButton("Файл", Icons.Default.FileOpen, busy) {
|
||||
fileLauncher.launch(WdttDocument.acceptedMimeTypes())
|
||||
shareUri(context, uri, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus")
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Передать $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Ссылка содержит пароль подключения и VK-хеши. Передавайте её только тому, кому доверяете.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
TransferButton("QR", Icons.Default.QrCode2, busy) {
|
||||
runCatchingUi {
|
||||
val link = settingsStore.connectionLinkForProfile(activeProfile)
|
||||
val bitmap = withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) }
|
||||
qrData = activeProfileLabel to bitmap
|
||||
}
|
||||
}
|
||||
TransferButton("Ссылка", Icons.Default.Share, busy) {
|
||||
runCatchingUi {
|
||||
shareText(context, settingsStore.connectionLinkForProfile(activeProfile))
|
||||
}
|
||||
}
|
||||
TransferButton("Файл", Icons.AutoMirrored.Filled.InsertDriveFile, busy) {
|
||||
runCatchingUi {
|
||||
val link = settingsStore.connectionLinkForProfile(activeProfile)
|
||||
val uri = withContext(Dispatchers.IO) {
|
||||
TransferFiles.writeTransferText(
|
||||
context,
|
||||
WdttDocument.fileName(
|
||||
"WDTT-Plus-${activeProfileLabel.safeTransferFileName()}"
|
||||
),
|
||||
link
|
||||
)
|
||||
}
|
||||
shareUri(context, uri, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isAdmin) {
|
||||
HorizontalDivider()
|
||||
Text("Настройки администратора", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Все три профиля подключения, параметры деплоя, пароли, токен бота, исключения и настройки выхода. Данные шифруются указанным паролем. Приватные SSH-ключи и конфигурации служб на VPS не передаются.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(
|
||||
onClick = { adminAction = AdminExportAction.Qr },
|
||||
enabled = !busy,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(Icons.Default.QrCode2, null, Modifier.size(18.dp))
|
||||
Text(" QR")
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { adminAction = AdminExportAction.File },
|
||||
enabled = !busy,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, null, Modifier.size(18.dp))
|
||||
Text(" Файл")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
if (busy) Text("Подготавливаю…", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
},
|
||||
confirmButton = {}
|
||||
)
|
||||
}
|
||||
|
||||
if (isAdmin) {
|
||||
HorizontalDivider()
|
||||
Text("Настройки администратора", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Самостоятельно настроенные профили, параметры деплоя, пароли, токен бота, исключения и настройки выхода. Готовые управляемые профили не входят в копию и добавляются на другом устройстве через сервис, где были получены. Данные шифруются указанным паролем. Приватные SSH-ключи и конфигурации служб на VPS не передаются.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(
|
||||
onClick = { adminAction = AdminExportAction.Qr },
|
||||
enabled = !busy,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(Icons.Default.QrCode2, null, Modifier.size(18.dp))
|
||||
Text(" QR")
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { adminAction = AdminExportAction.File },
|
||||
enabled = !busy,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, null, Modifier.size(18.dp))
|
||||
Text(" Файл")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
if (busy) Text("Подготавливаю…", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
|
||||
adminAction?.let { action ->
|
||||
AdminExportPasswordDialog(
|
||||
@@ -343,7 +430,7 @@ fun AdminImportDialog(
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = { if (!busy) onDismiss() },
|
||||
title = { Text(if (decrypted == null) "Защищённые настройки" else "Заменить настройки?") },
|
||||
text = {
|
||||
@@ -359,7 +446,7 @@ fun AdminImportDialog(
|
||||
modifier = Modifier.fillMaxWidth().onFocusChanged { passwordFocused = it.isFocused }
|
||||
)
|
||||
} else {
|
||||
Text("Будут заменены все три профиля подключения и локальные настройки администратора. Текущие данные приложения восстановить автоматически не получится. Приватные SSH-ключи и конфигурации служб на VPS не входят в передачу: при необходимости добавьте их отдельно.")
|
||||
Text("Будут заменены профили и локальные настройки администратора, включённые в копию. Профили, пропущенные при экспорте, останутся без изменений. Прежние значения заменённых настроек восстановить автоматически не получится. Приватные SSH-ключи и конфигурации служб на VPS не входят в передачу: при необходимости добавьте их отдельно.")
|
||||
}
|
||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
}
|
||||
@@ -411,7 +498,7 @@ private fun AdminExportPasswordDialog(onDismiss: () -> Unit, onConfirm: (CharArr
|
||||
repeat.isNotEmpty() && password != repeat -> "Пароли не совпадают"
|
||||
else -> null
|
||||
}
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Защитить настройки") },
|
||||
text = {
|
||||
@@ -458,7 +545,7 @@ private fun QrDisplayDialog(
|
||||
if (granted) onSave()
|
||||
else Toast.makeText(context, "Без разрешения Android 9 не может сохранить QR-код в галерею.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
|
||||
@@ -30,7 +30,6 @@ import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.DeleteOutline
|
||||
import androidx.compose.material.icons.filled.LocationOn
|
||||
import androidx.compose.material.icons.filled.Wifi
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -56,7 +55,6 @@ import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.core.net.toUri
|
||||
@@ -193,7 +191,7 @@ fun TrustedWifiSettingsDialog(
|
||||
currentWifi = withContext(Dispatchers.Default) { readConnectedWifiState(context) }
|
||||
}
|
||||
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
@@ -332,7 +330,7 @@ fun TrustedWifiSettingsDialog(
|
||||
) {
|
||||
Icon(Icons.Default.Wifi, contentDescription = null, modifier = Modifier.size(19.dp))
|
||||
Text(ssid, modifier = Modifier.weight(1f).padding(horizontal = 10.dp))
|
||||
IconButton(
|
||||
HintIconButton(hint = "Удалить сеть",
|
||||
onClick = {
|
||||
scope.launch {
|
||||
settingsStore.removeTrustedWifiSsid(ssid)
|
||||
@@ -391,7 +389,7 @@ fun TrustedWifiSettingsDialog(
|
||||
}
|
||||
|
||||
if (showManualInput) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = { showManualInput = false },
|
||||
title = {
|
||||
Row(
|
||||
@@ -515,7 +513,7 @@ private fun PermissionExplanationDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
BoundedAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
icon = { Icon(Icons.Default.LocationOn, contentDescription = null) },
|
||||
title = { Text(title, textAlign = TextAlign.Center) },
|
||||
|
||||
@@ -61,7 +61,6 @@ 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
|
||||
@@ -115,7 +114,7 @@ internal fun vkClientIdAvailabilityMessage(
|
||||
cleanIds.size == 1 && rejected.isNotEmpty() ->
|
||||
"Client ID ${cleanIds.first()} не принимается резервным способом"
|
||||
cleanIds.size == 1 ->
|
||||
"Не удалось проверить Client ID ${cleanIds.first()}: сеть или временная ошибка VK"
|
||||
"Не удалось проверить Client ID ${cleanIds.first()}: сеть или временная ошибка ВК"
|
||||
rejected.isEmpty() && failed.isEmpty() -> "Все встроенные Client ID доступны для резервного способа"
|
||||
else -> buildList {
|
||||
if (available.isNotEmpty()) add("Доступны: ${available.joinToString(", ")}")
|
||||
@@ -263,7 +262,7 @@ fun VkClientSettingsDialog(
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
@@ -300,7 +299,7 @@ fun VkClientSettingsDialog(
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
"Клиенты VK",
|
||||
"Клиенты ВК",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
@@ -369,9 +368,9 @@ fun VkClientSettingsDialog(
|
||||
Text("Собственные резервные реквизиты", fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
if (enabled) {
|
||||
"После быстрого VKCalls сначала пробуется ваш Client ID."
|
||||
"После быстрых ВК Звонков сначала пробуется ваш Client ID."
|
||||
} else {
|
||||
"После быстрого VKCalls используются встроенные Client ID."
|
||||
"После быстрых ВК Звонков используются встроенные Client ID."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
@@ -392,21 +391,16 @@ fun VkClientSettingsDialog(
|
||||
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 },
|
||||
modifier = Modifier.remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Как получить Client ID и secret"
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Резервные реквизиты приложения ВК", fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.weight(1f, fill = false))
|
||||
HintIconButton(hint = "Как получить Client ID и secret", onClick = { showHelp = true }, modifier = Modifier.remoteHelpFocus()) {
|
||||
Icon(Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Как получить Client ID и secret")
|
||||
}
|
||||
}
|
||||
Text("Оба поля обязательны", style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,7 +409,7 @@ fun VkClientSettingsDialog(
|
||||
onValueChange = { clientIdInput = normalizeVkClientId(it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text("Client ID") },
|
||||
supportingText = { Text("ID приложения из кабинета VK ID") },
|
||||
supportingText = { Text("ID приложения из кабинета ВК ID") },
|
||||
enabled = !tunnelRunning,
|
||||
singleLine = true,
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
|
||||
@@ -533,7 +527,7 @@ fun VkClientSettingsDialog(
|
||||
VkClientIdProbeStatus.LegacyRejected ->
|
||||
"Client ID не принимается резервным способом"
|
||||
VkClientIdProbeStatus.CheckFailed ->
|
||||
"Проверку выполнить не удалось: сеть или временная ошибка VK"
|
||||
"Проверку выполнить не удалось: сеть или временная ошибка ВК"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = statusContentColor,
|
||||
@@ -544,7 +538,7 @@ fun VkClientSettingsDialog(
|
||||
}
|
||||
|
||||
Text(
|
||||
"Сохранённый собственный Client ID проверяется автоматически при входе. Это второй вариант после VKCalls. Такая проверка подтверждает только приём ID старым способом VK; получение TURN-данных окончательно проверяется при подключении.",
|
||||
"Сохранённый собственный Client ID проверяется автоматически при входе. Это второй вариант после быстрых ВК Звонков. Такая проверка подтверждает только приём ID старым способом ВК; получение TURN-данных окончательно проверяется при подключении.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -553,9 +547,9 @@ fun VkClientSettingsDialog(
|
||||
Text("Встроенный резерв", fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
if (enabled) {
|
||||
"Используется, если VKCalls и собственные реквизиты не сработали. Встроенный ID можно проверить нажатием на строку."
|
||||
"Используется, если ВК Звонки и собственные реквизиты не сработали. Встроенный ID можно проверить нажатием на строку."
|
||||
} else {
|
||||
"Используется, если VKCalls не сработал. Проверка запускается автоматически при входе; нажмите на строку для повтора."
|
||||
"Используется, если ВК Звонки не сработали. Проверка запускается автоматически при входе; нажмите на строку для повтора."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
@@ -641,9 +635,9 @@ fun VkClientSettingsDialog(
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f))
|
||||
Text(
|
||||
if (enabled) {
|
||||
"Порядок подключения: быстрый VKCalls без капчи → собственные реквизиты → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически."
|
||||
"Порядок подключения: быстрые ВК Звонки без капчи → собственные реквизиты → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически."
|
||||
} else {
|
||||
"Порядок подключения: быстрый VKCalls без капчи → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически."
|
||||
"Порядок подключения: быстрые ВК Звонки без капчи → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
@@ -662,9 +656,7 @@ fun VkClientSettingsDialog(
|
||||
@Composable
|
||||
private fun VkClientCredentialsHelpDialog(onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val television = isTelevisionDevice()
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val configuration = LocalConfiguration.current
|
||||
val packageName = context.packageName
|
||||
val signingSha1 = remember(context) { appSigningSha1(context) }
|
||||
|
||||
@@ -673,144 +665,30 @@ private fun VkClientCredentialsHelpDialog(onDismiss: () -> Unit) {
|
||||
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
SettingsDialogLayout(
|
||||
title = "Резервные реквизиты ВК",
|
||||
onDismiss = onDismiss,
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Surface(
|
||||
modifier = (if (television) {
|
||||
Modifier.televisionDialogWidth(television, fraction = 0.82f, maxWidth = 1_000.dp)
|
||||
} else {
|
||||
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,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
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("Понятно")
|
||||
}
|
||||
}
|
||||
}
|
||||
Text("Резервный провайдер через кабинет ВК ID", style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.65f)
|
||||
) {
|
||||
Text(
|
||||
"Собственные реквизиты относятся только к резервному legacy-провайдеру. Для основных быстрых ВК Звонков они не нужны. Понадобятся ID приложения и Защищённый ключ из одного приложения ВК; сервисный ключ доступа не подходит.",
|
||||
modifier = Modifier.padding(14.dp),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
}
|
||||
|
||||
HelpStep(
|
||||
number = 1,
|
||||
title = "Откройте кабинет ВК ID",
|
||||
text = "Войдите в аккаунт владельца приложения, откройте раздел «Мои приложения» и нажмите «Добавить приложение»."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -853,7 +731,7 @@ private fun CopyValueCard(label: String, value: String, onCopy: (() -> Unit)?) {
|
||||
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) {
|
||||
HintIconButton(hint = "Копировать", onClick = { onCopy?.invoke() }, enabled = onCopy != null) {
|
||||
Icon(Icons.Default.ContentCopy, contentDescription = "Копировать")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,6 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.wdtt.plus.VPN_DNS_CUSTOM_ID
|
||||
import com.wdtt.plus.VPN_DNS_PROFILE_ID
|
||||
@@ -117,7 +116,7 @@ internal fun VpnDnsSettingsDialog(
|
||||
var validationError by remember(initialSettings.profileIndex) { mutableStateOf<String?>(null) }
|
||||
val selectedPreset = vpnDnsPresets.firstOrNull { it.id == selectionId }
|
||||
|
||||
Dialog(
|
||||
BoundedAppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
/** Monotonic safety state shared by page callbacks and the fallback watchdog. */
|
||||
internal class ModernVkFlowGuard {
|
||||
var mutationPossible = false
|
||||
private set
|
||||
var terminal = false
|
||||
private set
|
||||
private var closed = false
|
||||
private var bridgeStarted = false
|
||||
private var containerHandoffClaimed = false
|
||||
var containerHandoffPending = false
|
||||
private set
|
||||
|
||||
val canFallback: Boolean get() = !mutationPossible && !closed
|
||||
val allowPageStatus: Boolean get() = !bridgeStarted && acceptsPageCallbacks
|
||||
val acceptsPageCallbacks: Boolean get() = !containerHandoffPending && !terminal && !closed
|
||||
|
||||
/** Reserve the mobile-to-container transition before returning to WebView. */
|
||||
fun beginContainerHandoff(): Boolean {
|
||||
if (!allowPageStatus || containerHandoffClaimed) return false
|
||||
containerHandoffClaimed = true
|
||||
containerHandoffPending = true
|
||||
return true
|
||||
}
|
||||
|
||||
fun completeContainerHandoff(): Boolean {
|
||||
if (!containerHandoffPending) return false
|
||||
containerHandoffPending = false
|
||||
return !closed && !terminal && !mutationPossible
|
||||
}
|
||||
|
||||
fun accept(stage: String): Boolean {
|
||||
if (!acceptsPageCallbacks) return false
|
||||
if (mutationPossible && (stage.startsWith("AUTH_") || stage.startsWith("CLAIM_") ||
|
||||
stage in setOf("INIT_WAIT", "SESSION_WAIT", "PROFILE_WAIT", "AUTO_READY"))) return false
|
||||
bridgeStarted = true
|
||||
if (stage.startsWith("PERMIT_WAIT_") || stage.startsWith("CALL_PERMIT_") || stage.startsWith("CALL_SENT_") || stage == "CLAIM_BLOCKED") {
|
||||
mutationPossible = true
|
||||
}
|
||||
terminal = stage == "PREP_FAILED" || stage == "FLOW_FAILED" || stage == "CLAIM_BLOCKED" ||
|
||||
listOf("CALL_TIMEOUT_", "CALL_FAILED_", "CALL_INVALID_", "CALL_EMPTY_").any(stage::startsWith)
|
||||
return true
|
||||
}
|
||||
|
||||
fun close() { closed = true }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
internal data class NativeVkAccountActions(
|
||||
val showLogin: Boolean,
|
||||
val showAcquire: Boolean,
|
||||
val showReplace: Boolean,
|
||||
val showLogout: Boolean,
|
||||
) {
|
||||
companion object {
|
||||
fun forState(
|
||||
loginPageOpen: Boolean,
|
||||
authorized: Boolean,
|
||||
hasToken: Boolean,
|
||||
acquireFallbackAvailable: Boolean,
|
||||
replacementConfirmationNeeded: Boolean,
|
||||
logoutPending: Boolean = false,
|
||||
) =
|
||||
if (logoutPending) NativeVkAccountActions(false, false, false, true) else NativeVkAccountActions(
|
||||
showLogin = !loginPageOpen && !authorized && !hasToken && !replacementConfirmationNeeded,
|
||||
showAcquire = !loginPageOpen && (authorized || hasToken) && acquireFallbackAvailable &&
|
||||
!replacementConfirmationNeeded,
|
||||
showReplace = !loginPageOpen && replacementConfirmationNeeded,
|
||||
showLogout = authorized || hasToken,
|
||||
)
|
||||
|
||||
fun replacementConfirmationNeeded(
|
||||
hasCompleteLocalValues: Boolean,
|
||||
replacementConfirmed: Boolean,
|
||||
hasRecoveredOperation: Boolean,
|
||||
): Boolean = hasCompleteLocalValues &&
|
||||
!replacementConfirmed &&
|
||||
!hasRecoveredOperation
|
||||
|
||||
fun acquireFallbackAvailable(
|
||||
busy: Boolean,
|
||||
hasError: Boolean,
|
||||
journalPhases: List<String>,
|
||||
): Boolean {
|
||||
if (busy) return false
|
||||
if (journalPhases.any { it !in setOf("received", "uploaded") }) return false
|
||||
return hasError || journalPhases.isNotEmpty()
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,87 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.os.*
|
||||
import com.wdtt.plus.*
|
||||
import kotlinx.coroutines.*
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/** Unexported same-UID IPC; only this main-process service contacts our backend. */
|
||||
class NativeVkBrokerService : Service() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private val messenger = Messenger(object : Handler(Looper.getMainLooper()) {
|
||||
override fun handleMessage(message: Message) {
|
||||
if (message.sendingUid != Process.myUid()) return
|
||||
if (message.what == 2) {
|
||||
val code = message.data.getString("code").orEmpty()
|
||||
if (NativeVkFeedback.validDiagnostic(code)) {
|
||||
TunnelManager.noteSystemLifecycleEvent("native_vk_${SystemClock.elapsedRealtime()}",
|
||||
"[ВК] ${NativeVkFeedback.presentation(code)}")
|
||||
}
|
||||
return
|
||||
}
|
||||
if (message.what != 1) return
|
||||
val reply = message.replyTo ?: return
|
||||
val id = message.arg1
|
||||
val raw = message.data.getString("body").orEmpty()
|
||||
if (raw.toByteArray().size !in 1..768) return
|
||||
scope.launch {
|
||||
val answer = try { NativeVkBackend.post(raw) } catch (error: Exception) {
|
||||
val diagnostic = NativeVkFeedback.diagnostic("BROKER", error)
|
||||
TunnelManager.noteSystemLifecycleEvent("native_vk_broker_${SystemClock.elapsedRealtime()}",
|
||||
"[ВК] ${NativeVkFeedback.presentation(diagnostic)}")
|
||||
JSONObject().put("error", "Не удалось связаться с WDTT Plus. Уже созданные ссылки сохранены; повтор передачи не создаст новые звонки.")
|
||||
}
|
||||
runCatching { reply.send(Message.obtain().apply {
|
||||
what = 1; arg1 = id; data = Bundle().apply { putString("body", answer.toString()) }
|
||||
}) }
|
||||
}
|
||||
}
|
||||
})
|
||||
override fun onBind(intent: Intent): IBinder = messenger.binder
|
||||
override fun onDestroy() { scope.cancel(); super.onDestroy() }
|
||||
}
|
||||
|
||||
internal object NativeVkBackend {
|
||||
suspend fun post(raw: String): JSONObject = withContext(Dispatchers.IO) {
|
||||
val json = JSONObject(raw)
|
||||
require(json.optString("o") in setOf("prepare", "auth", "permit", "result", "finish"))
|
||||
val encrypted = NativeVkCrypto.exchange(raw)
|
||||
val bytes = encrypted.request.toByteArray(Charsets.UTF_8)
|
||||
val url = "https://wdttplus.ru/api/client/native"
|
||||
val response = requestRemoteDocumentWithTunnelFallback(
|
||||
preferTunnel = TunnelManager.isUpdateRelayAvailable(),
|
||||
tunnelRequest = { TunnelManager.postOpaqueHttpsStatusThroughTunnel(url, bytes) },
|
||||
directRequest = {
|
||||
val connection = URL(url).openConnection() as HttpURLConnection
|
||||
try {
|
||||
connection.requestMethod = "POST"
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.connectTimeout = 4_000; connection.readTimeout = 8_000
|
||||
connection.doOutput = true
|
||||
connection.setRequestProperty("Content-Type", "application/json")
|
||||
connection.outputStream.use { it.write(bytes) }
|
||||
val status = connection.responseCode
|
||||
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
|
||||
val body = stream?.use { input ->
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
val buffer = ByteArray(1024)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
check(out.size() + n <= 32_768)
|
||||
out.write(buffer, 0, n)
|
||||
}
|
||||
out.toString("UTF-8")
|
||||
}.orEmpty()
|
||||
RemoteDocumentHttpResponse(status, body)
|
||||
} finally { connection.disconnect() }
|
||||
},
|
||||
)
|
||||
if (response.status in 200..299) encrypted.response(response.body) else JSONObject().put("error",
|
||||
"Не удалось установить защищённую связь с backend (HTTP ${response.status}).")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.*
|
||||
import androidx.annotation.Keep
|
||||
import com.wdtt.plus.*
|
||||
import kotlinx.coroutines.*
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Device-side API fallback, available only with a server-issued capability. */
|
||||
@Keep
|
||||
object NativeVkContinuation : LocalContinuationExtension {
|
||||
override suspend fun execute(activity: MainActivity, target: RemoteLaunchTarget,
|
||||
deviceId: String, hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit): Uri {
|
||||
check(target.completion.available) { "Backend не выдал разрешение на получение." }
|
||||
val profile = target.localProfile ?: error("Не указан профиль для входа.")
|
||||
ProfileWebSessionScope.requireValid(profile)
|
||||
val pending = JSONObject().put("key", target.completion.key).put("device", deviceId)
|
||||
.put("expires", target.completion.expiresAtSeconds)
|
||||
check(activity.getSharedPreferences("native-vk-return", 0).edit()
|
||||
.putString("pending", SecureStringStore(activity).encrypt(pending.toString())).commit())
|
||||
val done = CompletableDeferred<Uri>()
|
||||
val receiver = object : ResultReceiver(Handler(Looper.getMainLooper())) {
|
||||
override fun onReceiveResult(code: Int, data: Bundle?) {
|
||||
val raw = data?.getString("document").orEmpty()
|
||||
val document = RemoteDocumentGateway.extractLink(raw)
|
||||
when {
|
||||
code == 1 && document != null -> done.complete(Uri.parse(document.url))
|
||||
code == 3 -> done.completeExceptionally(LocalContinuationSafeFallbackException())
|
||||
else -> done.completeExceptionally(LocalContinuationCancelledException())
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
withContext(Dispatchers.Main.immediate) {
|
||||
activity.startActivity(Intent().apply {
|
||||
setClassName(activity, ProfileWebSessionScope.nativeActivity(profile.index))
|
||||
ProfileWebSessionScope.put(this, profile)
|
||||
addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
putExtra("key", target.completion.key)
|
||||
putExtra("device", deviceId)
|
||||
putExtra("expires", target.completion.expiresAtSeconds)
|
||||
putExtra("has_complete_values", hasCompleteLocalValues)
|
||||
putExtra("receiver", receiver)
|
||||
})
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
throw LocalContinuationSafeFallbackException()
|
||||
}
|
||||
onProgress("Получение ВК-хешей во встроенном окне…")
|
||||
return withTimeout(15 * 60_000L) { done.await() }
|
||||
}
|
||||
override fun offerCallback(uri: Uri?) = false
|
||||
override suspend fun recoverPending(activity: MainActivity): Uri? {
|
||||
// Only retry delivery of four ledger-confirmed results. Never login or call VK.
|
||||
val prefs = activity.getSharedPreferences("native-vk-return", 0)
|
||||
return runCatching {
|
||||
val pending = JSONObject(SecureStringStore(activity).decrypt(prefs.getString("pending", null)) ?: return null)
|
||||
if (pending.getLong("expires") <= System.currentTimeMillis() / 1000) {
|
||||
prefs.edit().remove("pending").commit(); return null
|
||||
}
|
||||
val result = NativeVkBackend.post(NativeVkProtocol.payload(pending.getString("key"),
|
||||
pending.getString("device"), "finish"))
|
||||
RemoteDocumentGateway.extractLink(result.optString("document"))?.let { Uri.parse(it.url) }
|
||||
}.getOrNull()
|
||||
}
|
||||
override fun acknowledgeDocument(activity: MainActivity, uri: Uri) {
|
||||
activity.getSharedPreferences("native-vk-return", 0).edit().remove("pending").commit()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import java.security.*
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
import java.security.spec.X509EncodedKeySpec
|
||||
import java.util.Base64
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyAgreement
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Relay cannot read credentials/results or forge a mutation permit. No server secret in APK. */
|
||||
internal object NativeVkCrypto {
|
||||
private const val PUBLIC_KEY = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEECxFJu55s4aJHQIWzzGLegkLacvTHxdZDB2tFyAD8d33krcIJtJohsMJorGy4gKmdTqWwNCiNE2+9gkIZhetyQ=="
|
||||
private val context = "wdtt-native-e2e-v1".toByteArray()
|
||||
private fun encode(bytes: ByteArray) = Base64.getEncoder().encodeToString(bytes)
|
||||
private fun decode(value: String) = Base64.getDecoder().decode(value)
|
||||
class Exchange(val request: String, private val key: ByteArray, private val digest: ByteArray) {
|
||||
fun response(raw: String): JSONObject {
|
||||
val json = JSONObject(raw)
|
||||
val nonce = decode(json.getString("n"))
|
||||
require(nonce.size == 12)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
|
||||
cipher.updateAAD(context + ":response:".toByteArray() + digest)
|
||||
return JSONObject(cipher.doFinal(decode(json.getString("c"))).toString(Charsets.UTF_8))
|
||||
}
|
||||
}
|
||||
fun exchange(raw: String, publicKey: String = PUBLIC_KEY): Exchange {
|
||||
val pair = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1")) }.generateKeyPair()
|
||||
val server = KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(decode(publicKey)))
|
||||
val agreement = KeyAgreement.getInstance("ECDH")
|
||||
agreement.init(pair.private); agreement.doPhase(server, true)
|
||||
val key = MessageDigest.getInstance("SHA-256").digest(agreement.generateSecret() + context)
|
||||
val body = raw.toByteArray(Charsets.UTF_8)
|
||||
val nonce = ByteArray(12).also(SecureRandom()::nextBytes)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
|
||||
cipher.updateAAD(context + ":request".toByteArray())
|
||||
val json = JSONObject().put("e", encode(pair.public.encoded)).put("n", encode(nonce))
|
||||
.put("c", encode(cipher.doFinal(body))).toString()
|
||||
require(json.toByteArray().size <= 768)
|
||||
return Exchange(json, key, MessageDigest.getInstance("SHA-256").digest(body))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
/** Never forward exception text, provider bodies, OAuth URLs or credentials to logs. */
|
||||
internal object NativeVkFeedback {
|
||||
fun diagnostic(stage: String, error: Throwable): String {
|
||||
val kind = when (error) {
|
||||
is VkHttpFailure -> "HTTP_${error.status}"
|
||||
is java.net.SocketTimeoutException -> "TIMEOUT"
|
||||
is java.io.IOException -> "NETWORK"
|
||||
else -> "FAILED"
|
||||
}
|
||||
val code = Regex("\\b(?:NET_[A-Z_]{2,32}|HTTP_[0-9]{3}|(?:IDENTITY|CHECK_TOKEN)_(?:VK_(?:[0-9]{1,7}(?:_IP_MISMATCH)?|UNKNOWN)|HTTP_[0-9]{3}|NETWORK|TIMEOUT|JSON|SHAPE|EXPIRED)|TOKEN_LENGTH|SERVICE_CONFIG)\\b")
|
||||
.find(error.message.orEmpty())?.value
|
||||
val vk = Regex("VK API: ошибка ([0-9]{1,7})\\.").find(error.message.orEmpty())?.groupValues?.get(1)
|
||||
val errno = generateSequence(error) { it.cause }.take(8)
|
||||
.filterIsInstance<android.system.ErrnoException>().firstOrNull()?.errno
|
||||
val exceptionClass = error.javaClass.simpleName.uppercase().takeIf { it.matches(Regex("[A-Z]{1,48}")) }
|
||||
return listOf(stage.takeIf { it.matches(Regex("[A-Z_]{1,32}")) } ?: "OPERATION",
|
||||
code ?: vk?.let { "VK_$it" } ?: kind, exceptionClass,
|
||||
errno?.let { "ERRNO_$it" }).filterNotNull().joinToString(" / ")
|
||||
}
|
||||
|
||||
fun validDiagnostic(value: String) = value.length <= 160 &&
|
||||
value.matches(Regex("[A-Z0-9_ /]{1,160}"))
|
||||
|
||||
fun presentation(value: String): String {
|
||||
val parts = value.split('/').map(String::trim)
|
||||
if (parts.firstOrNull()?.startsWith("CAPTCHA_") == true) return when (parts.first()) {
|
||||
"CAPTCHA_AUTOMATIC" -> "ВК запросил проверку. Выполняется одна автоматическая попытка."
|
||||
"CAPTCHA_MANUAL" -> "Пройдите проверку ВК вручную в открытом окне."
|
||||
"CAPTCHA_IDLE" -> "Проверка ВК закрыта. Продолжаю действие."
|
||||
else -> "Не удалось пройти проверку ВК автоматически. Решите её вручную."
|
||||
}
|
||||
val stage = when (parts.firstOrNull()) {
|
||||
"PREPARE", "BROKER", "BROKER_BIND", "BROKER_LOST" -> "Не удалось подготовить получение ВК-хешей."
|
||||
"NETWORK", "NETWORK_LOST", "DIRECT_FALLBACK", "WEB_FALLBACK" -> "Не удалось подготовить соединение с ВК."
|
||||
"LOGIN", "WEB_TLS", "WEB_PAGE", "WEB_RENDER", "WEB_EXTERNAL" -> "Не удалось открыть страницу входа ВК."
|
||||
"VK_ID_CALLBACK", "OAUTH_CALLBACK", "IDENTITY" -> "Не удалось завершить вход в ВК."
|
||||
"PERMIT" -> "Не удалось безопасно начать получение ВК-хешей."
|
||||
"CALL" -> "ВК не создал ссылку звонка. Автоматический повтор отключён."
|
||||
"CAPTCHA" -> "Проверка ВК не завершена. Повторный запрос не отправлен."
|
||||
"UPLOAD", "FINISH" -> "Не удалось сохранить полученные ВК-хеши. Повтор не создаст новые ссылки."
|
||||
"RESTORE" -> "Не удалось восстановить сохранённое состояние получения."
|
||||
"LOGOUT" -> "Не удалось полностью завершить выход из ВК."
|
||||
else -> "Не удалось завершить получение ВК-хешей."
|
||||
}
|
||||
val detail = when {
|
||||
parts.any { it == "TIMEOUT" } -> "Время ожидания истекло."
|
||||
parts.any { it == "NETWORK" } -> "Проверьте подключение к интернету."
|
||||
else -> "Подробности сохранены без личных данных."
|
||||
}
|
||||
return "$stage $detail"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
/** Callback snapshots only: onAvailable is not proof that capabilities are readable. */
|
||||
internal class NativeVkNetworkGate<N>(private val requireBlockedStatus: Boolean) {
|
||||
private var current: N? = null
|
||||
private var physical = false
|
||||
private var links = false
|
||||
private var unblocked = !requireBlockedStatus
|
||||
|
||||
fun available(value: N) {
|
||||
current = value; physical = false; links = false; unblocked = !requireBlockedStatus
|
||||
}
|
||||
fun capabilities(value: N, notVpn: Boolean, internet: Boolean) {
|
||||
if (current == value) physical = notVpn && internet
|
||||
}
|
||||
fun linkProperties(value: N) { if (current == value) links = true }
|
||||
fun blocked(value: N, blocked: Boolean) { if (current == value) unblocked = !blocked }
|
||||
fun lost(value: N) { if (current == value) { current = null; physical = false; links = false } }
|
||||
fun ready(value: N) = current == value && physical && links && unblocked
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import java.net.URI
|
||||
import org.json.JSONObject
|
||||
|
||||
internal object NativeVkProtocol {
|
||||
fun mayCreate(phases: List<String>): Boolean = phases.size < 4 && phases.all { it == "uploaded" }
|
||||
|
||||
fun hash(response: JSONObject): String {
|
||||
VkApiProtocol.apiError(response)?.let { throw IllegalStateException(it) }
|
||||
VkApiProtocol.started(response) // Validate call identity before accepting its link.
|
||||
val result = response.getJSONObject("response")
|
||||
val uri = URI(result.getString("join_link"))
|
||||
require(uri.scheme == "https" && uri.rawUserInfo == null && uri.port in setOf(-1, 443))
|
||||
require(uri.host in setOf("vk.ru", "vk.com", "m.vk.ru", "m.vk.com"))
|
||||
require(uri.rawPath.startsWith("/call/join/"))
|
||||
val hash = uri.rawPath.removePrefix("/call/join/")
|
||||
require(Regex("[A-Za-z0-9_-]{16,512}").matches(hash))
|
||||
return hash
|
||||
}
|
||||
|
||||
fun payload(key: String, device: String, op: String, extras: JSONObject = JSONObject()): String {
|
||||
require(Regex("[A-Za-z0-9_.-]{24,100}").matches(key))
|
||||
require(Regex("[A-Za-z0-9_.:-]{8,128}").matches(device))
|
||||
require(op in setOf("prepare", "auth", "permit", "result", "finish"))
|
||||
val result = JSONObject().put("k", key).put("d", device).put("o", op)
|
||||
extras.keys().forEach { field ->
|
||||
require(field in setOf("a", "v", "i", "n"))
|
||||
result.put(field, extras.get(field))
|
||||
}
|
||||
return result.toString().also { require(it.toByteArray(Charsets.UTF_8).size <= 768) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
internal object NativeVkRoutePolicy {
|
||||
fun mayFallback(usingDefault: Boolean, attemptCount: Int) = !usingDefault && attemptCount == 0
|
||||
fun needsLogin(savedRoute: String, selectedRoute: String) =
|
||||
if (savedRoute.isEmpty()) selectedRoute.endsWith(":default") else savedRoute != selectedRoute
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import java.net.URI
|
||||
|
||||
/** Fail closed for the login document without aborting it for a blocked subresource. */
|
||||
internal object NativeVkSslPolicy {
|
||||
fun isMainFrameFailure(mainFrameUrl: String, failedUrl: String?): Boolean {
|
||||
val failed = canonical(failedUrl) ?: return true
|
||||
val main = canonical(mainFrameUrl) ?: return true
|
||||
return failed == main
|
||||
}
|
||||
|
||||
private fun canonical(raw: String?): String? = runCatching {
|
||||
val uri = URI(raw?.takeIf { it.length in 1..16_384 } ?: return null)
|
||||
val host = uri.host?.lowercase() ?: return null
|
||||
if (uri.scheme != "https" || uri.rawUserInfo != null || uri.port !in setOf(-1, 443)) return null
|
||||
URI("https", null, host, -1, uri.rawPath.orEmpty().ifEmpty { "/" }, uri.rawQuery, null).toASCIIString()
|
||||
}.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
internal fun ProfileSessionPreparation(status: String, failed: Boolean, close: () -> Unit) {
|
||||
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = .58f)).systemBarsPadding(),
|
||||
contentAlignment = Alignment.Center) {
|
||||
Surface(Modifier.fillMaxWidth().padding(12.dp), shape = RoundedCornerShape(24.dp)) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("ВК-хеши", Modifier.weight(1f), style = MaterialTheme.typography.titleLarge)
|
||||
IconButton(onClick = close) { Icon(Icons.Default.Close, "Закрыть") }
|
||||
}
|
||||
Text(status, color = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface)
|
||||
if (!failed) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.wdtt.plus.LocalContinuationProfile
|
||||
|
||||
/** One OS/WebView data partition for each of the app's three local profile slots. */
|
||||
internal object ProfileWebSessionScope {
|
||||
private const val SLOT = "local_profile_slot"
|
||||
private const val IDENTITY = "local_profile_identity"
|
||||
|
||||
fun requireValid(profile: LocalContinuationProfile) {
|
||||
require(profile.index in 0..2 && profile.identity.matches(Regex("[a-f0-9]{64}"))) {
|
||||
"Не удалось определить профиль для входа."
|
||||
}
|
||||
}
|
||||
|
||||
fun modernActivity(index: Int) = activity("Modern", index)
|
||||
fun nativeActivity(index: Int) = activity("Native", index)
|
||||
private fun activity(engine: String, index: Int): String {
|
||||
require(index in 0..2)
|
||||
return "com.wdtt.plus.vk.${engine}VkProfile${index}Activity"
|
||||
}
|
||||
|
||||
fun processSuffix(index: Int): String {
|
||||
require(index in 0..2)
|
||||
return ":local_web_auth_p$index"
|
||||
}
|
||||
|
||||
fun webDataSuffix(index: Int): String {
|
||||
require(index in 0..2)
|
||||
return "local-vk-profile-$index-v1"
|
||||
}
|
||||
|
||||
fun put(intent: Intent, profile: LocalContinuationProfile) {
|
||||
requireValid(profile)
|
||||
intent.putExtra(SLOT, profile.index).putExtra(IDENTITY, profile.identity)
|
||||
}
|
||||
|
||||
fun read(context: Context, intent: Intent): LocalContinuationProfile {
|
||||
val profile = LocalContinuationProfile(intent.getIntExtra(SLOT, -1), intent.getStringExtra(IDENTITY).orEmpty())
|
||||
requireValid(profile)
|
||||
check(Application.getProcessName() == context.packageName + processSuffix(profile.index)) {
|
||||
"Окно входа не соответствует выбранному профилю."
|
||||
}
|
||||
return profile
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Person
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.json.JSONObject
|
||||
|
||||
internal object VkAccountChoicePolicy {
|
||||
// Anonymous cookies alone are not proof of login, but they MUST NOT allow
|
||||
// silently skipping account selection if a login hint was lost on process death.
|
||||
fun required(remembered: Boolean, hasCookies: Boolean, hasToken: Boolean = false) =
|
||||
remembered || hasCookies || hasToken
|
||||
}
|
||||
|
||||
internal class VkAccountIdentity(val id: Long, val name: String) {
|
||||
companion object {
|
||||
fun from(id: Long, name: String): VkAccountIdentity {
|
||||
require(id > 0 && name.length <= 160)
|
||||
val clean = name.filterNot { it.isISOControl() || it in '\u202a'..'\u202e' || it in '\u2066'..'\u2069' }
|
||||
.trim().replace(Regex("\\s+"), " ")
|
||||
require(clean.isNotBlank())
|
||||
return VkAccountIdentity(id, clean)
|
||||
}
|
||||
|
||||
fun fromApi(json: JSONObject): VkAccountIdentity {
|
||||
check(!json.has("error")) { "ACCOUNT_UNAVAILABLE" }
|
||||
val profiles = json.getJSONArray("response")
|
||||
require(profiles.length() == 1)
|
||||
val profile = profiles.getJSONObject(0)
|
||||
return from(profile.getLong("id"),
|
||||
listOf(profile.optString("first_name"), profile.optString("last_name"))
|
||||
.filter(String::isNotBlank).joinToString(" "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class VkAccountMessage(val account: VkAccountIdentity, val nonce: String) {
|
||||
fun continueReply(): String = JSONObject().put("nonce", nonce).put("action", "continue").toString()
|
||||
|
||||
companion object {
|
||||
fun parse(raw: String, expectedState: String): VkAccountMessage {
|
||||
require(raw.length <= 4096 && expectedState.isNotBlank())
|
||||
val json = JSONObject(raw)
|
||||
require(json.getString("event") == "account" && json.getString("state") == expectedState)
|
||||
val nonce = json.getString("nonce")
|
||||
require(nonce.matches(Regex("ac1_[A-Za-z0-9_-]{16,96}")))
|
||||
return VkAccountMessage(VkAccountIdentity.from(json.getLong("id"), json.getString("name")), nonce)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun VkAccountChoicePanel(account: VkAccountIdentity, enabled: Boolean = true,
|
||||
onContinue: () -> Unit, onLogout: () -> Unit) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Icon(Icons.Default.Person, null, Modifier.size(32.dp), tint = MaterialTheme.colorScheme.primary)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Аккаунт ВК этого профиля", style = MaterialTheme.typography.bodySmall)
|
||||
Text(account.name, style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
}
|
||||
Text("Продолжить с этим аккаунтом или войти в другой?", style = MaterialTheme.typography.bodyMedium)
|
||||
Button(onClick = onContinue, enabled = enabled, modifier = Modifier.fillMaxWidth()) { Text("Продолжить") }
|
||||
OutlinedButton(onClick = onLogout, enabled = enabled, modifier = Modifier.fillMaxWidth()) { Text("Выйти из ВК") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
/** A definitive API rejection, not a timeout or permission to replay an uncertain call. */
|
||||
internal class VkApiCaptcha private constructor(val url: String, private val parameters: Map<String, String>) {
|
||||
fun continuation(success: String): Map<String, String> {
|
||||
require(validProof(success))
|
||||
return parameters + mapOf("captcha_key" to "", "success_token" to success)
|
||||
}
|
||||
companion object {
|
||||
fun validProof(value: String) = value.matches(Regex("[A-Za-z0-9._~+/=-]{1,8192}"))
|
||||
suspend fun continueRejected(
|
||||
result: JSONObject,
|
||||
solve: suspend (VkApiCaptcha) -> String,
|
||||
send: suspend (Map<String, String>) -> JSONObject,
|
||||
): JSONObject {
|
||||
if (result.optJSONObject("error")?.optInt("error_code") != 14) return result
|
||||
val challenge = parse(result) ?: error("ВК не предоставил доступную страницу проверки.")
|
||||
// No loop. A second rejection is returned to the caller as an error.
|
||||
return send(challenge.continuation(solve(challenge)))
|
||||
}
|
||||
|
||||
fun parse(response: JSONObject): VkApiCaptcha? {
|
||||
val error = response.optJSONObject("error") ?: return null
|
||||
if (error.optInt("error_code") != 14 || response.has("response")) return null
|
||||
val url = error.optString("redirect_uri")
|
||||
val sid = error.optString("captcha_sid")
|
||||
if (url.length !in 1..16384 || !VkCaptchaPolicy.captchaPage(url) || !sid.matches(Regex("[A-Za-z0-9_-]{1,256}"))) return null
|
||||
val fields = linkedMapOf("captcha_sid" to sid)
|
||||
for (key in listOf("captcha_ts", "captcha_attempt")) {
|
||||
val value = error.optString(key)
|
||||
if (value.isNotEmpty()) {
|
||||
if (!value.matches(Regex("[0-9]{1,20}"))) return null
|
||||
fields[key] = value
|
||||
}
|
||||
}
|
||||
return VkApiCaptcha(url, fields)
|
||||
}
|
||||
|
||||
// Used ONLY while an explicit REST error 14 challenge is open. Never
|
||||
// attached to login/consent; no tokens, responses or bodies go to logs.
|
||||
val completionScript = """
|
||||
(() => {
|
||||
if (window.__wdttApiCaptchaInstalled || !window.WDTTApiCaptchaResult ||
|
||||
!/(?:not_robot|captcha)/i.test(location.pathname)) return;
|
||||
window.__wdttApiCaptchaInstalled = true;
|
||||
const channel = window.WDTTApiCaptchaResult;
|
||||
let nonce = '';
|
||||
channel.onmessage = event => {
|
||||
try {
|
||||
const value = JSON.parse(event.data).observe;
|
||||
if (typeof value === 'string' && /^[A-Za-z0-9_-]{16,80}${'$'}/.test(value)) nonce = value;
|
||||
} catch (_) {}
|
||||
};
|
||||
channel.postMessage(JSON.stringify({page: location.href}));
|
||||
const emit = json => {
|
||||
const token = json && json.response && json.response.success_token;
|
||||
if (nonce && typeof token === 'string' && /^[A-Za-z0-9._~+/=-]{1,8192}${'$'}/.test(token)) {
|
||||
channel.postMessage(JSON.stringify({nonce, proof: token}));
|
||||
}
|
||||
};
|
||||
const isCheck = raw => {
|
||||
try {
|
||||
const url = new URL(raw, location.href);
|
||||
return url.protocol === 'https:' &&
|
||||
/^(id|api)\.vk\.(ru|com)${'$'}/.test(url.hostname) &&
|
||||
url.pathname.endsWith('/captchaNotRobot.check');
|
||||
} catch (_) { return false; }
|
||||
};
|
||||
const fetchOriginal = window.fetch;
|
||||
if (fetchOriginal) window.fetch = function(input) {
|
||||
const result = fetchOriginal.apply(this, arguments);
|
||||
if (nonce && isCheck(typeof input === 'string' ? input : input && input.url)) {
|
||||
result.then(response => response.clone().json().then(emit).catch(() => {})).catch(() => {});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const open = XMLHttpRequest.prototype.open, send = XMLHttpRequest.prototype.send;
|
||||
const checks = new WeakSet();
|
||||
XMLHttpRequest.prototype.open = function(method, url) {
|
||||
checks.delete(this); if (nonce && isCheck(url)) checks.add(this);
|
||||
return open.apply(this, arguments);
|
||||
};
|
||||
XMLHttpRequest.prototype.send = function() {
|
||||
if (checks.has(this)) this.addEventListener('load', () => {
|
||||
try { emit(this.responseType === 'json' ? this.response : JSON.parse(this.responseText)); } catch (_) {}
|
||||
}, {once: true});
|
||||
return send.apply(this, arguments);
|
||||
};
|
||||
})();
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import java.net.URI
|
||||
import java.net.URLDecoder
|
||||
import java.net.URLEncoder
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import org.json.JSONObject
|
||||
|
||||
internal object VkApiProtocol {
|
||||
const val CLIENT_ID = "54670575"
|
||||
const val REDIRECT = "vk54670575://vk.ru/blank.html"
|
||||
const val START_ENDPOINT = "https://api.vk.ru/method/calls.start"
|
||||
const val USER_ENDPOINT = "https://api.vk.ru/method/users.get"
|
||||
|
||||
// Intentionally not data classes: their toString() must not expose credentials.
|
||||
class AuthAttempt(val verifier: String, val state: String) {
|
||||
val challenge: String get() = base64(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray()))
|
||||
fun url(): String = "https://id.vk.ru/authorize?" + encode(linkedMapOf(
|
||||
"client_id" to CLIENT_ID, "redirect_uri" to REDIRECT, "response_type" to "code",
|
||||
"scope" to "vkid.personal_info", "state" to state,
|
||||
"code_challenge" to challenge, "code_challenge_method" to "S256",
|
||||
))
|
||||
}
|
||||
class Callback(val code: String, val deviceId: String)
|
||||
class Token(val value: String, val expiresAt: Long)
|
||||
class Started(val callId: String, val linkReceived: Boolean)
|
||||
|
||||
fun newAttempt(): AuthAttempt = AuthAttempt(random(), random())
|
||||
private fun random(): String = base64(ByteArray(32).also(SecureRandom()::nextBytes))
|
||||
private fun base64(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
|
||||
fun encode(fields: Map<String, String>): String = fields.entries.joinToString("&") {
|
||||
URLEncoder.encode(it.key, "UTF-8") + "=" + URLEncoder.encode(it.value, "UTF-8")
|
||||
}
|
||||
|
||||
fun allowedPage(raw: String): Boolean = runCatching {
|
||||
require(raw.length <= 16_384)
|
||||
val uri = URI(raw)
|
||||
val host = uri.host?.lowercase() ?: return false
|
||||
uri.scheme == "https" && uri.userInfo == null && uri.port in setOf(-1, 443) &&
|
||||
(host == "vk.ru" || host.endsWith(".vk.ru") || host == "vk.com" || host.endsWith(".vk.com"))
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun isCallback(raw: String): Boolean = runCatching {
|
||||
val uri = URI(raw)
|
||||
uri.scheme == "vk$CLIENT_ID" && uri.host == "vk.ru" && uri.rawPath == "/blank.html" &&
|
||||
uri.rawUserInfo == null && uri.port == -1
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun callback(raw: String, expectedState: String): Callback {
|
||||
require(raw.length <= 16_384 && isCallback(raw))
|
||||
val uri = URI(raw)
|
||||
require(uri.rawFragment == null)
|
||||
val fields = mutableMapOf<String, String>()
|
||||
uri.rawQuery.orEmpty().split('&').forEach {
|
||||
val pair = it.split('=', limit = 2)
|
||||
require(pair.size == 2)
|
||||
val key = URLDecoder.decode(pair[0], "UTF-8")
|
||||
require(!fields.containsKey(key))
|
||||
fields[key] = URLDecoder.decode(pair[1], "UTF-8")
|
||||
}
|
||||
require(MessageDigest.isEqual(fields["state"].orEmpty().toByteArray(), expectedState.toByteArray()))
|
||||
require(!fields.containsKey("error"))
|
||||
val code = fields["code"].orEmpty()
|
||||
val device = fields["device_id"].orEmpty()
|
||||
require(code.length in 1..4096 && device.length in 1..4096)
|
||||
return Callback(code, device)
|
||||
}
|
||||
|
||||
fun started(json: JSONObject): Started {
|
||||
val result = json.getJSONObject("response")
|
||||
val id = result.getString("call_id")
|
||||
require(Regex("[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}").matches(id))
|
||||
val hasLink = listOf("join_link", "ok_join_link").any {
|
||||
runCatching {
|
||||
val uri = URI(result.optString(it))
|
||||
uri.scheme == "https" && uri.host != null && uri.rawUserInfo == null &&
|
||||
!uri.rawPath.isNullOrBlank()
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
return Started(id, hasLink)
|
||||
}
|
||||
|
||||
fun apiError(json: JSONObject, method: String = "calls.start"): String? {
|
||||
require(method == "calls.start")
|
||||
if (!json.has("error")) return null
|
||||
val code = json.optJSONObject("error")?.optInt("error_code", -1) ?: -1
|
||||
return if (code == 1051) "VK API: ошибка 1051. Метод недоступен этому типу приложения/токена. Вход выполнен, но $method недоступен."
|
||||
else if (code in 0..1_000_000) "VK API: ошибка $code. Повторный $method не выполнялся."
|
||||
else "VK API вернул неизвестную ошибку. Повторный $method не выполнялся."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import java.net.URI
|
||||
|
||||
/** Presentation/one-click budget only: never grants permission to replay an API request. */
|
||||
internal class VkCaptchaPolicy {
|
||||
enum class State { IDLE, AUTOMATIC, MANUAL, ERROR }
|
||||
data class Frame(val generation: Int, val state: String, val seenAt: Long)
|
||||
private val frames = linkedMapOf<String, Frame>()
|
||||
private val attempted = mutableSetOf<String>()
|
||||
private val manual = mutableSetOf<String>()
|
||||
private var clicks = 0
|
||||
var state = State.IDLE
|
||||
private set
|
||||
val active get() = state != State.IDLE
|
||||
fun update(frame: String, generation: Int, state: String, now: Long, foreground: Boolean): String? {
|
||||
if (!frame.matches(Regex("[a-z0-9]{1,64}")) || generation !in 0..128 ||
|
||||
state !in setOf("clear", "checkbox", "automatic", "waiting", "manual", "error")) return null
|
||||
if (frames[frame]?.generation?.let { it > generation } == true) return null
|
||||
if (state == "clear") frames.remove(frame)
|
||||
else if (frames.size < 16 || frame in frames) frames[frame] = Frame(generation, state, now)
|
||||
val key = "$frame:$generation"
|
||||
if (state == "manual" || state == "error") manual.add(key)
|
||||
val action = if (state == "checkbox" && foreground && frame in frames && key !in attempted && key !in manual) {
|
||||
if (clicks < 4) { attempted.add(key); clicks++; "click" }
|
||||
else { manual.add(key); "manual" }
|
||||
} else null
|
||||
refresh(now)
|
||||
return action
|
||||
}
|
||||
fun userInteraction(now: Long) {
|
||||
frames.forEach { (id, frame) -> manual.add("$id:${frame.generation}") }
|
||||
refresh(now)
|
||||
}
|
||||
fun refresh(now: Long) {
|
||||
frames.entries.removeAll { now - it.value.seenAt > 3500 }
|
||||
state = when {
|
||||
frames.isEmpty() -> State.IDLE
|
||||
frames.values.any { it.state == "error" } -> State.ERROR
|
||||
frames.any { (id, frame) -> frame.state == "manual" || "$id:${frame.generation}" in manual } -> State.MANUAL
|
||||
frames.values.any { it.state == "checkbox" || it.state == "automatic" } -> State.AUTOMATIC
|
||||
else -> State.MANUAL
|
||||
}
|
||||
}
|
||||
companion object {
|
||||
val origins = setOf("https://vk.ru", "https://m.vk.ru", "https://www.vk.ru", "https://id.vk.ru",
|
||||
"https://login.vk.ru", "https://oauth.vk.ru", "https://api.vk.ru",
|
||||
"https://vk.com", "https://m.vk.com", "https://www.vk.com", "https://id.vk.com",
|
||||
"https://login.vk.com", "https://oauth.vk.com", "https://api.vk.com")
|
||||
fun trustedOrigin(raw: String): Boolean = runCatching {
|
||||
val uri = URI(raw)
|
||||
uri.rawUserInfo == null && uri.port in setOf(-1, 443) && "${uri.scheme}://${uri.host}" in origins
|
||||
}.getOrDefault(false)
|
||||
fun captchaPage(raw: String): Boolean = trustedOrigin(raw) && runCatching {
|
||||
val path = URI(raw).path.orEmpty().lowercase()
|
||||
"captcha" in path || "not_robot" in path
|
||||
}.getOrDefault(false)
|
||||
fun message(state: State): String = when (state) {
|
||||
State.AUTOMATIC -> "ВК запросил проверку. Пробую пройти её автоматически…"
|
||||
State.MANUAL -> "Пройдите проверку ВК в этом окне. Затем действие продолжится."
|
||||
State.ERROR -> "Проверка ВК не пройдена. Решите её на странице ВК."
|
||||
State.IDLE -> "Проверка завершена. Продолжаю…"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
/** Runs only in allow-listed VK frames. Never inspects login fields, cookies or page text. */
|
||||
internal object VkCaptchaScript {
|
||||
const val CHANNEL = "WDTTInPlaceCaptcha"
|
||||
val source = """
|
||||
(() => {
|
||||
if (window.__wdttCaptchaInstalled || !window.WDTTInPlaceCaptcha) return;
|
||||
window.__wdttCaptchaInstalled = true;
|
||||
const channel = window.WDTTInPlaceCaptcha;
|
||||
if (location.origin === 'https://wdttplus.ru') {
|
||||
channel.onmessage = event => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (typeof data.pending === 'boolean') {
|
||||
window.__wdttCaptchaPending = data.pending;
|
||||
window.__wdttCaptchaHeartbeat = Date.now();
|
||||
}
|
||||
if (data.api && typeof window.__wdttApiCaptchaReply === 'function') window.__wdttApiCaptchaReply(data);
|
||||
} catch (_) {}
|
||||
};
|
||||
channel.postMessage('{"state":"runtime"}');
|
||||
window.__wdttCaptchaApiAvailable = true;
|
||||
return;
|
||||
}
|
||||
const frame = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
||||
let generation = 0, present = false, attempted = false, manual = false;
|
||||
let automaticUntil = 0, emptySince = 0, lastState = '', stopped = false;
|
||||
const complexSelector = '[class*="SliderCaptcha"], [class*="Kaleidoscope"], [class*="SwipeButton"], [class*="PuzzleCaptcha"]';
|
||||
const checkboxSelector = '#not-robot-captcha-checkbox, label[for="not-robot-captcha-checkbox"]';
|
||||
const rootSelector = '[class*="Captcha"], [class*="captcha"], [id*="captcha"]';
|
||||
const frameSelector = 'iframe[src*="captcha"], iframe[src*="not_robot"]';
|
||||
function visible(node) {
|
||||
if (!node || !node.isConnected) return false;
|
||||
const rect = node.getBoundingClientRect();
|
||||
if (rect.width <= 4 || rect.height <= 4 || node.getClientRects().length === 0) return false;
|
||||
// A preloaded challenge/error can have its own rectangle while a
|
||||
// parent is transparent. Never latch manual mode for that hidden DOM.
|
||||
for (let parent = node; parent; parent = parent.parentElement) {
|
||||
const style = getComputedStyle(parent);
|
||||
if (style.display === 'none' || style.visibility === 'hidden' ||
|
||||
style.visibility === 'collapse' || Number(style.opacity) === 0 ||
|
||||
style.contentVisibility === 'hidden') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function first(selector, root = document) {
|
||||
return Array.from(root.querySelectorAll(selector)).find(visible) || null;
|
||||
}
|
||||
function checkbox() {
|
||||
const input = document.getElementById('not-robot-captcha-checkbox');
|
||||
if (!input || input.type !== 'checkbox' || input.checked || input.disabled ||
|
||||
input.getAttribute('aria-checked') === 'true') return null;
|
||||
// VK hides the actual input inside an implicit label (no "for").
|
||||
// Only labels associated with this EXACT input are eligible.
|
||||
const labels = Array.from(input.labels || []);
|
||||
const enclosing = input.closest('label');
|
||||
if (enclosing && enclosing.control === input && !labels.includes(enclosing)) labels.push(enclosing);
|
||||
for (const label of labels) {
|
||||
if (!visible(label)) continue;
|
||||
const icon = first('[class*="Checkbox__iconBlock"]', label);
|
||||
return icon || label;
|
||||
}
|
||||
return first(checkboxSelector);
|
||||
}
|
||||
function send(state) {
|
||||
lastState = state;
|
||||
channel.postMessage(JSON.stringify({frame, generation, state}));
|
||||
}
|
||||
function scan() {
|
||||
if (stopped) return;
|
||||
try {
|
||||
const box = checkbox(), complex = first(complexSelector), root = first(rootSelector);
|
||||
const iframe = first(frameSelector);
|
||||
const captchaPage = /(?:not_robot|captcha)/i.test(location.pathname);
|
||||
const found = box || complex || root || iframe || captchaPage;
|
||||
if (!found) {
|
||||
if (!emptySince) emptySince = Date.now();
|
||||
if (present && Date.now() - emptySince < 1500) return;
|
||||
present = false; attempted = false; manual = false;
|
||||
send('clear');
|
||||
return;
|
||||
}
|
||||
emptySince = 0;
|
||||
if (!present) { present = true; generation++; }
|
||||
// Empty live regions and decorative "Error" CSS classes are not
|
||||
// evidence that VK rejected a check. No page text is read.
|
||||
const input = document.getElementById('not-robot-captcha-checkbox');
|
||||
const failed = root && Array.from(root.querySelectorAll('[role="alert"]:not(:empty), [class*="CaptchaError"]:not(:empty), [class*="captcha-error"]:not(:empty), [data-testid="captcha-error"]:not(:empty)'))
|
||||
.find(node => visible(node) && (!input || !node.contains(input)));
|
||||
if (failed) { manual = true; send('error'); }
|
||||
else if (complex) { manual = true; send('manual'); }
|
||||
else if (manual) send('manual');
|
||||
else if (attempted) {
|
||||
if (Date.now() >= automaticUntil) { manual = true; send('manual'); }
|
||||
else send('automatic');
|
||||
} else if (box) send('checkbox');
|
||||
else send('waiting'); // Parent iframe detector never clicks through another origin.
|
||||
} catch (_) { manual = true; send('error'); }
|
||||
}
|
||||
channel.onmessage = event => {
|
||||
let command;
|
||||
try { command = JSON.parse(event.data); } catch (_) { return; }
|
||||
if (command.frame !== frame || command.generation !== generation || !present || stopped) return;
|
||||
if (command.action === 'manual') { manual = true; scan(); return; }
|
||||
if (command.action !== 'click' || attempted || manual || lastState !== 'checkbox') return;
|
||||
// Latch BEFORE scheduling; duplicate messages or DOM rerenders cannot click twice.
|
||||
attempted = true; automaticUntil = Date.now() + 8000;
|
||||
setTimeout(() => {
|
||||
if (stopped || manual || !present) return;
|
||||
if (document.visibilityState === 'hidden') { manual = true; scan(); return; }
|
||||
const box = checkbox();
|
||||
if (!box || first(complexSelector)) { manual = true; scan(); return; }
|
||||
try { box.click(); } catch (_) { manual = true; }
|
||||
scan();
|
||||
}, 350);
|
||||
};
|
||||
function userInput(event) {
|
||||
if (event.isTrusted && present) { manual = true; scan(); }
|
||||
}
|
||||
document.addEventListener('pointerdown', userInput, true);
|
||||
document.addEventListener('touchstart', userInput, true);
|
||||
document.addEventListener('keydown', userInput, true);
|
||||
const timer = setInterval(scan, 500);
|
||||
window.addEventListener('pagehide', () => {
|
||||
stopped = true; clearInterval(timer); send('clear');
|
||||
}, {once: true});
|
||||
scan();
|
||||
})();
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
|
||||
/** Pause the remaining network budget, not a new attempt; manual waiting is bounded. */
|
||||
internal class VkCaptchaTimeout(private val expired: () -> Unit) {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val budget = VkCaptchaDeadline()
|
||||
private val task = Runnable { budget.cancel(); expired() }
|
||||
fun arm(milliseconds: Long) { budget.arm(milliseconds, SystemClock.elapsedRealtime()); schedule() }
|
||||
fun armIfIdle(milliseconds: Long) {
|
||||
budget.armIfIdle(milliseconds, SystemClock.elapsedRealtime())
|
||||
schedule()
|
||||
}
|
||||
fun pause(value: Boolean) { budget.pause(value, SystemClock.elapsedRealtime()); schedule() }
|
||||
private fun schedule() {
|
||||
handler.removeCallbacks(task)
|
||||
budget.delay(SystemClock.elapsedRealtime())?.let { handler.postDelayed(task, it) }
|
||||
}
|
||||
fun cancel() { budget.cancel(); handler.removeCallbacks(task) }
|
||||
}
|
||||
|
||||
/** Pure clock model, exercised without Android or a live WebView. */
|
||||
internal class VkCaptchaDeadline {
|
||||
private var due = 0L
|
||||
private var remaining: Long? = null
|
||||
private var paused = false
|
||||
private var pauseStarted = 0L
|
||||
fun arm(milliseconds: Long, now: Long) {
|
||||
remaining = milliseconds
|
||||
if (!paused) due = now + milliseconds
|
||||
}
|
||||
fun armIfIdle(milliseconds: Long, now: Long) {
|
||||
if (remaining == null) arm(milliseconds, now)
|
||||
}
|
||||
fun pause(value: Boolean, now: Long) {
|
||||
if (paused == value) return
|
||||
if (value) {
|
||||
remaining = remaining?.let { (due - now).coerceAtLeast(1) }
|
||||
pauseStarted = now
|
||||
} else remaining?.let { due = now + it }
|
||||
paused = value
|
||||
}
|
||||
fun delay(now: Long): Long? {
|
||||
remaining ?: return null
|
||||
return if (paused) (180_000 - (now - pauseStarted)).coerceAtLeast(1) else (due - now).coerceAtLeast(1)
|
||||
}
|
||||
fun cancel() { remaining = null }
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.ResultReceiver
|
||||
import android.os.Build
|
||||
import android.webkit.WebView
|
||||
import androidx.annotation.Keep
|
||||
import com.wdtt.plus.LocalContinuationExtension
|
||||
import com.wdtt.plus.LocalContinuationCancelledException
|
||||
import com.wdtt.plus.LocalContinuationSafeFallbackException
|
||||
import com.wdtt.plus.MainActivity
|
||||
import com.wdtt.plus.RemoteContinuationLauncher
|
||||
import com.wdtt.plus.RemoteActionCompletion
|
||||
import com.wdtt.plus.RemoteActionCompletionState
|
||||
import com.wdtt.plus.RemoteDocumentGateway
|
||||
import com.wdtt.plus.RemoteLaunchTarget
|
||||
import com.wdtt.plus.SecureStringStore
|
||||
import com.wdtt.plus.TemporaryDirectRouteLease
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.TimeoutCancellationException
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.selects.select
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import org.json.JSONObject
|
||||
import java.util.UUID
|
||||
|
||||
private class ModernVkSafeFallbackException : IllegalStateException("Нужен резервный способ получения ВК-хешей.")
|
||||
|
||||
/** Device-side provider adapter. Entitlements and result delivery remain server-authoritative. */
|
||||
@Keep
|
||||
object VkContinuationExecutor : LocalContinuationExtension {
|
||||
private data class ActiveCallback(val result: CompletableDeferred<Uri?>)
|
||||
private data class PendingCompletion(
|
||||
val completion: RemoteActionCompletion,
|
||||
val deviceId: String,
|
||||
val documentUrl: String = "",
|
||||
)
|
||||
|
||||
private val callbackLock = Any()
|
||||
private var activeCallback: ActiveCallback? = null
|
||||
private var recoveryInProgress = false
|
||||
|
||||
override val experimentalAvailable: Boolean
|
||||
get() = runCatching { Class.forName(MODERN_ACTIVITY_CLASS) }.isSuccess
|
||||
|
||||
override suspend fun execute(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit,
|
||||
): Uri = executePreferredChain(
|
||||
activity,
|
||||
target,
|
||||
deviceId,
|
||||
hasCompleteLocalValues,
|
||||
onProgress,
|
||||
)
|
||||
|
||||
override fun offerCallback(uri: Uri?): Boolean {
|
||||
val current = synchronized(callbackLock) { activeCallback } ?: return false
|
||||
if (uri != null && !isAcceptedCallback(uri)) return false
|
||||
current.result.complete(uri)
|
||||
return true
|
||||
}
|
||||
|
||||
override suspend fun executeExperimental(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit,
|
||||
): Uri = executePreferredChain(
|
||||
activity,
|
||||
target,
|
||||
deviceId,
|
||||
hasCompleteLocalValues,
|
||||
onProgress,
|
||||
)
|
||||
|
||||
private suspend fun executePreferredChain(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit,
|
||||
): Uri {
|
||||
check(target.completion.available) { "WDTT Plus не выдал разрешение на получение." }
|
||||
var callback = ActiveCallback(CompletableDeferred())
|
||||
var closeModernWindow: (() -> Unit)? = null
|
||||
synchronized(callbackLock) {
|
||||
check(activeCallback == null) { "Другое получение уже выполняется." }
|
||||
activeCallback = callback
|
||||
}
|
||||
try {
|
||||
savePending(activity, PendingCompletion(target.completion, deviceId))
|
||||
val modernResult = try {
|
||||
runModernContainer(
|
||||
activity = activity,
|
||||
target = target,
|
||||
deviceId = deviceId,
|
||||
hasCompleteLocalValues = hasCompleteLocalValues,
|
||||
onProgress = onProgress,
|
||||
callback = callback,
|
||||
retainFallbackWindow = { closeModernWindow = it },
|
||||
)
|
||||
} catch (_: ModernVkSafeFallbackException) {
|
||||
noteVkEvent("Основной способ недоступен до создания ссылок. Открываю резервный способ внутри приложения.")
|
||||
progress(onProgress, "Открываю резервный способ внутри приложения…")
|
||||
null
|
||||
}
|
||||
if (modernResult != null) return modernResult
|
||||
|
||||
callback = replaceCallback(callback)
|
||||
val native = nativeContinuationOrNull()
|
||||
if (native != null) {
|
||||
try {
|
||||
return native.execute(
|
||||
activity,
|
||||
target,
|
||||
deviceId,
|
||||
hasCompleteLocalValues,
|
||||
onProgress,
|
||||
).also { markReadyDocument(activity, it) }
|
||||
} catch (_: LocalContinuationSafeFallbackException) {
|
||||
noteVkEvent("Встроенный резервный способ не подошёл до создания ссылок. Открываю ВК в браузере.")
|
||||
progress(onProgress, "Открываю резервный способ в браузере…")
|
||||
}
|
||||
}
|
||||
callback = replaceCallback(callback)
|
||||
return runBrowserFallback(activity, target, deviceId, onProgress, callback)
|
||||
} finally {
|
||||
closeModernWindow?.invoke()
|
||||
synchronized(callbackLock) {
|
||||
if (activeCallback === callback) activeCallback = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun runModernContainer(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
hasCompleteLocalValues: Boolean,
|
||||
onProgress: (String) -> Unit,
|
||||
callback: ActiveCallback,
|
||||
retainFallbackWindow: (() -> Unit) -> Unit,
|
||||
): Uri {
|
||||
val embedded = target.embedded ?: throw ModernVkSafeFallbackException()
|
||||
val profile = target.localProfile ?: throw IllegalStateException("Не указан профиль для входа.")
|
||||
ProfileWebSessionScope.requireValid(profile)
|
||||
if (!modernContainerSupported(activity, profile.index)) throw ModernVkSafeFallbackException()
|
||||
val session = UUID.randomUUID().toString()
|
||||
var directRouteLease: TemporaryDirectRouteLease? = null
|
||||
var completedSuccessfully = false
|
||||
var handingOff = false
|
||||
val closeWindow = {
|
||||
activity.sendBroadcast(Intent(MODERN_FINISH_ACTION).apply {
|
||||
setPackage(activity.packageName)
|
||||
putExtra("session", session)
|
||||
putExtra("success", completedSuccessfully)
|
||||
})
|
||||
}
|
||||
try {
|
||||
progress(onProgress, "Открываю получение ВК-хешей внутри приложения…")
|
||||
directRouteLease = TemporaryDirectRouteLease.acquire(
|
||||
context = activity,
|
||||
domains = DIRECT_VK_DOMAINS,
|
||||
)
|
||||
val receiver = object : ResultReceiver(Handler(Looper.getMainLooper())) {
|
||||
override fun onReceiveResult(code: Int, data: Bundle?) {
|
||||
when (code) {
|
||||
MODERN_RESULT_LOG -> {
|
||||
modernLogPresentation(data?.getString("message").orEmpty())
|
||||
?.let(::noteVkEvent)
|
||||
}
|
||||
MODERN_RESULT_CANCEL -> callback.result.complete(null)
|
||||
MODERN_RESULT_SAFE_FALLBACK -> callback.result.completeExceptionally(
|
||||
ModernVkSafeFallbackException(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
withContext(Dispatchers.Main.immediate) {
|
||||
activity.startActivity(Intent().apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
setClassName(activity, ProfileWebSessionScope.modernActivity(profile.index))
|
||||
ProfileWebSessionScope.put(this, profile)
|
||||
putExtra("url", embedded.url)
|
||||
putExtra("login_url", embedded.fallback)
|
||||
putExtra("confirmation_url", embedded.confirmationUrl)
|
||||
putExtra("confirmation_login_url", embedded.confirmationFallback)
|
||||
putExtra("context", embedded.context)
|
||||
putExtra("session", session)
|
||||
putExtra("has_complete_values", hasCompleteLocalValues)
|
||||
putExtra("receiver", receiver)
|
||||
})
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
throw ModernVkSafeFallbackException()
|
||||
}
|
||||
progress(onProgress, "Войдите в ВК при необходимости. Хеши будут получены автоматически…")
|
||||
val documentUri = try {
|
||||
withTimeout(AUTH_TIMEOUT_MS) {
|
||||
awaitCallbackOrCompletion(
|
||||
activity = activity,
|
||||
callback = callback,
|
||||
completion = target.completion,
|
||||
deviceId = deviceId,
|
||||
)
|
||||
}
|
||||
} catch (_: TimeoutCancellationException) {
|
||||
throw IllegalStateException(
|
||||
"Время ожидания ответа ВК истекло. Новые ссылки автоматически не создаются.",
|
||||
)
|
||||
} ?: throw LocalContinuationCancelledException()
|
||||
markReadyDocument(activity, documentUri)
|
||||
completedSuccessfully = true
|
||||
progress(onProgress, "Четыре хеша получены. Обновляю профиль…")
|
||||
return documentUri
|
||||
} catch (fallback: ModernVkSafeFallbackException) {
|
||||
handingOff = true
|
||||
retainFallbackWindow(closeWindow)
|
||||
throw fallback
|
||||
} finally {
|
||||
if (!handingOff) closeWindow()
|
||||
directRouteLease?.release()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun runBrowserFallback(
|
||||
activity: MainActivity,
|
||||
target: RemoteLaunchTarget,
|
||||
deviceId: String,
|
||||
onProgress: (String) -> Unit,
|
||||
callback: ActiveCallback,
|
||||
): Uri {
|
||||
var directRouteLease: TemporaryDirectRouteLease? = null
|
||||
try {
|
||||
progress(onProgress, "Открываю ВК в браузере…")
|
||||
directRouteLease = TemporaryDirectRouteLease.acquire(
|
||||
context = activity,
|
||||
domains = DIRECT_VK_DOMAINS,
|
||||
)
|
||||
val launchUri = Uri.parse(RemoteContinuationLauncher.authTabLaunchUrl(target))
|
||||
withContext(Dispatchers.Main.immediate) {
|
||||
activity.launchLocalContinuation(launchUri)
|
||||
}
|
||||
val callbackUri = try {
|
||||
withTimeout(AUTH_TIMEOUT_MS) {
|
||||
awaitCallbackOrCompletion(
|
||||
activity = activity,
|
||||
callback = callback,
|
||||
completion = target.completion,
|
||||
deviceId = deviceId,
|
||||
)
|
||||
}
|
||||
} catch (_: TimeoutCancellationException) {
|
||||
throw IllegalStateException("Время ожидания ответа ВК истекло.")
|
||||
} ?: throw LocalContinuationCancelledException()
|
||||
if (RemoteContinuationLauncher.isCancellationCallback(callbackUri)) {
|
||||
throw LocalContinuationCancelledException()
|
||||
}
|
||||
val documentUri = RemoteDocumentGateway.extractLink(callbackUri)?.let { callbackUri }
|
||||
?: RemoteContinuationLauncher.callbackDocumentUri(callbackUri)
|
||||
?: throw IllegalStateException(
|
||||
"WDTT Plus получил повреждённый результат автоматической настройки.",
|
||||
)
|
||||
markReadyDocument(activity, documentUri)
|
||||
progress(onProgress, "Хеши получены. Обновляю профиль…")
|
||||
return documentUri
|
||||
} finally {
|
||||
directRouteLease?.release()
|
||||
}
|
||||
}
|
||||
|
||||
private fun replaceCallback(previous: ActiveCallback): ActiveCallback {
|
||||
val replacement = ActiveCallback(CompletableDeferred())
|
||||
synchronized(callbackLock) {
|
||||
check(activeCallback === previous) { "Состояние получения изменилось." }
|
||||
activeCallback = replacement
|
||||
}
|
||||
return replacement
|
||||
}
|
||||
|
||||
private fun nativeContinuationOrNull(): LocalContinuationExtension? = try {
|
||||
Class.forName("com.wdtt.plus.vk.NativeVkContinuation")
|
||||
.getField("INSTANCE").get(null) as LocalContinuationExtension
|
||||
} catch (_: ReflectiveOperationException) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun modernContainerSupported(activity: MainActivity, profileIndex: Int): Boolean {
|
||||
if (!experimentalAvailable) return false
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
if (runCatching { WebView.getCurrentWebViewPackage() }.getOrNull() == null) return false
|
||||
}
|
||||
return runCatching {
|
||||
activity.packageManager.getActivityInfo(
|
||||
android.content.ComponentName(activity, ProfileWebSessionScope.modernActivity(profileIndex)),
|
||||
0,
|
||||
)
|
||||
}.isSuccess
|
||||
}
|
||||
|
||||
private fun modernLogPresentation(raw: String): String? {
|
||||
val message = raw.trim()
|
||||
return when {
|
||||
message == "CAPTCHA / AUTOMATIC" -> "ВК запросил проверку. Выполняется одна автоматическая попытка."
|
||||
message == "CAPTCHA / MANUAL" -> "Пройдите проверку ВК вручную в открытом окне."
|
||||
message == "CAPTCHA / ERROR" -> "Не удалось пройти проверку ВК автоматически. Ошибка показана в окне проверки."
|
||||
message == "CAPTCHA / IDLE" -> "Окно проверки ВК закрыто. Продолжаю действие."
|
||||
message == "CAPTCHA / TIMEOUT" -> "Время ожидания проверки ВК истекло. Повторные запросы не отправляются."
|
||||
message.startsWith("OPEN /") -> "Открыто получение ВК-хешей внутри приложения."
|
||||
message.startsWith("MOBILE_AUTH_COMPLETE /") -> "Проверяю сессию ВК после мобильного входа."
|
||||
message.startsWith("REPLACE_CONFIRMED") -> "Подтверждена замена четырёх ВК-хешей."
|
||||
message.startsWith("BRIDGE / AUTO_READY /") -> "ВК готов к автоматическому получению хешей."
|
||||
message.startsWith("BRIDGE / INIT_WAIT /") -> "Подключаюсь к ВК для получения хешей."
|
||||
message.startsWith("BRIDGE / SESSION_WAIT /") -> "Проверяю сохранённый вход в ВК."
|
||||
message.startsWith("BRIDGE / PROFILE_WAIT /") -> "Подтверждаю аккаунт ВК."
|
||||
message.startsWith("BRIDGE / AUTH_REQUEST /") ->
|
||||
"ВК запросил подтверждение доступа для создания ссылок."
|
||||
message.startsWith("BRIDGE / AUTH_READY /") ->
|
||||
"Доступ ВК подтверждён. Начинаю получение хешей."
|
||||
message.startsWith("BRIDGE_REOPEN /") ->
|
||||
"После входа заново открываю получение ВК-хешей."
|
||||
message.startsWith("BRIDGE / CLAIM_WAIT /") ->
|
||||
"Завершаю вход в ВК и подготавливаю получение хешей."
|
||||
message.startsWith("BRIDGE / CLAIM_READY /") ->
|
||||
"Получение ВК-хешей подготовлено."
|
||||
message.startsWith("BRIDGE / AUTH_FAILED /") ->
|
||||
"Доступ ВК не подтверждён. Перехожу к резервному способу."
|
||||
message.startsWith("BRIDGE / CALL_SENT_") -> {
|
||||
val number = message.substringAfter("CALL_SENT_").substringBefore('/').trim()
|
||||
"Создаю ссылку ВК $number из 4."
|
||||
}
|
||||
message.startsWith("BRIDGE / CALL_HASH_") -> {
|
||||
val count = message.substringAfterLast('/').trim()
|
||||
"Получено ВК-хешей: $count из 4."
|
||||
}
|
||||
message.startsWith("BRIDGE / CALL_TIMEOUT_") ->
|
||||
"ВК не ответил вовремя. Автоматический повтор отключён."
|
||||
message.startsWith("BRIDGE / CALL_FAILED_") ->
|
||||
"ВК не создал ссылку. Автоматический повтор отключён."
|
||||
message.startsWith("BRIDGE / CALL_INVALID_") ||
|
||||
message.startsWith("BRIDGE / CALL_EMPTY_") ->
|
||||
"ВК не вернул ссылку звонка. Автоматический повтор отключён."
|
||||
message.startsWith("BRIDGE / PREP_FAILED /") ->
|
||||
"Не удалось завершить подготовку получения ВК-хешей."
|
||||
message.startsWith("BRIDGE / FLOW_FAILED /") ->
|
||||
"Получение остановлено без повторного создания ссылок."
|
||||
message.startsWith("BRIDGE / DELIVER_WAIT /") ->
|
||||
"Сохраняю четыре ВК-хеша в профиле."
|
||||
message.startsWith("BRIDGE / DELIVER_FAILED /") ->
|
||||
"Ссылки созданы, но передача результата не завершена. Повторяется только сохранение."
|
||||
message.startsWith("LOGOUT / COMPLETE") -> "Выполнен выход из ВК."
|
||||
message.startsWith("LOGOUT / FAILED") -> "Не удалось полностью выйти из ВК. Получение остановлено; повторите выход."
|
||||
message.startsWith("COMPLETE /") -> "Получены четыре ВК-хеша."
|
||||
message.startsWith("CLOSE /") -> "Получение ВК-хешей закрыто."
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun noteVkEvent(message: String) {
|
||||
com.wdtt.plus.TunnelManager.noteSystemLifecycleEvent(
|
||||
"vk_hashes_${System.currentTimeMillis()}",
|
||||
"[ВК] $message",
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun recoverPending(activity: MainActivity): Uri? {
|
||||
synchronized(callbackLock) {
|
||||
if (activeCallback != null || recoveryInProgress) return null
|
||||
recoveryInProgress = true
|
||||
}
|
||||
try {
|
||||
val pending = loadPending(activity) ?: return null
|
||||
if (pending.completion.expiresAtSeconds <= nowSeconds()) {
|
||||
clearPending(activity)
|
||||
return null
|
||||
}
|
||||
if (pending.documentUrl.isNotBlank()) {
|
||||
return Uri.parse(pending.documentUrl)
|
||||
}
|
||||
val native = try {
|
||||
Class.forName("com.wdtt.plus.vk.NativeVkContinuation")
|
||||
.getField("INSTANCE").get(null) as LocalContinuationExtension
|
||||
} catch (_: ClassNotFoundException) { null }
|
||||
native?.recoverPending(activity)?.let { recovered ->
|
||||
markReadyDocument(activity, recovered)
|
||||
return recovered
|
||||
}
|
||||
return when (
|
||||
val status = runCatching {
|
||||
RemoteContinuationLauncher.checkCompletion(
|
||||
context = activity,
|
||||
completion = pending.completion,
|
||||
device = pending.deviceId,
|
||||
)
|
||||
}.getOrNull()
|
||||
) {
|
||||
is RemoteActionCompletionState.Ready -> {
|
||||
Uri.parse(status.document.url).also { markReadyDocument(activity, it) }
|
||||
}
|
||||
RemoteActionCompletionState.Unavailable -> {
|
||||
clearPending(activity)
|
||||
null
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
} finally {
|
||||
synchronized(callbackLock) { recoveryInProgress = false }
|
||||
}
|
||||
}
|
||||
|
||||
override fun acknowledgeDocument(activity: MainActivity, uri: Uri) {
|
||||
val context = activity.applicationContext
|
||||
val delivered = RemoteDocumentGateway.extractLink(uri)?.url ?: return
|
||||
val pending = loadPending(context) ?: return
|
||||
if (pending.documentUrl == delivered) {
|
||||
clearPending(context)
|
||||
val native = try {
|
||||
Class.forName("com.wdtt.plus.vk.NativeVkContinuation")
|
||||
.getField("INSTANCE").get(null) as LocalContinuationExtension
|
||||
} catch (_: ClassNotFoundException) { null }
|
||||
native?.acknowledgeDocument(activity, uri)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun awaitCallbackOrCompletion(
|
||||
activity: MainActivity,
|
||||
callback: ActiveCallback,
|
||||
completion: RemoteActionCompletion,
|
||||
deviceId: String,
|
||||
): Uri? {
|
||||
if (!completion.available) return callback.result.await()
|
||||
return coroutineScope {
|
||||
val polling = async(Dispatchers.IO) {
|
||||
delay(INITIAL_POLL_DELAY_MS)
|
||||
var attempt = 0
|
||||
while (isActive && completion.expiresAtSeconds > nowSeconds()) {
|
||||
when (
|
||||
val status = runCatching {
|
||||
RemoteContinuationLauncher.checkCompletion(
|
||||
context = activity,
|
||||
completion = completion,
|
||||
device = deviceId,
|
||||
)
|
||||
}.getOrNull()
|
||||
) {
|
||||
is RemoteActionCompletionState.Ready ->
|
||||
return@async Uri.parse(status.document.url)
|
||||
RemoteActionCompletionState.Unavailable -> return@async null
|
||||
else -> Unit
|
||||
}
|
||||
attempt++
|
||||
delay(if (attempt < FAST_POLL_ATTEMPTS) FAST_POLL_MS else SLOW_POLL_MS)
|
||||
}
|
||||
null
|
||||
}
|
||||
try {
|
||||
select {
|
||||
callback.result.onAwait { it }
|
||||
polling.onAwait { recovered ->
|
||||
recovered?.also { markReadyDocument(activity, it) }
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
polling.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isAcceptedCallback(uri: Uri): Boolean =
|
||||
RemoteContinuationLauncher.isCancellationCallback(uri) ||
|
||||
RemoteContinuationLauncher.callbackDocumentUri(uri) != null
|
||||
|
||||
private fun savePending(context: Context, pending: PendingCompletion) {
|
||||
val plain = JSONObject()
|
||||
.put("url", pending.completion.url)
|
||||
.put("key", pending.completion.key)
|
||||
.put("expires", pending.completion.expiresAtSeconds)
|
||||
.put("device", pending.deviceId)
|
||||
.put("document", pending.documentUrl)
|
||||
.toString()
|
||||
val encrypted = SecureStringStore(context).encrypt(plain)
|
||||
context.applicationContext
|
||||
.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString(PENDING_KEY, encrypted)
|
||||
.apply()
|
||||
}
|
||||
|
||||
private fun loadPending(context: Context): PendingCompletion? {
|
||||
val encrypted = context.applicationContext
|
||||
.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
|
||||
.getString(PENDING_KEY, null)
|
||||
?: return null
|
||||
val plain = SecureStringStore(context).decrypt(encrypted) ?: run {
|
||||
clearPending(context)
|
||||
return null
|
||||
}
|
||||
return runCatching {
|
||||
val root = JSONObject(plain)
|
||||
val completion = RemoteActionCompletion(
|
||||
available = true,
|
||||
url = root.getString("url"),
|
||||
key = root.getString("key"),
|
||||
expiresAtSeconds = root.getLong("expires"),
|
||||
)
|
||||
val device = root.getString("device")
|
||||
check(completion.url.startsWith("https://"))
|
||||
check(completion.key.length in 24..256)
|
||||
check(device.length in 8..128)
|
||||
PendingCompletion(
|
||||
completion = completion,
|
||||
deviceId = device,
|
||||
documentUrl = root.optString("document"),
|
||||
)
|
||||
}.getOrElse {
|
||||
clearPending(context)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun markReadyDocument(context: Context, uri: Uri) {
|
||||
val document = RemoteDocumentGateway.extractLink(uri)?.url ?: return
|
||||
val pending = loadPending(context) ?: return
|
||||
savePending(context, pending.copy(documentUrl = document))
|
||||
}
|
||||
|
||||
private fun clearPending(context: Context) {
|
||||
context.applicationContext
|
||||
.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.remove(PENDING_KEY)
|
||||
.apply()
|
||||
}
|
||||
|
||||
private suspend fun progress(onProgress: (String) -> Unit, message: String) {
|
||||
withContext(Dispatchers.Main.immediate) { onProgress(message) }
|
||||
}
|
||||
|
||||
private fun nowSeconds(): Long = System.currentTimeMillis() / 1000L
|
||||
|
||||
private const val AUTH_TIMEOUT_MS = 15 * 60 * 1000L
|
||||
private const val INITIAL_POLL_DELAY_MS = 4_000L
|
||||
private const val FAST_POLL_MS = 4_000L
|
||||
private const val SLOW_POLL_MS = 10_000L
|
||||
private const val FAST_POLL_ATTEMPTS = 15
|
||||
private const val PREFERENCES = "wdtt_local_continuation"
|
||||
private const val PENDING_KEY = "pending_completion"
|
||||
private const val MODERN_ACTIVITY_CLASS = "com.wdtt.plus.vk.ModernVkContainerActivity"
|
||||
private const val MODERN_FINISH_ACTION = "com.wdtt.plus.vk.MODERN_VK_FINISH"
|
||||
private const val MODERN_RESULT_CANCEL = 0
|
||||
private const val MODERN_RESULT_LOG = 2
|
||||
private const val MODERN_RESULT_SAFE_FALLBACK = 3
|
||||
private val DIRECT_VK_DOMAINS = setOf(
|
||||
"vk.ru",
|
||||
"m.vk.ru",
|
||||
"id.vk.ru",
|
||||
"login.vk.ru",
|
||||
"api.vk.ru",
|
||||
"api.vk.com",
|
||||
"vk.com",
|
||||
"m.vk.com",
|
||||
"id.vk.com",
|
||||
"login.vk.com",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.net.Network
|
||||
import java.net.Proxy
|
||||
import java.util.concurrent.TimeUnit
|
||||
import okhttp3.ConnectionPool
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import org.json.JSONObject
|
||||
|
||||
internal class VkHttpFailure(val status: Int) : Exception("HTTP $status")
|
||||
|
||||
internal object VkHttp {
|
||||
fun builder(): OkHttpClient.Builder = OkHttpClient.Builder()
|
||||
.retryOnConnectionFailure(false)
|
||||
.followRedirects(false).followSslRedirects(false)
|
||||
// OkHttp can otherwise follow a 503 + Retry-After: 0 even with connection retries off.
|
||||
.addNetworkInterceptor { chain ->
|
||||
val response = chain.proceed(chain.request())
|
||||
if (!response.isSuccessful) {
|
||||
val code = response.code
|
||||
response.close()
|
||||
throw VkHttpFailure(code)
|
||||
}
|
||||
response
|
||||
}
|
||||
.proxy(Proxy.NO_PROXY)
|
||||
.connectionPool(ConnectionPool(0, 1, TimeUnit.SECONDS))
|
||||
.connectTimeout(12, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS)
|
||||
.callTimeout(35, TimeUnit.SECONDS)
|
||||
|
||||
fun client(network: Network): OkHttpClient = builder()
|
||||
.socketFactory(network.socketFactory)
|
||||
.dns(object : okhttp3.Dns {
|
||||
override fun lookup(hostname: String): List<java.net.InetAddress> =
|
||||
network.getAllByName(hostname).toList()
|
||||
})
|
||||
.build()
|
||||
|
||||
/** Check permission to create a network-bound socket without connecting anywhere. */
|
||||
fun checkSocketAccess(client: OkHttpClient) {
|
||||
client.socketFactory.createSocket().use { socket ->
|
||||
check(!socket.isConnected) { "Socket preflight must not connect." }
|
||||
}
|
||||
}
|
||||
|
||||
fun post(client: OkHttpClient, endpoint: String, fields: Map<String, String>): JSONObject {
|
||||
require(endpoint in setOf(VkApiProtocol.START_ENDPOINT, VkApiProtocol.USER_ENDPOINT))
|
||||
return request(client, endpoint, fields)
|
||||
}
|
||||
|
||||
// Also exercised against a local fake server. No logging, interceptors or generic app proxy.
|
||||
internal fun request(client: OkHttpClient, endpoint: String, fields: Map<String, String>): JSONObject {
|
||||
val body = FormBody.Builder().apply { fields.forEach { (k, v) -> add(k, v) } }.build()
|
||||
val request = Request.Builder().url(endpoint).post(body)
|
||||
.header("Connection", "close").header("Cache-Control", "no-store").build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) throw VkHttpFailure(response.code)
|
||||
val bytes = response.body?.byteStream()?.use { it.readBytesBounded() }
|
||||
?: throw IllegalStateException("Empty response")
|
||||
return JSONObject(bytes.toString(Charsets.UTF_8))
|
||||
}
|
||||
}
|
||||
|
||||
private fun java.io.InputStream.readBytesBounded(): ByteArray {
|
||||
val result = java.io.ByteArrayOutputStream()
|
||||
val buffer = ByteArray(4096)
|
||||
while (true) {
|
||||
val size = read(buffer)
|
||||
if (size < 0) return result.toByteArray()
|
||||
require(result.size() + size <= 65_536)
|
||||
result.write(buffer, 0, size)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.webkit.WebView
|
||||
import androidx.webkit.JavaScriptReplyProxy
|
||||
import androidx.webkit.ScriptHandler
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import org.json.JSONObject
|
||||
|
||||
/** One observer per existing profile WebView. No new cookie jar or network binding. */
|
||||
internal class VkInPlaceCaptcha(
|
||||
private val view: WebView,
|
||||
private val foreground: () -> Boolean,
|
||||
private val apiBridgeEnabled: Boolean = false,
|
||||
private val changed: (VkCaptchaPolicy.State) -> Unit,
|
||||
) {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val policy = VkCaptchaPolicy()
|
||||
private val replies = mutableMapOf<String, Pair<Int, JavaScriptReplyProxy>>()
|
||||
private var runtime: JavaScriptReplyProxy? = null
|
||||
private var script: ScriptHandler? = null
|
||||
private var proofScript: ScriptHandler? = null
|
||||
private var apiUrl = ""
|
||||
private var apiNonce = ""
|
||||
private var apiReply: JavaScriptReplyProxy? = null
|
||||
private var apiProof: String? = null
|
||||
private var closed = false
|
||||
private var wasForeground = false
|
||||
private var resumedAt = 0L
|
||||
private var previous = VkCaptchaPolicy.State.IDLE
|
||||
val active get() = policy.active || apiNonce.isNotEmpty()
|
||||
var supported = false
|
||||
private set
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (closed) return
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val visible = foreground()
|
||||
if (visible && !wasForeground) resumedAt = now
|
||||
wasForeground = visible
|
||||
// A background renderer may throttle heartbeat JS. Do not hide its
|
||||
// known challenge or enter fallback before it can report on resume.
|
||||
if (visible && now - resumedAt >= 3500) policy.refresh(now)
|
||||
publish()
|
||||
handler.postDelayed(this, 500)
|
||||
}
|
||||
}
|
||||
init {
|
||||
if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) &&
|
||||
WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
|
||||
runCatching {
|
||||
val origins = VkCaptchaPolicy.origins + "https://wdttplus.ru"
|
||||
WebViewCompat.addWebMessageListener(view, VkCaptchaScript.CHANNEL, origins) { source, message, origin, _, reply ->
|
||||
if (closed || source !== view) return@addWebMessageListener
|
||||
val raw = message.data.orEmpty()
|
||||
if (raw.length > 17000) return@addWebMessageListener
|
||||
val data = runCatching { JSONObject(raw) }.getOrNull() ?: return@addWebMessageListener
|
||||
if (origin.toString() == "https://wdttplus.ru") {
|
||||
when (data.optString("state")) {
|
||||
"runtime" -> { runtime = reply; publish() }
|
||||
"api_begin" -> {
|
||||
val nonce = data.optString("nonce")
|
||||
val url = data.optString("url")
|
||||
if (apiBridgeEnabled && apiNonce.isEmpty() && nonce.matches(Regex("[A-Za-z0-9_-]{16,80}")) &&
|
||||
url.length <= 16384 && VkCaptchaPolicy.captchaPage(url) && foreground()) {
|
||||
apiUrl = url; apiNonce = nonce; apiReply = reply
|
||||
send(reply, JSONObject().put("api", "ready").put("nonce", nonce))
|
||||
publish()
|
||||
}
|
||||
}
|
||||
"api_end" -> if (data.optString("nonce") == apiNonce) {
|
||||
apiUrl = ""; apiNonce = ""; apiReply = null; apiProof = null; publish()
|
||||
}
|
||||
}
|
||||
return@addWebMessageListener
|
||||
}
|
||||
if (raw.length > 256) return@addWebMessageListener
|
||||
if (!VkCaptchaPolicy.trustedOrigin(origin.toString())) return@addWebMessageListener
|
||||
val frame = data.optString("frame")
|
||||
val generation = data.optInt("generation", -1)
|
||||
val action = policy.update(frame, generation, data.optString("state"), SystemClock.elapsedRealtime(), foreground())
|
||||
if (frame.matches(Regex("[a-z0-9]{1,64}")) && generation in 0..128 && replies.size < 32) {
|
||||
replies[frame] = generation to reply
|
||||
}
|
||||
publish() // Reveal the original page before attempting its exact checkbox.
|
||||
if (action != null) send(reply, JSONObject().put("frame", frame).put("generation", generation).put("action", action))
|
||||
}
|
||||
script = WebViewCompat.addDocumentStartJavaScript(view, VkCaptchaScript.source, origins)
|
||||
if (apiBridgeEnabled) {
|
||||
WebViewCompat.addWebMessageListener(view, "WDTTApiCaptchaResult", VkCaptchaPolicy.origins) { source, message, origin, _, reply ->
|
||||
if (closed || source !== view || apiNonce.isEmpty() || !VkCaptchaPolicy.trustedOrigin(origin.toString())) return@addWebMessageListener
|
||||
val raw = message.data.orEmpty()
|
||||
if (raw.length > 17000) return@addWebMessageListener
|
||||
val data = runCatching { JSONObject(raw) }.getOrNull() ?: return@addWebMessageListener
|
||||
if (data.optString("page") == apiUrl) {
|
||||
send(reply, JSONObject().put("observe", apiNonce))
|
||||
} else if (data.optString("nonce") == apiNonce && VkApiCaptcha.validProof(data.optString("proof"))) {
|
||||
if (apiProof == null && apiReply != null) apiProof = data.optString("proof")
|
||||
publish() // Forward once, and only while the user is in this window.
|
||||
}
|
||||
}
|
||||
proofScript = WebViewCompat.addDocumentStartJavaScript(view, VkApiCaptcha.completionScript, VkCaptchaPolicy.origins)
|
||||
}
|
||||
supported = true
|
||||
handler.post(tick)
|
||||
}.onFailure { close() }
|
||||
}
|
||||
}
|
||||
fun userInteraction() {
|
||||
if (closed || !active) return
|
||||
policy.userInteraction(SystemClock.elapsedRealtime())
|
||||
replies.forEach { (frame, value) -> send(value.second, JSONObject().put("frame", frame)
|
||||
.put("generation", value.first).put("action", "manual")) }
|
||||
publish()
|
||||
}
|
||||
private fun publish() {
|
||||
runtime?.let { send(it, JSONObject().put("pending", active)) }
|
||||
if (foreground() && apiNonce.isNotEmpty()) apiProof?.let { proof ->
|
||||
apiReply?.let { send(it, JSONObject().put("api", "solved").put("nonce", apiNonce).put("proof", proof)) }
|
||||
apiReply = null; apiProof = null
|
||||
}
|
||||
val state = if (policy.active) policy.state else if (apiNonce.isNotEmpty()) VkCaptchaPolicy.State.MANUAL else VkCaptchaPolicy.State.IDLE
|
||||
if (previous != state) { previous = state; changed(state) }
|
||||
}
|
||||
private fun send(reply: JavaScriptReplyProxy, data: JSONObject) {
|
||||
runCatching { reply.postMessage(data.toString()) }
|
||||
}
|
||||
fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
handler.removeCallbacks(tick)
|
||||
runCatching { script?.remove() }; script = null
|
||||
runCatching { proofScript?.remove() }; proofScript = null
|
||||
if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
|
||||
runCatching { WebViewCompat.removeWebMessageListener(view, VkCaptchaScript.CHANNEL) }
|
||||
if (apiBridgeEnabled) runCatching { WebViewCompat.removeWebMessageListener(view, "WDTTApiCaptchaResult") }
|
||||
}
|
||||
replies.clear(); runtime = null; apiReply = null; apiProof = null; apiUrl = ""; apiNonce = ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.content.Context
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.WebStorage
|
||||
import androidx.webkit.WebStorageCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import com.wdtt.plus.LocalContinuationProfile
|
||||
|
||||
/** Only engines of the SAME local profile share a session; each slot has its own process. */
|
||||
internal class VkLocalSession(private val storage: Storage) {
|
||||
interface Storage {
|
||||
val remembered: Boolean
|
||||
val logoutPending: Boolean
|
||||
val owner: String
|
||||
fun remember()
|
||||
fun beginLogout()
|
||||
fun removeNativeToken()
|
||||
fun finishLogout()
|
||||
fun saveOwner(identity: String)
|
||||
}
|
||||
|
||||
val logoutPending get() = storage.logoutPending
|
||||
// Only a routing hint. VK and the backend still verify the current account.
|
||||
val remembered get() = storage.remembered && !logoutPending
|
||||
|
||||
fun observeBridgeStage(stage: String) {
|
||||
if (stage in setOf("AUTH_REQUEST", "AUTH_READY", "AUTO_READY")) rememberAuthenticatedWebSession()
|
||||
}
|
||||
|
||||
fun rememberAuthenticatedWebSession() {
|
||||
if (!logoutPending) storage.remember()
|
||||
}
|
||||
|
||||
suspend fun logout(clearWebData: suspend () -> Unit) {
|
||||
// Persist a barrier BEFORE clearing separate token/cookie stores. A killed
|
||||
// Activity or failed cookie callback must not resurrect the other engine's account.
|
||||
storage.beginLogout()
|
||||
storage.removeNativeToken()
|
||||
clearWebData()
|
||||
storage.finishLogout()
|
||||
}
|
||||
|
||||
suspend fun finishPendingLogout(clearWebData: suspend () -> Unit) {
|
||||
if (logoutPending) logout(clearWebData)
|
||||
}
|
||||
|
||||
suspend fun prepareProfile(identity: String, clearWebData: suspend () -> Unit) {
|
||||
require(identity.matches(Regex("[a-f0-9]{64}")))
|
||||
// A reset/replaced slot cannot inherit its previous profile's account.
|
||||
// Commit the new owner only AFTER clearing all of the slot's old web data.
|
||||
if (storage.owner != identity) {
|
||||
logout(clearWebData)
|
||||
storage.saveOwner(identity)
|
||||
} else {
|
||||
finishPendingLogout(clearWebData)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun nativeTokenPreferences(context: Context, profile: LocalContinuationProfile) =
|
||||
context.getSharedPreferences("native-vk-session-profile-${profile.index}", Context.MODE_PRIVATE)
|
||||
|
||||
fun forContext(context: Context, profile: LocalContinuationProfile): VkLocalSession {
|
||||
ProfileWebSessionScope.requireValid(profile)
|
||||
val session = context.getSharedPreferences("vk-web-session-profile-${profile.index}", Context.MODE_PRIVATE)
|
||||
val native = nativeTokenPreferences(context, profile)
|
||||
return VkLocalSession(object : Storage {
|
||||
override val remembered get() = session.getBoolean("has_vk_web_session", false)
|
||||
override val logoutPending get() = session.getBoolean("logout_pending", false)
|
||||
override val owner get() = session.getString("owner", "").orEmpty()
|
||||
override fun remember() {
|
||||
session.edit().putBoolean("has_vk_web_session", true).apply()
|
||||
}
|
||||
override fun beginLogout() {
|
||||
check(session.edit().putBoolean("logout_pending", true)
|
||||
.remove("has_vk_web_session").commit()) { "SESSION_REMOVE" }
|
||||
}
|
||||
override fun removeNativeToken() {
|
||||
// Deliberately preserve the operation ledger, permits and saved results.
|
||||
check(native.edit().remove("token").commit()) { "TOKEN_REMOVE" }
|
||||
}
|
||||
override fun finishLogout() {
|
||||
check(session.edit().remove("logout_pending").commit()) { "SESSION_REMOVE" }
|
||||
}
|
||||
override fun saveOwner(identity: String) {
|
||||
check(session.edit().putString("owner", identity).commit()) { "SESSION_OWNER" }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
suspend fun clearWebData() {
|
||||
val cleared = CompletableDeferred<Unit>()
|
||||
if (WebViewFeature.isFeatureSupported(WebViewFeature.DELETE_BROWSING_DATA)) {
|
||||
// Includes cookies, HTTP cache and service-worker/JS storage. Await
|
||||
// completion BEFORE allowing another account to open in this slot.
|
||||
WebStorageCompat.deleteBrowsingData(WebStorage.getInstance()) { cleared.complete(Unit) }
|
||||
withTimeout(10_000) { cleared.await() }
|
||||
CookieManager.getInstance().flush()
|
||||
return
|
||||
}
|
||||
// false means the cookie jar was already empty, not an error.
|
||||
CookieManager.getInstance().removeAllCookies { cleared.complete(Unit) }
|
||||
withTimeout(5_000) { cleared.await() }
|
||||
CookieManager.getInstance().flush()
|
||||
WebStorage.getInstance().deleteAllData()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import java.net.URI
|
||||
import java.net.URLDecoder
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** Official Mini App OAuth adapter. No cookie extraction, injected script or third-party identity. */
|
||||
internal object VkOAuthProtocol {
|
||||
const val CLIENT_ID = "54670800"
|
||||
const val REDIRECT = "https://oauth.vk.ru/blank.html"
|
||||
// Local upper bound, not a claim about the provider's token lifetime.
|
||||
private const val MAX_LOCAL_TOKEN_SECONDS = 86_400L
|
||||
|
||||
class AuthAttempt(val state: String) {
|
||||
fun url(): String = "https://oauth.vk.ru/authorize?" + VkApiProtocol.encode(linkedMapOf(
|
||||
"client_id" to CLIENT_ID, "redirect_uri" to REDIRECT,
|
||||
"display" to "mobile", "response_type" to "token", "v" to "5.199", "state" to state,
|
||||
))
|
||||
}
|
||||
|
||||
enum class Rejection { REDIRECT, MALFORMED, MISSING_STATE, STATE_MISMATCH, DENIED }
|
||||
class Rejected(val reason: Rejection) : IllegalArgumentException("OAuth response rejected")
|
||||
|
||||
fun newAttempt(): AuthAttempt = AuthAttempt(VkApiProtocol.newAttempt().state)
|
||||
|
||||
fun isCallback(raw: String): Boolean = runCatching {
|
||||
if (raw.length > 16_384) return false
|
||||
val uri = URI(raw)
|
||||
uri.scheme == "https" && uri.host == "oauth.vk.ru" && uri.rawPath == "/blank.html" &&
|
||||
uri.rawUserInfo == null && uri.port == -1
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** Never allow an access-token redirect to be loaded as a web page, even at a wrong target. */
|
||||
fun containsCredential(raw: String): Boolean = runCatching {
|
||||
val uri = URI(raw)
|
||||
listOf(uri.rawQuery, uri.rawFragment).filterNotNull().any { part ->
|
||||
part.split('&').any {
|
||||
URLDecoder.decode(it.substringBefore('='), "UTF-8") in
|
||||
setOf("access_token", "id_token", "refresh_token")
|
||||
}
|
||||
}
|
||||
}.getOrDefault(true)
|
||||
|
||||
fun blockResource(raw: String, mainFrame: Boolean): Boolean =
|
||||
isCallback(raw) || (mainFrame && containsCredential(raw))
|
||||
|
||||
fun callback(raw: String, expectedState: String, now: Long): VkApiProtocol.Token {
|
||||
if (!isCallback(raw)) throw Rejected(Rejection.REDIRECT)
|
||||
try {
|
||||
require(expectedState.matches(Regex("[A-Za-z0-9_-]{32,128}")))
|
||||
val uri = URI(raw)
|
||||
// Successful implicit OAuth responses belong in the fragment, never the query.
|
||||
require(uri.rawQuery == null)
|
||||
val fields = uniqueFields(uri.rawFragment ?: throw Rejected(Rejection.MALFORMED))
|
||||
val state = fields["state"]?.takeIf { it.isNotEmpty() }
|
||||
?: throw Rejected(Rejection.MISSING_STATE)
|
||||
if (!MessageDigest.isEqual(state.toByteArray(), expectedState.toByteArray())) {
|
||||
throw Rejected(Rejection.STATE_MISMATCH)
|
||||
}
|
||||
if (fields.containsKey("error")) throw Rejected(Rejection.DENIED)
|
||||
require(!fields.containsKey("code") && !fields.containsKey("id_token") && !fields.containsKey("refresh_token"))
|
||||
val value = fields["access_token"].orEmpty()
|
||||
require(value.length in 1..8192 && value.matches(Regex("[A-Za-z0-9._~+/-]+=*")))
|
||||
val userId = fields["user_id"].orEmpty()
|
||||
require(userId.matches(Regex("[1-9][0-9]{0,18}")) && userId.toLong() > 0)
|
||||
val secondsText = fields["expires_in"].orEmpty()
|
||||
require(secondsText.matches(Regex("[0-9]{1,8}")))
|
||||
val seconds = secondsText.toLong()
|
||||
require(seconds in 0..31_536_000)
|
||||
val localSeconds = if (seconds == 0L) MAX_LOCAL_TOKEN_SECONDS
|
||||
else minOf(seconds, MAX_LOCAL_TOKEN_SECONDS)
|
||||
return VkApiProtocol.Token(value, Math.addExact(now, localSeconds * 1000))
|
||||
} catch (error: Rejected) {
|
||||
throw error
|
||||
} catch (_: Exception) {
|
||||
// Do not retain malformed URLs, provider messages or token fragments in exceptions.
|
||||
throw Rejected(Rejection.MALFORMED)
|
||||
}
|
||||
}
|
||||
|
||||
private fun uniqueFields(raw: String): Map<String, String> {
|
||||
val result = mutableMapOf<String, String>()
|
||||
raw.split('&').forEach {
|
||||
val pair = it.split('=', limit = 2)
|
||||
require(pair.size == 2)
|
||||
val key = URLDecoder.decode(pair[0], "UTF-8")
|
||||
require(key.isNotEmpty() && !result.containsKey(key))
|
||||
result[key] = URLDecoder.decode(pair[1], "UTF-8")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun rejectionMessage(error: Rejected): String = when (error.reason) {
|
||||
Rejection.MISSING_STATE -> "VK не вернул state. Ответ входа отклонён; calls.start не отправлялся."
|
||||
Rejection.STATE_MISMATCH -> "Ответ VK относится к другой попытке входа. calls.start не отправлялся."
|
||||
Rejection.DENIED -> "VK не выдал разрешение или вход отменён. calls.start не отправлялся."
|
||||
Rejection.REDIRECT -> "VK вернул разрешение на неожиданный адрес. Ответ отклонён; calls.start не отправлялся."
|
||||
Rejection.MALFORMED -> "Ответ OAuth Mini App не прошёл проверку. calls.start не отправлялся."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
import android.app.Application
|
||||
import android.webkit.WebView
|
||||
import androidx.annotation.Keep
|
||||
import androidx.compose.runtime.Composable
|
||||
import com.wdtt.plus.LocalBuildExtension
|
||||
|
||||
@Keep
|
||||
object VkProcessInitializer : LocalBuildExtension {
|
||||
override fun initializeAuxiliaryProcess(application: Application): Boolean {
|
||||
val process = Application.getProcessName()
|
||||
val profile = (0..2).firstOrNull {
|
||||
process == application.packageName + ProfileWebSessionScope.processSuffix(it)
|
||||
}
|
||||
if (profile == null) return false
|
||||
// Before any WebView/CookieManager access. Other app WebViews cannot read this jar.
|
||||
WebView.setDataDirectorySuffix(ProfileWebSessionScope.webDataSuffix(profile))
|
||||
WebView.setWebContentsDebuggingEnabled(false)
|
||||
// No main-process VPN initialization, workers, backend requests or widget state here.
|
||||
return true
|
||||
}
|
||||
|
||||
@Composable
|
||||
override fun Content() = Unit
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
// Separate manifest processes give Android 9+ and old WebView versions real
|
||||
// cookie/localStorage/IndexedDB/service-worker isolation without copying cookies.
|
||||
class ModernVkProfile0Activity : ModernVkContainerActivity()
|
||||
class ModernVkProfile1Activity : ModernVkContainerActivity()
|
||||
class ModernVkProfile2Activity : ModernVkContainerActivity()
|
||||
class NativeVkProfile0Activity : NativeVkActivity()
|
||||
class NativeVkProfile1Activity : NativeVkActivity()
|
||||
class NativeVkProfile2Activity : NativeVkActivity()
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.wdtt.plus.vk
|
||||
|
||||
/**
|
||||
* Validates the modern VK ID callback before advancing to the Mini App OAuth
|
||||
* context whose token is compatible with VK Calls. No credential from the
|
||||
* first stage is retained or exchanged.
|
||||
*/
|
||||
internal object VkTwoStageLoginProtocol {
|
||||
fun continueWithMiniApp(
|
||||
rawCallback: String,
|
||||
vkIdAttempt: VkApiProtocol.AuthAttempt,
|
||||
): VkOAuthProtocol.AuthAttempt {
|
||||
VkApiProtocol.callback(rawCallback, vkIdAttempt.state)
|
||||
return VkOAuthProtocol.newAttempt()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ConnectionDiagnosticsTest {
|
||||
@Test fun modesHaveUnambiguousDatagramPolicy() {
|
||||
assertEquals("UDP", connectionModeDiagnostic(false).status)
|
||||
assertEquals("TCP/TLS", connectionModeDiagnostic(true).status)
|
||||
assertTrue(connectionModeDiagnostic(true).details.contains("HTTP/3 запрещены"))
|
||||
assertTrue(connectionModeDiagnostic(false).details.contains("пауза", ignoreCase = true))
|
||||
assertTrue(connectionModeDiagnostic(false).details.contains("рабочих UDP-каналов нет"))
|
||||
for (mode in listOf(false, true)) assertTrue(connectionModeDiagnostic(mode).details.contains("восстанавливаются"))
|
||||
}
|
||||
@Test fun eventParserRejectsUnknownAndStaleValues() {
|
||||
assertNull(connectionEventLog("READY 3 tcp", 4))
|
||||
assertNull(connectionEventLog("READY 4 arbitrary-secret", 4))
|
||||
assertNull(connectionEventLog("READY 4 tcp trailing-secret", 4))
|
||||
assertNull(connectionEventLog("UDP_BACKOFF 3", 4))
|
||||
assertEquals("Сервер ответил · TCP ✓", connectionEventLog("READY 4 tcp", 4)?.message)
|
||||
}
|
||||
@Test fun connectionEventsAreNotConfusedWithProxyAutoMode() {
|
||||
for (event in listOf("TRY tls-front", "READY 0 tls-front", "PAUSED limit", "UDP_BACKOFF 0")) {
|
||||
val result = connectionEventLog(event, 0)!!
|
||||
assertFalse(result.message.contains("Авто"))
|
||||
}
|
||||
assertTrue(connectionEventLog("UDP_BACKOFF 0", 0)!!.warning)
|
||||
}
|
||||
@Test fun confirmedTransportsRemainSeparateInAggregatedLogs() {
|
||||
val udp = connectionEventLog("READY 4 udp", 4)!!
|
||||
val tcp = connectionEventLog("READY 4 tcp", 4)!!
|
||||
assertNotEquals(udp.key, tcp.key)
|
||||
assertTrue(udp.message.contains("UDP ✓"))
|
||||
assertTrue(tcp.message.contains("TCP ✓"))
|
||||
assertTrue(connectionEventLog("UDP_PARTIAL 4", 4)!!.message.contains("Остальные UDP-каналы работают"))
|
||||
assertNull(connectionEventLog("UDP_PARTIAL 3", 4))
|
||||
}
|
||||
@Test fun failuresShowStageAndDurationWithoutRawErrorText() {
|
||||
val failure = connectionEventLog("FAILED 4 udp dtls timeout 8002", 4)!!
|
||||
assertTrue(failure.warning)
|
||||
assertTrue(failure.message.contains("защищённое соединение с сервером"))
|
||||
assertTrue(failure.message.contains("8 с"))
|
||||
for (event in listOf(
|
||||
"FAILED 3 udp dtls timeout 8002", "FAILED 4 udp dtls timeout -1",
|
||||
"FAILED 4 udp secret timeout 8002", "FAILED 4 udp dtls secret 8002",
|
||||
"FAILED 4 udp dtls timeout 8002 extra", "FAILED 4 unknown dtls timeout 8002",
|
||||
)) assertNull(connectionEventLog(event, 4))
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class DeviceCompatibilityTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun processExitHistoryKeepsSystemKillVisibleAfterPackageUpdate() {
|
||||
fun systemKillRemainsVisibleWithoutClaimingCurrentRestrictions() {
|
||||
val now = 1_800_000_000_000L
|
||||
val systemKill = ProcessExitRecord(
|
||||
timestampMs = now - 2_000L,
|
||||
@@ -57,15 +57,16 @@ class DeviceCompatibilityTest {
|
||||
manufacturer = "OnePlus",
|
||||
backgroundRestricted = false,
|
||||
batteryOptimizationsIgnored = true,
|
||||
nowMs = now,
|
||||
)
|
||||
|
||||
assertEquals(packageUpdate, history.latest)
|
||||
assertEquals(systemKill, history.latestUnexpected)
|
||||
assertEquals(DeviceCheckSeverity.Warning, item.severity)
|
||||
assertEquals(DeviceCheckSeverity.Info, item.severity)
|
||||
assertTrue(item.details.contains("o-kill(6)"))
|
||||
assertTrue(item.details.contains("более новое штатное событие"))
|
||||
assertTrue(item.details.contains("более новое завершение процесса"))
|
||||
assertTrue(!item.details.contains("private-value-must-not-leak"))
|
||||
assertTrue(item.recommendation.contains("OxygenOS"))
|
||||
assertTrue(item.recommendation.contains("Повторно менять эти разрешения не нужно"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -106,6 +107,64 @@ class DeviceCompatibilityTest {
|
||||
assertTrue(recommendation.contains("автозапуск"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oldCrashIsHistoryWhileRecentCrashAffectsTheConclusion() {
|
||||
val now = 1_800_000_000_000L
|
||||
fun check(age: Long): DeviceCheckItem = processExitHistoryItem(
|
||||
history = processExitHistory(listOf(ProcessExitRecord(
|
||||
timestampMs = now - age,
|
||||
reason = ApplicationExitInfo.REASON_CRASH,
|
||||
)), now),
|
||||
manufacturer = "OnePlus",
|
||||
backgroundRestricted = false,
|
||||
batteryOptimizationsIgnored = true,
|
||||
nowMs = now,
|
||||
)
|
||||
val old = check(2L * 24 * 60 * 60 * 1000)
|
||||
val recent = check(60_000)
|
||||
assertEquals(DeviceCheckSeverity.Info, old.severity)
|
||||
assertTrue(DeviceCompatibilityReport(now, listOf(old)).problemItems.isEmpty())
|
||||
assertEquals(DeviceCheckSeverity.Error, recent.severity)
|
||||
assertTrue(DeviceCompatibilityReport(now, listOf(recent)).hasErrors)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recentSystemExitWithCurrentRestrictionsStillWarns() {
|
||||
val now = 1_800_000_000_000L
|
||||
val item = processExitHistoryItem(
|
||||
history = processExitHistory(listOf(ProcessExitRecord(
|
||||
timestampMs = now - 60_000,
|
||||
reason = ApplicationExitInfo.REASON_OTHER,
|
||||
description = "o-kill(6)",
|
||||
)), now),
|
||||
manufacturer = "OnePlus",
|
||||
backgroundRestricted = true,
|
||||
batteryOptimizationsIgnored = false,
|
||||
nowMs = now,
|
||||
)
|
||||
assertEquals(DeviceCheckSeverity.Warning, item.severity)
|
||||
assertEquals(DeviceCheckAction.BatterySettings, item.action)
|
||||
assertTrue(item.recommendation.contains("ограниченное в фоне"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownVendorExitWithoutReportedRestrictionsDoesNotInventAPermissionProblem() {
|
||||
val now = 1_800_000_000_000L
|
||||
val item = processExitHistoryItem(
|
||||
history = processExitHistory(listOf(ProcessExitRecord(
|
||||
timestampMs = now - 60_000,
|
||||
reason = ApplicationExitInfo.REASON_UNKNOWN,
|
||||
)), now),
|
||||
manufacturer = "OnePlus",
|
||||
backgroundRestricted = null,
|
||||
batteryOptimizationsIgnored = null,
|
||||
nowMs = now,
|
||||
)
|
||||
assertEquals(DeviceCheckSeverity.Info, item.severity)
|
||||
assertEquals(null, item.action)
|
||||
assertTrue(item.recommendation.contains("дополнительных действий не требуется"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sixteenKibPagesAreSupportedByThe64BitRelease() {
|
||||
val item = pageSizeCompatibilityItem(16L * 1024L, processIs64Bit = true)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ProxyStartupErrorTest {
|
||||
@Test
|
||||
fun `native process replacement is serialized with confirmed old process exit`() {
|
||||
val source = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/TunnelManager.kt"),
|
||||
File("src/main/java/com/wdtt/plus/TunnelManager.kt"),
|
||||
).first(File::isFile).readText()
|
||||
|
||||
assertTrue("private val processLifecycleLock = Any()" in source)
|
||||
assertTrue("process = startNativeProcess(pb)" in source)
|
||||
assertTrue("process?.let(::stopNativeProcessLocked)" in source)
|
||||
assertTrue("check(process?.let(::stopNativeProcessLocked) != false)" in source)
|
||||
assertTrue("builder.start().also { process = it }" in source)
|
||||
assertTrue(
|
||||
"proxy ready state must be cleared while an old process is stopping",
|
||||
"if (tunnelModeUsesLocalProxy(activeMode.value))" in source &&
|
||||
"proxyReadyAddresses.value = emptyList()" in source,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `port in use becomes a dedicated connection issue`() {
|
||||
val presentation = proxyErrorPresentation("port_in_use|127.0.0.1:1080")
|
||||
|
||||
assertEquals(ConnectionIssueKind.PROXY_PORT_IN_USE, presentation.issue.kind)
|
||||
assertEquals("Порт прокси уже занят", presentation.issue.title)
|
||||
assertTrue(presentation.issue.action.contains("127.0.0.1:1080 уже занят"))
|
||||
assertTrue(presentation.issue.action.contains("Выберите другой порт"))
|
||||
assertEquals("[ПРОКСИ] Порт занят: 127.0.0.1:1080", presentation.logMessage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `proxy error state never retains planned ready addresses`() {
|
||||
val presentation = proxyErrorPresentation("port_in_use|192.168.1.113:1080")
|
||||
|
||||
assertNull(presentation.readyAddress)
|
||||
assertTrue(presentation.readyAddresses.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generic structured startup error remains readable`() {
|
||||
val presentation = proxyErrorPresentation("startup|ошибка userspace WireGuard")
|
||||
|
||||
assertEquals(ConnectionIssueKind.GENERAL, presentation.issue.kind)
|
||||
assertEquals("Прокси не запустился", presentation.issue.title)
|
||||
assertTrue(presentation.issue.action.contains("ошибка userspace WireGuard"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.CancellationException
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class RemoteDocumentTransportTest {
|
||||
@Test
|
||||
fun `direct response stays authoritative and does not use tunnel`() = runBlocking {
|
||||
var tunnelCalled = false
|
||||
|
||||
val result = requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = { RemoteDocumentHttpResponse(409, "direct") },
|
||||
tunnelRequest = {
|
||||
tunnelCalled = true
|
||||
OpaqueHttpsRelayResult.Success(200, "relay", "")
|
||||
},
|
||||
)
|
||||
|
||||
assertEquals(409, result.status)
|
||||
assertEquals("direct", result.body)
|
||||
assertFalse(tunnelCalled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `transport failure retries once through active tunnel`() = runBlocking {
|
||||
val result = requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = { throw IOException("direct route unavailable") },
|
||||
tunnelRequest = {
|
||||
OpaqueHttpsRelayResult.Success(200, "relay", "")
|
||||
},
|
||||
)
|
||||
|
||||
assertEquals(200, result.status)
|
||||
assertEquals("relay", result.body)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `preferred tunnel avoids blocked physical request`() = runBlocking {
|
||||
var directCalled = false
|
||||
|
||||
val result = requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = {
|
||||
directCalled = true
|
||||
throw IOException("physical network is allowlisted")
|
||||
},
|
||||
tunnelRequest = {
|
||||
OpaqueHttpsRelayResult.Success(200, "relay", "")
|
||||
},
|
||||
preferTunnel = true,
|
||||
)
|
||||
|
||||
assertEquals(200, result.status)
|
||||
assertEquals("relay", result.body)
|
||||
assertFalse(directCalled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `preferred unavailable tunnel falls back to physical request`() = runBlocking {
|
||||
val result = requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = { RemoteDocumentHttpResponse(200, "direct") },
|
||||
tunnelRequest = {
|
||||
OpaqueHttpsRelayResult.Unavailable("tunnel unavailable")
|
||||
},
|
||||
preferTunnel = true,
|
||||
)
|
||||
|
||||
assertEquals(200, result.status)
|
||||
assertEquals("direct", result.body)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unavailable tunnel preserves original transport failure`() {
|
||||
val directError = IOException("direct route unavailable")
|
||||
|
||||
val thrown = assertThrows(IOException::class.java) {
|
||||
runBlocking {
|
||||
requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = { throw directError },
|
||||
tunnelRequest = {
|
||||
OpaqueHttpsRelayResult.Unavailable("tunnel unavailable")
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
assertSame(directError, thrown)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cancelled request never starts tunnel fallback`() {
|
||||
var tunnelCalled = false
|
||||
|
||||
assertThrows(CancellationException::class.java) {
|
||||
runBlocking {
|
||||
requestRemoteDocumentWithTunnelFallback(
|
||||
directRequest = { throw CancellationException("cancelled") },
|
||||
tunnelRequest = {
|
||||
tunnelCalled = true
|
||||
OpaqueHttpsRelayResult.Success(200, "relay", "")
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
assertFalse(tunnelCalled)
|
||||
}
|
||||
}
|
||||
@@ -25,32 +25,12 @@ class RtTurnSniTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun masqueRequiresBothSwitches() {
|
||||
assertFalse(shouldUseRtMasque(rtNetwork = false, rtMasque = false))
|
||||
assertFalse(shouldUseRtMasque(rtNetwork = false, rtMasque = true))
|
||||
assertFalse(shouldUseRtMasque(rtNetwork = true, rtMasque = false))
|
||||
assertTrue(shouldUseRtMasque(rtNetwork = true, rtMasque = true))
|
||||
assertFalse(
|
||||
shouldUseRtMasqueServerBootstrap(
|
||||
rtNetwork = false,
|
||||
rtMasque = true,
|
||||
serverBootstrap = true,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
shouldUseRtMasqueServerBootstrap(
|
||||
rtNetwork = true,
|
||||
rtMasque = false,
|
||||
serverBootstrap = true,
|
||||
)
|
||||
)
|
||||
assertTrue(
|
||||
shouldUseRtMasqueServerBootstrap(
|
||||
rtNetwork = true,
|
||||
rtMasque = true,
|
||||
serverBootstrap = true,
|
||||
)
|
||||
)
|
||||
fun masqueRequiresConsentInEitherConnectionMode() {
|
||||
assertFalse(shouldUseRtMasque(false))
|
||||
assertTrue(shouldUseRtMasque(true))
|
||||
assertFalse(shouldUseRtMasqueServerBootstrap(false, true))
|
||||
assertFalse(shouldUseRtMasqueServerBootstrap(true, false))
|
||||
assertTrue(shouldUseRtMasqueServerBootstrap(true, true))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -282,4 +262,15 @@ class RtTurnSniTest {
|
||||
assertNotNull(params)
|
||||
assertEquals(false, params?.rtMasqueServerBootstrap)
|
||||
}
|
||||
@Test
|
||||
fun masqueLogsRespectNoUdpAndDoNotPromiseForbiddenFallbacks() {
|
||||
val enabled = classifyMasqueLog("[MASQUE] Включён резерв: только HTTP/2; HTTP/3 запрещён режимом TCP/TLS")
|
||||
assertTrue(enabled!!.message.contains("HTTP/3 отключён"))
|
||||
val failure = classifyMasqueLog("[MASQUE] TLS через HTTP/2 не сработал: timeout")
|
||||
assertFalse(failure!!.message.contains("и HTTP/3"))
|
||||
val fallback = classifyMasqueLog("[MASQUE] Прямые TCP/TLS-пути не сработали; пробуем резерв MASQUE")
|
||||
assertFalse(fallback!!.message.contains("РТ"))
|
||||
assertFalse(fallback.message.contains("до попытки UDP"))
|
||||
assertFalse(wrapHandshakeTerminalMessage(true).contains("сеть РТ"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.TimeUnit
|
||||
import com.wdtt.plus.ui.rootCommand
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ServerAdminSudoTest {
|
||||
private val request = "{\"main_password\":\"owner-secret\",\"args\":[\"list\"]}\n"
|
||||
|
||||
@Test
|
||||
fun framedAdminInputSurvivesPasswordPrompt() {
|
||||
val plan = buildAdminRootStdinExecPlan(
|
||||
command = "cat",
|
||||
sudoPassword = "sudo-secret",
|
||||
stdinPayload = request,
|
||||
)
|
||||
|
||||
val inputAfterSudoPassword = plan.stdinPayload.substringAfter('\n')
|
||||
val result = runShell(buildAdminStdinForwardingCommand("cat"), inputAfterSudoPassword)
|
||||
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals(request, result.stdout)
|
||||
assertEquals("", result.stderr)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun framedAdminInputSurvivesCachedOrPasswordlessSudo() {
|
||||
val plan = buildAdminRootStdinExecPlan(
|
||||
command = "cat",
|
||||
sudoPassword = "sudo-secret",
|
||||
stdinPayload = request,
|
||||
)
|
||||
|
||||
val result = runShell(buildAdminStdinForwardingCommand("cat"), plan.stdinPayload)
|
||||
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals(request, result.stdout)
|
||||
assertEquals("", result.stderr)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun framingAlsoHandlesPasswordEqualToPublicStartMarker() {
|
||||
val marker = buildAdminRootStdinExecPlan("cat", "password", request)
|
||||
.stdinPayload
|
||||
.lineSequence()
|
||||
.drop(1)
|
||||
.first()
|
||||
val plan = buildAdminRootStdinExecPlan("cat", marker, request)
|
||||
|
||||
val result = runShell(buildAdminStdinForwardingCommand("cat"), plan.stdinPayload)
|
||||
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals(request, result.stdout)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun adminPlanUsesOneChannelAndKeepsSecretsOutOfCommand() {
|
||||
val plan = buildAdminRootStdinExecPlan(
|
||||
command = "/usr/local/bin/wdtt-server admin --config-dir /etc/wdtt --request-stdin",
|
||||
sudoPassword = "sudo-secret",
|
||||
stdinPayload = request,
|
||||
)
|
||||
|
||||
assertTrue("sudo -S -p ''" in plan.command)
|
||||
assertTrue("command -v sudo" in plan.command)
|
||||
assertTrue("id -u" in plan.command)
|
||||
assertFalse("sudo -n" in plan.command)
|
||||
assertFalse("sudo -v" in plan.command)
|
||||
assertFalse("sudo-secret" in plan.command)
|
||||
assertFalse("owner-secret" in plan.command)
|
||||
assertTrue("sudo-secret" in plan.stdinPayload)
|
||||
assertTrue("owner-secret" in plan.stdinPayload)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun completeAdminPlanWorksWhenSudoReadsPassword() {
|
||||
val result = runPlanWithFakePrivileges(
|
||||
sudoScript = """
|
||||
#!/bin/sh
|
||||
[ "${'$'}1" = "-S" ] && shift
|
||||
if [ "${'$'}1" = "-p" ]; then shift 2; fi
|
||||
IFS= read -r supplied_password || exit 40
|
||||
[ "${'$'}supplied_password" = "sudo-secret" ] || exit 41
|
||||
exec "${'$'}@"
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals(request, result.stdout)
|
||||
assertEquals("", result.stderr)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun completeAdminPlanWorksWhenSudoDoesNotReadPassword() {
|
||||
val result = runPlanWithFakePrivileges(
|
||||
sudoScript = """
|
||||
#!/bin/sh
|
||||
[ "${'$'}1" = "-S" ] && shift
|
||||
if [ "${'$'}1" = "-p" ]; then shift 2; fi
|
||||
exec "${'$'}@"
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals(request, result.stdout)
|
||||
assertEquals("", result.stderr)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun completeAdminPlanUsesDirectRootPathWithoutSudo() {
|
||||
val result = runPlanWithFakePrivileges(
|
||||
sudoScript = """
|
||||
#!/bin/sh
|
||||
exit 99
|
||||
""".trimIndent(),
|
||||
uid = 0,
|
||||
)
|
||||
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals(request, result.stdout)
|
||||
assertEquals("", result.stderr)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun multilineSudoPasswordFailsBeforeOpeningRemoteCommand() {
|
||||
val error = assertThrows(IllegalArgumentException::class.java) {
|
||||
buildAdminRootStdinExecPlan("cat", "first\nsecond", request)
|
||||
}
|
||||
|
||||
assertTrue(error.message.orEmpty().contains("перенос строки"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sudoFailuresHaveActionableRussianMessages() {
|
||||
assertEquals(
|
||||
"Не удалось подтвердить права sudo. Проверьте SSH-пароль или пароль sudo в «Деплой → SSH».",
|
||||
friendlyAdminSudoError("sudo: 1 incorrect password attempt"),
|
||||
)
|
||||
assertEquals(
|
||||
"У SSH-пользователя нет разрешения выполнять команды управления через sudo.",
|
||||
friendlyAdminSudoError("user is not in the sudoers file"),
|
||||
)
|
||||
assertEquals(
|
||||
"Для управления сервером нужны root-права или установленный sudo.",
|
||||
friendlyAdminSudoError("error: root privileges required and sudo not found"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fastCommandWaitsForInputBeforeFinishing() {
|
||||
val plan = buildSshExecStdinPlan(
|
||||
"if [ 0 = 0 ]; then printf 'ready\\n'; else sudo -S -p '' printf 'ready\\n'; fi",
|
||||
"sudo-secret",
|
||||
)!!
|
||||
// Test the actual frame received by root or passwordless sudo. Delay the
|
||||
// writer, as happens when the SSH reply outruns the local sending thread.
|
||||
val process = ProcessBuilder("bash", "-c", buildAdminStdinForwardingCommand("exec sh -s")).start()
|
||||
try {
|
||||
assertFalse(process.waitFor(150, TimeUnit.MILLISECONDS))
|
||||
process.outputStream.use { it.write(plan.stdinPayload.toByteArray()) }
|
||||
assertTrue(process.waitFor(5, TimeUnit.SECONDS))
|
||||
assertEquals(0, process.exitValue())
|
||||
assertEquals("ready\n", process.inputStream.bufferedReader().readText())
|
||||
assertEquals("", process.errorStream.bufferedReader().readText())
|
||||
} finally {
|
||||
process.destroyForcibly()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ordinaryCommandsDoNotReceivePasswordOrWrapper() {
|
||||
assertEquals(null, buildSshExecStdinPlan("command -v sudo; printf 'ready\\n'", "sudo-secret"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun alreadyFramedAdminRequestIsNotFramedTwice() {
|
||||
val original = buildAdminRootStdinExecPlan("cat", "sudo-secret", request)
|
||||
assertEquals(original, buildSshExecStdinPlan(original.command, "sudo-secret", original.stdinPayload))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun plainRootCommandReceivesNoUnusedPassword() {
|
||||
val plan = buildSshExecStdinPlan(
|
||||
"if [ 0 = 0 ]; then cat </dev/null; else sudo -S -p '' cat; fi",
|
||||
"sudo-secret",
|
||||
)!!
|
||||
val result = runShell(buildAdminStdinForwardingCommand("exec sh -s"), plan.stdinPayload)
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals("", result.stdout)
|
||||
assertEquals("", result.stderr)
|
||||
assertFalse("sudo-secret" in plan.command)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun plainShDiagnosticsDoNotGainBashDependency() {
|
||||
val plan = buildSshExecStdinPlan(
|
||||
"if [ 0 = 0 ]; then sh -c 'printf ready'; else sudo -S -p '' sh -c 'printf ready'; fi",
|
||||
"sudo-secret",
|
||||
)!!
|
||||
assertFalse("bash" in plan.command)
|
||||
val result = runShell(buildAdminStdinForwardingCommand("exec sh -s", shell = "sh"), plan.stdinPayload)
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals("ready", result.stdout)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun longRootScriptTravelsOverStdinWithoutExceedingArgumentLimit() {
|
||||
val script = "printf 'probe-ok\\n'\n" + "v='x'\n".repeat(4_000)
|
||||
val original = rootCommand(script)
|
||||
assertTrue(original.length in 50_000..130_000)
|
||||
assertTrue(buildAdminRootStdinExecPlan(original, "sudo-secret", "", shell = "sh").command.length > 131_072)
|
||||
val plan = buildSshExecStdinPlan(original, "sudo-secret")!!
|
||||
assertTrue(plan.command.length < 2_000)
|
||||
assertFalse(original in plan.command)
|
||||
assertTrue(original in plan.stdinPayload)
|
||||
|
||||
val directory = Files.createTempDirectory("wdtt-long-ssh-script-").toFile()
|
||||
try {
|
||||
val fakeId = directory.resolve("id")
|
||||
fakeId.writeText("#!/bin/sh\nprintf '0\\n'\n")
|
||||
assertTrue(fakeId.setExecutable(true))
|
||||
val result = runShell(
|
||||
plan.command,
|
||||
plan.stdinPayload,
|
||||
mapOf("PATH" to "${directory.absolutePath}:${System.getenv("PATH")}"),
|
||||
)
|
||||
assertEquals(0, result.exitCode)
|
||||
assertEquals("probe-ok\n", result.stdout)
|
||||
assertEquals("", result.stderr)
|
||||
} finally {
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runShell(command: String, input: String): ShellResult {
|
||||
return runShell(command, input, emptyMap())
|
||||
}
|
||||
|
||||
private fun runPlanWithFakePrivileges(sudoScript: String, uid: Int = 1000): ShellResult {
|
||||
val directory = Files.createTempDirectory("wdtt-admin-sudo-test-").toFile()
|
||||
return try {
|
||||
val fakeId = directory.resolve("id")
|
||||
fakeId.writeText("#!/bin/sh\nprintf '$uid\\n'\n")
|
||||
assertTrue(fakeId.setExecutable(true))
|
||||
val fakeSudo = directory.resolve("sudo")
|
||||
fakeSudo.writeText("$sudoScript\n")
|
||||
assertTrue(fakeSudo.setExecutable(true))
|
||||
val plan = buildAdminRootStdinExecPlan("cat", "sudo-secret", request)
|
||||
runShell(
|
||||
command = plan.command,
|
||||
input = plan.stdinPayload,
|
||||
environment = mapOf("PATH" to "${directory.absolutePath}:${System.getenv("PATH")}"),
|
||||
)
|
||||
} finally {
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runShell(command: String, input: String, environment: Map<String, String>): ShellResult {
|
||||
val builder = ProcessBuilder("bash", "-c", command)
|
||||
builder.environment().putAll(environment)
|
||||
val process = builder.start()
|
||||
process.outputStream.bufferedWriter().use { it.write(input) }
|
||||
val stdout = process.inputStream.bufferedReader().use { it.readText() }
|
||||
val stderr = process.errorStream.bufferedReader().use { it.readText() }
|
||||
return ShellResult(process.waitFor(), stdout, stderr)
|
||||
}
|
||||
|
||||
private data class ShellResult(
|
||||
val exitCode: Int,
|
||||
val stdout: String,
|
||||
val stderr: String,
|
||||
)
|
||||
}
|
||||
@@ -10,6 +10,25 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ServerMigrationTest {
|
||||
@Test
|
||||
fun cleanVpsDoesNotRequireAnUpdateWhenCredentialsHaveBeenFilled() {
|
||||
val state = ServerMigrationState(19, 17, 0, 2, installationPresent = false)
|
||||
assertFalse(state.profileUpdateRequired)
|
||||
assertFalse(state.shouldShowNoticeForProfile(2))
|
||||
assertEquals(0, state.completedLevel)
|
||||
assertTrue(state.copy(installationPresent = true).profileUpdateRequired)
|
||||
assertFalse(state.copy(installationPresent = true, completedLevel = 19).profileUpdateRequired)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun probePresenceIsOnlyReusedForTheSameServerAndSshPort() {
|
||||
assertEquals(false, resolveServerInstallationPresence(false, " VPS.EXAMPLE ", 22, "vps.example", 22))
|
||||
assertEquals(null, resolveServerInstallationPresence(false, "vps.example", 22, "other.example", 22))
|
||||
assertEquals(null, resolveServerInstallationPresence(false, "vps.example", 22, "vps.example", 2222))
|
||||
assertEquals(null, resolveServerInstallationPresence(false, "", 22, "", 22))
|
||||
assertEquals(null, resolveServerInstallationPresence(null, null, null, "vps.example", 22))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun currentServerSnapshotWithBackupPolicyIsAccepted() {
|
||||
fun file(path: String, value: String): JSONObject {
|
||||
@@ -200,6 +219,38 @@ class ServerMigrationTest {
|
||||
assertTrue(state.profileUpdateRequired)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun release19RequiresUpdateFrom18() {
|
||||
val result = resolveServerMigrationInitialization(19, true, 18, 17, 17, 5)
|
||||
assertEquals(19, result.pendingLevel)
|
||||
assertEquals(17, result.acknowledgedLevel)
|
||||
assertEquals(19, latestServerMigrationLevel(19))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun freshInstall19DoesNotShowAnUpdateNotice() {
|
||||
val result = resolveServerMigrationInitialization(19, false, null, 0, null, 0)
|
||||
assertEquals(0, result.pendingLevel)
|
||||
assertEquals(19, result.lastSeenAppVersionCode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acknowledged19IsNotRepeatedButIncompleteProfilesStillNeedUpdating() {
|
||||
val result = resolveServerMigrationInitialization(19, true, 19, 19, 19, 5)
|
||||
val state = ServerMigrationState(result.pendingLevel, result.acknowledgedLevel, 17, 2)
|
||||
assertFalse(state.shouldShowNoticeForProfile(2))
|
||||
assertTrue(state.profileUpdateRequired)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noticeOnlyBelongsToTheCurrentUnfinishedProfile() {
|
||||
val pending = ServerMigrationState(19, 17, 17, 2)
|
||||
assertTrue(pending.shouldShowNoticeForProfile(2))
|
||||
assertFalse(pending.shouldShowNoticeForProfile(1))
|
||||
assertFalse(pending.copy(completedLevel = 19).shouldShowNoticeForProfile(2))
|
||||
assertTrue(pending.copy(completedLevel = 19).noticeRequired)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverNoticeRequiresBothSshAndOwnerCredentials() {
|
||||
assertTrue(hasManagedServerCredentials("example.org", "password", "ssh-password", "owner-password"))
|
||||
|
||||
@@ -52,4 +52,12 @@ class VkJoinLinkTest {
|
||||
assertFalse(VkJoinLink.isValidInput("https://vk.ru/not-a-call/a"))
|
||||
assertEquals("a,b_C-2", VkJoinLink.normalizeHashes("a, b_C-2"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun completeHashSetRequiresFourDistinctValidValues() {
|
||||
assertTrue(VkJoinLink.hasCompleteHashSet("one,two,three,four"))
|
||||
assertFalse(VkJoinLink.hasCompleteHashSet("one,two,three"))
|
||||
assertFalse(VkJoinLink.hasCompleteHashSet("one,two,three,three"))
|
||||
assertFalse(VkJoinLink.hasCompleteHashSet("one,two,three,нельзя"))
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,33 @@ import org.junit.Test
|
||||
import org.json.JSONObject
|
||||
|
||||
class VpnAddressRoutingTest {
|
||||
@Test
|
||||
fun temporaryDirectAddressesAreRemovedWithoutDroppingOtherRoutes() {
|
||||
assertEquals(
|
||||
listOf(
|
||||
"198.51.100.0/24",
|
||||
"203.0.113.0/32",
|
||||
"203.0.113.2/31",
|
||||
"::/1",
|
||||
),
|
||||
applyTemporaryDirectIpv4Addresses(
|
||||
allowedIps = listOf("203.0.113.0/30", "198.51.100.0/24", "::/1"),
|
||||
directAddresses = listOf("203.0.113.1", "203.0.113.1", "not-an-ip"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun temporaryDirectAddressesDoNotCreateRoutesOutsideExistingWhitelist() {
|
||||
assertEquals(
|
||||
listOf("192.0.2.0/24"),
|
||||
applyTemporaryDirectIpv4Addresses(
|
||||
allowedIps = listOf("192.0.2.0/24"),
|
||||
directAddresses = listOf("203.0.113.1"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun addressListsAreRegisteredAsPerProfilePreferences() {
|
||||
assertTrue(
|
||||
|
||||
@@ -6,8 +6,60 @@ import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.nio.file.Files
|
||||
|
||||
class DeployDataSafetyTest {
|
||||
@Test
|
||||
fun `server update rollback probe distinguishes valid corrupted and unknown backups`() {
|
||||
val root = Files.createTempDirectory("wdtt-update-backup-test").toFile()
|
||||
try {
|
||||
val missing = runRollbackProbe(File(root, "missing"))
|
||||
assertTrue(missing is ServerUpdateRollbackState.None)
|
||||
|
||||
val backup = File(root, "backup").apply { mkdirs() }
|
||||
File(backup, "state").writeText("prepared\n")
|
||||
File(backup, "had_config").createNewFile()
|
||||
File(backup, "config").mkdir()
|
||||
val valid = runRollbackProbe(backup)
|
||||
assertTrue(valid is ServerUpdateRollbackState.PreparedValid)
|
||||
assertTrue((valid as ServerUpdateRollbackState.PreparedValid).markers.hadConfig)
|
||||
|
||||
File(backup, "config").delete()
|
||||
val corrupted = runRollbackProbe(backup)
|
||||
assertTrue(corrupted is ServerUpdateRollbackState.PreparedCorrupted)
|
||||
|
||||
File(backup, "had_config").delete()
|
||||
File(backup, "state").writeText("committed\n")
|
||||
val unknown = runRollbackProbe(backup)
|
||||
assertTrue(unknown is ServerUpdateRollbackState.UnknownState)
|
||||
} finally {
|
||||
root.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unfinished update backup requires explicit recovery UI`() {
|
||||
val source = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
|
||||
File("src/main/java/com/wdtt/plus/ui/DeployTab.kt")
|
||||
).first(File::isFile).readText()
|
||||
|
||||
assertTrue("ServerUpdateRollbackDialog(" in source)
|
||||
assertTrue("Восстановить прежнее состояние" in source)
|
||||
assertTrue("server-update-backup-cleanup" in source)
|
||||
assertTrue("systemctl is-active --quiet wdtt" in source)
|
||||
assertTrue("WDTT_UPDATE_BACKUP=stale" in source)
|
||||
}
|
||||
|
||||
private fun runRollbackProbe(backup: File): ServerUpdateRollbackState {
|
||||
val process = ProcessBuilder("bash", "-c", serverUpdateRollbackProbeScript(backup.absolutePath))
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
val output = process.inputStream.bufferedReader().readText()
|
||||
assertEquals(0, process.waitFor())
|
||||
return parseServerUpdateRollbackState(output)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `single owner profile difference is shown without a whole-profile warning`() {
|
||||
assertEquals(
|
||||
@@ -41,7 +93,12 @@ class DeployDataSafetyTest {
|
||||
.filter { it.isFile && it.extension in setOf("kt", "java") }
|
||||
.joinToString("\n") { it.readText() }
|
||||
|
||||
assertFalse("own-VPN Network socket binding reintroduces EPERM", "network.socketFactory" in deploySources)
|
||||
val sshSources = sourceRoot.walkTopDown()
|
||||
.filter { it.isFile && (it.name.contains("Ssh") || it.name == "DeployTab.kt") }
|
||||
.joinToString("\n") { it.readText() }
|
||||
// A provider HTTP client may deliberately bind a physical Network.
|
||||
// This regression protects SSH/deploy, not every socket in the app.
|
||||
assertFalse("own-VPN Network socket binding reintroduces EPERM", "network.socketFactory" in sshSources)
|
||||
assertFalse("removed SSH VPN socket factory was restored", "WdttVpnSocketFactory" in deploySources)
|
||||
assertFalse("removed SSH VPN network selector was restored", "WdttVpnSshFallback" in deploySources)
|
||||
assertTrue(
|
||||
@@ -226,6 +283,34 @@ class DeployDataSafetyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `deploy expandable sections scroll while expanding without persistence delay`() {
|
||||
val source = sequenceOf(
|
||||
File("app/src/main/java/com/wdtt/plus/ui/DeployTab.kt"),
|
||||
File("src/main/java/com/wdtt/plus/ui/DeployTab.kt")
|
||||
).first(File::isFile).readText()
|
||||
|
||||
assertTrue("all deploy sections must use post-layout window coordinates",
|
||||
listOf(
|
||||
"clientsSectionTopInWindow = it.boundsInWindow().top",
|
||||
"outboundSectionTopInWindow = it.boundsInWindow().top",
|
||||
"migrationSectionTopInWindow = it.boundsInWindow().top",
|
||||
).all(source::contains))
|
||||
assertFalse("scrolling must not wait for expansion to settle",
|
||||
"framesSinceGrowth" in source || "stableFrames" in source)
|
||||
assertTrue("scrolling must follow the expanding scroll range",
|
||||
"deployScrollState.maxValue.toFloat()" in source && "scrollBy(next - deployScrollState.value)" in source)
|
||||
assertTrue("local section state must update before asynchronous persistence",
|
||||
listOf("clientsExpandedOverride = expanded", "outboundExpandedOverride = willExpand",
|
||||
"migrationExpandedOverride = willExpand").all(source::contains))
|
||||
assertTrue("each section state must trigger the shared reveal path",
|
||||
source.split("revealExpandedSection").size - 1 >= 4)
|
||||
assertFalse("section reveal must not race DataStore with a fixed delay",
|
||||
"animateScrollTo((clientsSectionY" in source ||
|
||||
"animateScrollTo((outboundSectionY" in source ||
|
||||
"animateScrollTo((migrationSectionY" in source)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `backup history keeps information in pager and actions in a separate selected panel`() {
|
||||
val source = sequenceOf(
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class DeployRootAccessTest {
|
||||
@Test
|
||||
fun confirmedRootAccessIsAccepted() {
|
||||
validateRootAccessOutput("WDTT_ROOT_ACCESS=ok\n")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun timeoutIsReportedAsTimeoutRatherThanMissingRoot() {
|
||||
val error = assertThrows(IllegalStateException::class.java) {
|
||||
validateRootAccessOutput("error: timeout")
|
||||
}
|
||||
assertTrue(friendlyDeployError(error, "проверка сервера").contains("не ответил вовремя"))
|
||||
assertFalse(error.message.orEmpty().contains("sudo"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun brokenChannelIsReportedAsConnectionFailure() {
|
||||
for (failure in listOf("session is down", "Pipe closed", "Broken pipe", "Socket closed", "Connection reset", "channel is not opened")) {
|
||||
val error = assertThrows(IllegalStateException::class.java) {
|
||||
validateRootAccessOutput("error: $failure")
|
||||
}
|
||||
assertTrue(friendlyDeployError(error, "проверка сервера").contains("SSH-сессия оборвалась"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingAnswerDoesNotClaimPermissionDenial() {
|
||||
for (output in listOf("", "partial response", "WDTT_ROOT_ACCESS=")) {
|
||||
val error = assertThrows(IllegalStateException::class.java) { validateRootAccessOutput(output) }
|
||||
assertTrue(error.message.orEmpty().contains("не подтвердил проверку"))
|
||||
assertFalse(error.message.orEmpty().contains("root-права не получены"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rootMarkerDoesNotHideCommandFailure() {
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
validateRootAccessOutput("WDTT_ROOT_ACCESS=ok\nerror: remote command exited with code 1\n")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun actualSudoDenialKeepsPermissionGuidance() {
|
||||
for (output in listOf("sudo: 1 incorrect password attempt", "user is not in the sudoers file", "error: root privileges required and sudo not found")) {
|
||||
val error = assertThrows(IllegalStateException::class.java) { validateRootAccessOutput(output) }
|
||||
assertTrue(error.message.orEmpty().contains("sudo"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ExternalProxyDiagnosticsTest {
|
||||
private fun probe(scenario: String): Pair<Int, String> {
|
||||
val dir = Files.createTempDirectory("proxy-probe-test").toFile()
|
||||
try {
|
||||
fun executable(name: String, body: String) = dir.resolve(name).apply {
|
||||
writeText("#!/bin/sh\n$body\n")
|
||||
setExecutable(true)
|
||||
}
|
||||
executable("systemctl", "exit 0")
|
||||
executable("iptables", """
|
||||
case "${'$'}*" in
|
||||
*"-A WDTT_PROXY_TEST"*) [ "${'$'}SCENARIO" != rule_failure ] || exit 1 ;;
|
||||
*"-L WDTT_PROXY_TEST"*)
|
||||
if [ "${'$'}SCENARIO" = bypass ]; then echo '0 0 REDIRECT'; else echo '1 60 REDIRECT'; fi ;;
|
||||
esac
|
||||
exit 0
|
||||
""".trimIndent())
|
||||
executable("curl", """
|
||||
echo curl >>"${'$'}CALLS"
|
||||
[ "${'$'}1" = -q ] || exit 99
|
||||
case " ${'$'}* " in *" --proxy --noproxy * --interface 10.66.66.1 "*) ;; *) exit 99 ;; esac
|
||||
case "${'$'}SCENARIO" in
|
||||
fallback) case "${'$'}*" in *api.ipify.org*) exit 28 ;; esac ;;
|
||||
partial) echo 198.51.100.2; exit 28 ;;
|
||||
invalid) echo '<html>error</html>'; exit 0 ;;
|
||||
esac
|
||||
echo 198.51.100.2
|
||||
""".trimIndent())
|
||||
val script = dir.resolve("probe.sh").apply {
|
||||
writeText("""
|
||||
set -e
|
||||
wdtt_test_source() { echo 10.66.66.1; }
|
||||
wdtt_cleanup_proxy_test() { echo cleanup >>"${'$'}CALLS"; }
|
||||
wdtt_proxy_reserved_returns() { return 0; }
|
||||
${externalProxyProbeFunctions()}
|
||||
if ! wdtt_test_redsocks_path 203.0.113.2; then exit 3; fi
|
||||
""".trimIndent())
|
||||
}
|
||||
val calls = dir.resolve("calls")
|
||||
val process = ProcessBuilder("sh", script.absolutePath).apply {
|
||||
environment()["PATH"] = dir.absolutePath + ":" + System.getenv("PATH")
|
||||
environment()["SCENARIO"] = scenario
|
||||
environment()["CALLS"] = calls.absolutePath
|
||||
redirectErrorStream(true)
|
||||
}.start()
|
||||
val output = process.inputStream.bufferedReader().readText()
|
||||
val result = process.waitFor()
|
||||
val events = calls.readLines()
|
||||
assertEquals("Cleanup before and after every probe", 2, events.count { it == "cleanup" })
|
||||
if (scenario == "rule_failure") assertFalse(events.contains("curl"))
|
||||
if (scenario == "fallback") assertEquals(2, events.count { it == "curl" })
|
||||
return result to output
|
||||
} finally {
|
||||
dir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun alternativeSiteCanVerifyRedirectedConnection() {
|
||||
val (code, output) = probe("fallback")
|
||||
assertEquals(output, 0, code)
|
||||
assertTrue(output.contains("198.51.100.2"))
|
||||
}
|
||||
|
||||
@Test fun failedRulesAndUnredirectedRequestsCannotPass() {
|
||||
for ((scenario, marker) in listOf(
|
||||
"rule_failure" to "external_proxy_test_rule_failed",
|
||||
"bypass" to "external_proxy_test_not_redirected",
|
||||
)) {
|
||||
val (code, output) = probe(scenario)
|
||||
assertEquals(output, 3, code)
|
||||
assertTrue(output.contains("WDTT_ERROR=$marker"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun partialCurlOutputAndHtmlAreNotSuccessfulChecks() {
|
||||
for (scenario in listOf("partial", "invalid")) {
|
||||
val (code, output) = probe(scenario)
|
||||
assertEquals(output, 3, code)
|
||||
assertTrue(output.contains("WDTT_ERROR=external_proxy_apply_failed"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun currentErrorSurvivesLongProgressAndDoesNotClaimDirectSuccess() {
|
||||
val excerpt = rootScriptErrorExcerpt("WDTT_PROGRESS|0.1|install\n".repeat(100) +
|
||||
"WDTT_ERROR=external_proxy_apply_failed\nWDTT_PROXY_CURL_EXIT=28\n")
|
||||
assertTrue(excerpt.startsWith("WDTT_ERROR="))
|
||||
val message = externalProxyFailureMessage(excerpt)
|
||||
assertTrue(message.contains("врем"))
|
||||
assertFalse(message.contains("отвечает напрямую"))
|
||||
assertFalse(message.contains("redsocks_drop_client"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import com.wdtt.plus.shouldPrepareInitialServerTunnel
|
||||
|
||||
class FirstServerSetupTest {
|
||||
private val valid = ServerSetupDraft(host = "203.0.113.42", sshPassword = "vps-secret", mainPassword = "wdtt-secret")
|
||||
|
||||
@Test fun `fresh classification requires absence of every installation trace`() {
|
||||
assertEquals(ServerSetupKind.FRESH, classifyFirstServerSetup(false, DeploymentOwnership.UnknownExisting, false))
|
||||
assertEquals(ServerSetupKind.FRESH, classifyFirstServerSetup(false, DeploymentOwnership.NoInstall, false))
|
||||
assertNull(classifyFirstServerSetup(true, DeploymentOwnership.UnknownExisting, false))
|
||||
assertNull(classifyFirstServerSetup(false, DeploymentOwnership.AndroidDeploy, false))
|
||||
}
|
||||
@Test fun `known installations and backups select separate safe routes`() {
|
||||
val cases = mapOf(
|
||||
DeploymentOwnership.AndroidDeploy to ServerSetupKind.EXISTING,
|
||||
DeploymentOwnership.LegacyAndroidDeploy to ServerSetupKind.EXISTING,
|
||||
DeploymentOwnership.PreservedAndroidData to ServerSetupKind.PRESERVED,
|
||||
DeploymentOwnership.IncompleteAndroidDeploy to ServerSetupKind.INCOMPLETE,
|
||||
DeploymentOwnership.StandaloneInstaller to ServerSetupKind.STANDALONE,
|
||||
)
|
||||
cases.forEach { (owner, expected) -> assertEquals(expected, classifyFirstServerSetup(true, owner, false)) }
|
||||
assertEquals(ServerSetupKind.RECOVERY, classifyFirstServerSetup(false, DeploymentOwnership.UnknownExisting, true))
|
||||
assertEquals(ServerSetupKind.STANDALONE, classifyFirstServerSetup(true, DeploymentOwnership.StandaloneInstaller, true))
|
||||
}
|
||||
@Test fun `password generation is compatible and does not repeat a fixed default`() {
|
||||
val values = (1..100).map { generateServerAdminPassword() }
|
||||
assertTrue(values.all { it.matches(Regex("[a-zA-Z0-9]{24}")) })
|
||||
assertEquals(values.size, values.toSet().size)
|
||||
assertTrue(valid.copy(mainPassword = values.first()).settingsIssue() == null)
|
||||
}
|
||||
@Test fun `missing and malformed SSH settings block probing`() {
|
||||
assertNull(valid.accessIssue())
|
||||
assertNotNull(valid.copy(host = "").accessIssue())
|
||||
assertNotNull(valid.copy(sshPassword = "").accessIssue())
|
||||
assertNotNull(valid.copy(sshPort = "65536").accessIssue())
|
||||
assertNotNull(valid.copy(authMode = "key", privateKey = "").accessIssue())
|
||||
}
|
||||
@Test fun `custom ports DNS and optional bot are checked before confirmation`() {
|
||||
assertNull(valid.settingsIssue())
|
||||
assertNotNull(valid.copy(mainPassword = "").settingsIssue())
|
||||
assertNotNull(valid.copy(mainPassword = "contains space").settingsIssue())
|
||||
assertNotNull(valid.copy(dtlsPort = "0").settingsIssue())
|
||||
assertNotNull(valid.copy(dtlsPort = "56001").settingsIssue())
|
||||
assertNotNull(valid.copy(localPort = "65536").settingsIssue())
|
||||
assertNotNull(valid.copy(dns1 = "1.1.1.1;echo").settingsIssue())
|
||||
assertNotNull(valid.copy(adminId = "123").settingsIssue())
|
||||
assertNotNull(valid.copy(adminId = "bad", botToken = "token").settingsIssue())
|
||||
assertNull(valid.copy(dns1 = "9.9.9.9", dns2 = "", dtlsPort = "60000", wgPort = "60001", localPort = "9100").settingsIssue())
|
||||
}
|
||||
@Test fun `request uses the confirmed settings and keeps VPS and WDTT passwords separate`() {
|
||||
val request = valid.copy(user = "operator", sshPort = "2222", dtlsPort = "60000", wgPort = "60001", localPort = "9100", dns1 = "9.9.9.9", dns2 = "", adminId = "123", botToken = "token").request()
|
||||
assertEquals("vps-secret", request.pass)
|
||||
assertEquals("wdtt-secret", request.mainPass)
|
||||
assertEquals("operator", request.user)
|
||||
assertEquals(2222, request.sshPort)
|
||||
assertEquals(60000, request.dtlsPort)
|
||||
assertEquals(60001, request.wgPort)
|
||||
assertEquals(9100, request.localPort)
|
||||
assertEquals("9.9.9.9", request.dns1)
|
||||
assertEquals("", request.dns2)
|
||||
assertEquals("123", request.adminId)
|
||||
assertEquals("token", request.botToken)
|
||||
val localOnly = valid.copy(localPort = "9100").request()
|
||||
assertEquals(56000, localOnly.dtlsPort)
|
||||
assertEquals(56001, localOnly.wgPort)
|
||||
assertEquals(9100, localOnly.localPort)
|
||||
}
|
||||
@Test fun `moving between wizard steps requires the exact VPS access that was checked`() {
|
||||
val checked = valid.copy(authMode = "password", sshPort = "22")
|
||||
assertTrue(checked.copy(mainPassword = "changed", dns1 = "9.9.9.9").sameServerAccess(checked))
|
||||
assertFalse(checked.copy(host = "203.0.113.43").sameServerAccess(checked))
|
||||
assertFalse(checked.copy(sshPassword = "other-password").sameServerAccess(checked))
|
||||
assertFalse(checked.copy(sshPort = "2222").sameServerAccess(checked))
|
||||
assertFalse(checked.copy(authMode = "key", privateKey = "key").sameServerAccess(checked))
|
||||
}
|
||||
@Test fun `filled existing profile can update without an old wizard completion marker`() {
|
||||
assertTrue(offersServerUpdate(false, true, "wdtt-secret"))
|
||||
assertTrue(offersServerUpdate(true, false, ""))
|
||||
assertFalse(offersServerUpdate(false, false, "wdtt-secret"))
|
||||
assertFalse(offersServerUpdate(false, true, " "))
|
||||
}
|
||||
@Test fun `first install prepares only a tunnel without any existing server credentials or remote binding`() {
|
||||
assertTrue(shouldPrepareInitialServerTunnel("", "", "", false, ""))
|
||||
assertTrue(shouldPrepareInitialServerTunnel(" ", " ", " ", false, ""))
|
||||
assertFalse(shouldPrepareInitialServerTunnel("old.example.org", "", "", false, ""))
|
||||
assertFalse(shouldPrepareInitialServerTunnel("", "old-password", "", false, ""))
|
||||
assertFalse(shouldPrepareInitialServerTunnel("", "", "wdtt://old-profile", false, ""))
|
||||
assertFalse(shouldPrepareInitialServerTunnel("", "", "", true, ""))
|
||||
assertFalse(shouldPrepareInitialServerTunnel("", "", "", false, "opaque-binding"))
|
||||
}
|
||||
@Test fun `first install can open tunnel only while its original navigation is unchanged`() {
|
||||
assertTrue(canOpenInitialServerTunnel(2, 10, 2, 10, true, false))
|
||||
assertFalse(canOpenInitialServerTunnel(2, 10, 2, 11, false, false))
|
||||
// Returning to Deploy cannot revive a transition cancelled by earlier navigation.
|
||||
assertFalse(canOpenInitialServerTunnel(2, 10, 2, 12, true, false))
|
||||
assertFalse(canOpenInitialServerTunnel(2, 10, 1, 10, true, false))
|
||||
}
|
||||
@Test fun `opening another window permanently cancels only the automatic navigation`() {
|
||||
assertFalse(canOpenInitialServerTunnel(2, 10, 2, 10, true, true))
|
||||
assertFalse(canOpenInitialServerTunnel(2, 10, 2, 10, false, false))
|
||||
assertFalse(canOpenInitialServerTunnel(null, null, 2, 10, true, false))
|
||||
}
|
||||
private fun completeProbe(): String = listOf("SERVICE", "BINARY", "CONFIG_DIR", "ACCESS_DB", "WG_KEYS", "WDTT_STANDALONE_MANAGED", "WDTT_ANDROID_DEPLOY_MANAGED", "WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE", "WDTT_ANDROID_DATA_PRESERVED", "WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE").joinToString("\n") { "$it=0" } + "\nACTIVE=unknown\nWDTT_UPDATE_BACKUP_STATUS=none\n"
|
||||
@Test fun `truncated failed duplicated or malformed probe cannot imply a clean VPS`() {
|
||||
validateExistingInstallProbe(completeProbe())
|
||||
for (bad in listOf("", "Permission denied", completeProbe().replace("SERVICE=0\n", ""), completeProbe().replace("BINARY=0", "BINARY=2"), completeProbe() + "SERVICE=1\n", completeProbe().replace("WDTT_UPDATE_BACKUP_STATUS=none\n", ""))) {
|
||||
assertTrue(runCatching { validateExistingInstallProbe(bad) }.isFailure)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,30 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class FloatingToolbarPositionTest {
|
||||
@Test
|
||||
fun relativePositionSurvivesRestartAndLateWindowMeasurement() {
|
||||
val saved = floatingToolbarFraction(680f, 80f, 1680f, 1f)
|
||||
assertEquals(0.375f, saved)
|
||||
assertEquals(680f, floatingToolbarOffset(saved, 80f, 1680f))
|
||||
assertEquals(380f, floatingToolbarOffset(saved, 80f, 880f))
|
||||
assertEquals(680f, floatingToolbarOffset(saved, 80f, 1680f))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tinyWindowDoesNotReplaceTheSavedFraction() {
|
||||
assertEquals(80f, floatingToolbarOffset(0.6f, 80f, 80f))
|
||||
assertEquals(0.6f, floatingToolbarFraction(80f, 80f, 80f, 0.6f))
|
||||
assertEquals(680f, floatingToolbarOffset(0.6f, 80f, 1080f))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun newInstallationDefaultsToBottomAndDraggingClampsToBothEdges() {
|
||||
assertEquals(880f, floatingToolbarOffset(-1f, 80f, 880f))
|
||||
assertEquals(880f, floatingToolbarOffset(Float.NaN, 80f, 880f))
|
||||
assertEquals(0f, floatingToolbarFraction(-200f, 80f, 880f, 0.5f))
|
||||
assertEquals(1f, floatingToolbarFraction(1200f, 80f, 880f, 0.5f))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun defaultBottomPositionStaysAboveNavigation() {
|
||||
assertEquals(
|
||||
@@ -96,4 +120,17 @@ class FloatingToolbarPositionTest {
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun startingProxyDoesNotPresentConfiguredAddressAsReady() {
|
||||
assertEquals(
|
||||
"АВТО ПРОКСИ · не запущен",
|
||||
proxyTunnelAddressSummary(
|
||||
mode = "auto",
|
||||
fallbackAddress = "127.0.0.1:1080",
|
||||
readyAddresses = emptyList(),
|
||||
running = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user