diff --git a/.github/ISSUE_TEMPLATE/connection.yml b/.github/ISSUE_TEMPLATE/connection.yml index 74f838f..65326c6 100644 --- a/.github/ISSUE_TEMPLATE/connection.yml +++ b/.github/ISSUE_TEMPLATE/connection.yml @@ -196,7 +196,7 @@ body: id: server_diagnostics attributes: label: Диагностика собственного сервера из «Деплой» - description: 'Для своего сервера: «Деплой» → «Установка на сервер» → лупа «Проверить сервер» → «Скопировать отчёт». SSH-доступ нужен только к серверу, которым вы управляете. Для полученного профиля без такого доступа поле можно пропустить. Перед публикацией проверьте адреса, логины, порты и сведения о системе.' + description: 'Для своего сервера: «Деплой» → лупа «Проверить сервер» → «Скопировать отчёт». SSH-доступ нужен только к серверу, которым вы управляете. Для полученного профиля без такого доступа поле можно пропустить. Перед публикацией проверьте адреса, логины, порты и сведения о системе.' render: text validations: required: false diff --git a/CHANGELOG.md b/CHANGELOG.md index e8d7178..9412d9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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-ключей; неудачная или прерванная операция полностью откатывается. - Ручная установка больше не останавливается с ошибкой при проверке свободного места на сервере. diff --git a/README.md b/README.md index bdb90a0..55b0d9e 100644 --- a/README.md +++ b/README.md @@ -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 для обхода блокировок или нарушения правил каких-либо платформ, а также не несут ответственности за финальные сценарии использования утилиты пользователями. Любые специфические технические особенности приложения описаны как исследование сетевой архитектуры и протоколов. > -> Проект является полностью некоммерческим, не содержит платных функций, скрытых подписок или коммерческой выгоды. +> Публичное приложение и самостоятельный сервер доступны бесплатно и не требуют подписки для самостоятельного использования. ## Для разработки diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 9d9d610..88db51d 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -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("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("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("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") diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a92e7a5..94941f5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -7,6 +7,7 @@ + @@ -199,6 +200,25 @@ android:resource="@xml/vpn_widget_compact_info" /> + + + + + + + diff --git a/app/src/main/assets/deploy.sh b/app/src/main/assets/deploy.sh index 21218b3..d5437ec 100755 --- a/app/src/main/assets/deploy.sh +++ b/app/src/main/assets/deploy.sh @@ -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" diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt index b6294db..e692de4 100644 --- a/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt @@ -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( diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt index bf0c175..71b4bc5 100644 --- a/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt @@ -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 вернул неподходящее обновление профиля." diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt index 1639749..ab4408e 100644 --- a/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt @@ -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() diff --git a/app/src/main/java/com/wdtt/plus/ConnectionDiagnostics.kt b/app/src/main/java/com/wdtt/plus/ConnectionDiagnostics.kt new file mode 100644 index 0000000..797a4c5 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ConnectionDiagnostics.kt @@ -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, +) diff --git a/app/src/main/java/com/wdtt/plus/ConnectionNetwork.kt b/app/src/main/java/com/wdtt/plus/ConnectionNetwork.kt new file mode 100644 index 0000000..1196ea8 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ConnectionNetwork.kt @@ -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 + } +} diff --git a/app/src/main/java/com/wdtt/plus/DefaultNetworkHttp.kt b/app/src/main/java/com/wdtt/plus/DefaultNetworkHttp.kt new file mode 100644 index 0000000..b5e4b6e --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/DefaultNetworkHttp.kt @@ -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 diff --git a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt index 1ac5187..8891b87 100644 --- a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt +++ b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt @@ -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, ) diff --git a/app/src/main/java/com/wdtt/plus/LocalBuildExtension.kt b/app/src/main/java/com/wdtt/plus/LocalBuildExtension.kt new file mode 100644 index 0000000..f259424 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/LocalBuildExtension.kt @@ -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() + } +} diff --git a/app/src/main/java/com/wdtt/plus/LocalContinuationExtension.kt b/app/src/main/java/com/wdtt/plus/LocalContinuationExtension.kt new file mode 100644 index 0000000..14d7dec --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/LocalContinuationExtension.kt @@ -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" +} diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt index a6698f3..3443176 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -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(null) } + var deployHeaderBounds by remember { mutableStateOf(null) } + var tunnelProfileStripEnd by remember { mutableStateOf(null) } + var deployProfileStripEnd by remember { mutableStateOf(null) } + var contentBounds by remember { mutableStateOf(Rect.Zero) } var showTransferCenter by rememberSaveable { mutableStateOf(false) } + LaunchedEffect(selectedTab, activeProfile, showTransferCenter) { navigationRevision++ } var startupDeviceReport by remember { mutableStateOf(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(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, diff --git a/app/src/main/java/com/wdtt/plus/ProfileTransfer.kt b/app/src/main/java/com/wdtt/plus/ProfileTransfer.kt new file mode 100644 index 0000000..49dc812 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ProfileTransfer.kt @@ -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 +} diff --git a/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt b/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt index 7c900d8..0fc6347 100644 --- a/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt +++ b/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt @@ -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 = 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 = (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 = ( // 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) diff --git a/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt b/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt index 4e74cb5..ccfb2fd 100644 --- a/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt +++ b/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt @@ -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? = 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) } diff --git a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt index f42669c..143437c 100644 --- a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt +++ b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt @@ -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() diff --git a/app/src/main/java/com/wdtt/plus/ServerMigration.kt b/app/src/main/java/com/wdtt/plus/ServerMigration.kt index 11cfc31..06ca780 100644 --- a/app/src/main/java/com/wdtt/plus/ServerMigration.kt +++ b/app/src/main/java/com/wdtt/plus/ServerMigration.kt @@ -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( diff --git a/app/src/main/java/com/wdtt/plus/SettingsStore.kt b/app/src/main/java/com/wdtt/plus/SettingsStore.kt index d786e66..4c1bda3 100644 --- a/app/src/main/java/com/wdtt/plus/SettingsStore.kt +++ b/app/src/main/java/com/wdtt/plus/SettingsStore.kt @@ -235,6 +235,7 @@ data class TunnelProfileSnapshot( val vpnDnsSelectionId: String = VPN_DNS_PROFILE_ID, val vpnDnsCustomServers: List = 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 = _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, @@ -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> = 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> = listOf( + LOCAL_CONTINUATION_ID, + ) + private val PROFILE_INT_KEYS: List> = 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> = 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> = 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 = - (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> = + (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 getProfileKey(baseKey: Preferences.Key, profile: Int): Preferences.Key { + 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 + PROFILE_STRING_KEYS.any { it.name == baseKey.name } || + PROFILE_LOCAL_STRING_KEYS.any { it.name == baseKey.name } -> + stringPreferencesKey(newName) as Preferences.Key PROFILE_INT_KEYS.any { it.name == baseKey.name } -> intPreferencesKey(newName) as Preferences.Key PROFILE_LONG_KEYS.any { it.name == baseKey.name } -> longPreferencesKey(newName) as Preferences.Key PROFILE_BOOLEAN_KEYS.any { it.name == baseKey.name } -> booleanPreferencesKey(newName) as Preferences.Key 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 = preferencesFlow.map { it[SHOW_SYSTEM_APPS] ?: false } val loggingEnabled: Flow = preferencesFlow.map { it[LOGGING_ENABLED] ?: true } val floatingToolbarYFraction: Flow = 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 = preferencesFlow.map { it[TRUSTED_WIFI_ENABLED] ?: false } val trustedWifiSsids: Flow> = 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 { + 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 = 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 = preferencesFlow.map { prefs -> + prefs[getProfileKey(DEPLOY_SETUP_COMPLETED, prefs[ACTIVE_PROFILE] ?: 0)] ?: false + } + + val deploySetupCompletion: Flow = 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 = 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 { + 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)) diff --git a/app/src/main/java/com/wdtt/plus/SshAuthentication.kt b/app/src/main/java/com/wdtt/plus/SshAuthentication.kt index c099c10..0a80a1f 100644 --- a/app/src/main/java/com/wdtt/plus/SshAuthentication.kt +++ b/app/src/main/java/com/wdtt/plus/SshAuthentication.kt @@ -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) diff --git a/app/src/main/java/com/wdtt/plus/TemporaryDirectRouting.kt b/app/src/main/java/com/wdtt/plus/TemporaryDirectRouting.kt new file mode 100644 index 0000000..01844c8 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/TemporaryDirectRouting.kt @@ -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>() + private var resolvedDomains: Set = emptySet() + + fun currentDomains(): Set = synchronized(lock) { + leases.values.flatten().toSet() + } + + fun add(domains: Set): 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) = synchronized(lock) { + resolvedDomains = domains.intersect(leases.values.flatten().toSet()) + } + + fun allResolved(domains: Set): 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): 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): Set { + 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() + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/TransportMode.kt b/app/src/main/java/com/wdtt/plus/TransportMode.kt new file mode 100644 index 0000000..1a24fb4 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/TransportMode.kt @@ -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 diff --git a/app/src/main/java/com/wdtt/plus/TunnelManager.kt b/app/src/main/java/com/wdtt/plus/TunnelManager.kt index 43847cd..ca52ee5 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelManager.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelManager.kt @@ -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 = 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 = 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(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 = "", diff --git a/app/src/main/java/com/wdtt/plus/TunnelService.kt b/app/src/main/java/com/wdtt/plus/TunnelService.kt index 1fa38ce..576d7e2 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelService.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelService.kt @@ -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, ) diff --git a/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt b/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt index c5a0377..a661c02 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt @@ -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) diff --git a/app/src/main/java/com/wdtt/plus/VkJoinLink.kt b/app/src/main/java/com/wdtt/plus/VkJoinLink.kt index 857c30a..975ca7e 100644 --- a/app/src/main/java/com/wdtt/plus/VkJoinLink.kt +++ b/app/src/main/java/com/wdtt/plus/VkJoinLink.kt @@ -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() } diff --git a/app/src/main/java/com/wdtt/plus/VpnAddressRouting.kt b/app/src/main/java/com/wdtt/plus/VpnAddressRouting.kt index 7c69fea..7c7e321 100644 --- a/app/src/main/java/com/wdtt/plus/VpnAddressRouting.kt +++ b/app/src/main/java/com/wdtt/plus/VpnAddressRouting.kt @@ -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, + directAddresses: Collection, +): List { + 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 { 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, diff --git a/app/src/main/java/com/wdtt/plus/WdttApplication.kt b/app/src/main/java/com/wdtt/plus/WdttApplication.kt index d4015c5..62d4ebd 100644 --- a/app/src/main/java/com/wdtt/plus/WdttApplication.kt +++ b/app/src/main/java/com/wdtt/plus/WdttApplication.kt @@ -23,6 +23,7 @@ class WdttApplication : Application() { override fun onCreate() { super.onCreate() + if (LocalBuildExtensions.initializeAuxiliaryProcess(this)) return DeployManager.init(this) val settingsStore = SettingsStore(this) diff --git a/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt b/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt index dcef47e..bfe09dc 100644 --- a/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt +++ b/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt @@ -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()}") } diff --git a/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt b/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt index 8302682..7edacb5 100644 --- a/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt @@ -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) { diff --git a/app/src/main/java/com/wdtt/plus/ui/CheckActionIcon.kt b/app/src/main/java/com/wdtt/plus/ui/CheckActionIcon.kt new file mode 100644 index 0000000..e1edf0e --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/CheckActionIcon.kt @@ -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, + ) + } +} diff --git a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt index b67012d..7ccf8de 100644 --- a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt @@ -18,6 +18,7 @@ import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.animate import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween @@ -51,12 +52,14 @@ import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import com.wdtt.plus.TunnelService import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Rect import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.graphics.graphicsLayer @@ -66,7 +69,6 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalDensity @@ -93,11 +95,14 @@ import com.wdtt.plus.DeviceCheckItem import com.wdtt.plus.DeviceCheckSeverity import com.wdtt.plus.DeviceCompatibilityReport import com.wdtt.plus.ServerAdminClient +import com.wdtt.plus.buildSshExecStdinPlan +import com.wdtt.plus.friendlyAdminSudoError import com.wdtt.plus.ServerAdminProfileInfo import com.wdtt.plus.ServerAdminTarget import com.wdtt.plus.ServerBackupManagerInfo import com.wdtt.plus.ServerStoredBackupDocument import com.wdtt.plus.ServerStoredBackupInfo +import com.wdtt.plus.ServerConnectionAccess import com.wdtt.plus.SettingsStore import com.wdtt.plus.SshCredentials import com.wdtt.plus.SshRoutePolicy @@ -118,13 +123,18 @@ import com.wdtt.plus.sshCredentialsForMode import com.wdtt.plus.vpnProfileRestorableName import com.wdtt.plus.vpnProfileDisplayName import com.wdtt.plus.vpnProfileTransferName +import kotlinx.coroutines.asContextElement import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.Job +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.launch +import kotlinx.coroutines.runInterruptible import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout import java.io.File import java.io.FileOutputStream import java.security.MessageDigest @@ -292,8 +302,8 @@ internal fun primaryServerSshAccessIssue( privateKey: String, sshPort: Int ): String? { - if (host.isBlank()) return "Укажите IP-адрес или домен сервера в верхнем блоке «Деплой»." - if (!hostValid) return "Проверьте IP-адрес или домен сервера в верхнем блоке «Деплой»." + if (host.isBlank()) return "Укажите IP-адрес или домен сервера в настройках SSH." + if (!hostValid) return "Проверьте IP-адрес или домен сервера в настройках SSH." sshAuthenticationIssueForMode( mode = mode, password = password, @@ -301,7 +311,7 @@ internal fun primaryServerSshAccessIssue( passwordLabel = "SSH-пароль", privateKeyLabel = "приватный SSH-ключ" )?.let { return it } - if (sshPort !in 1..65535) return "Откройте «Секреты» и укажите корректный SSH-порт от 1 до 65535." + if (sshPort !in 1..65535) return "Откройте настройки SSH и укажите корректный SSH-порт от 1 до 65535." return null } @@ -460,7 +470,8 @@ internal data class ExistingServerConnection( private data class PendingExistingConnectionApply( val connection: ExistingServerConnection, - val effectiveLogin: String, + val profileIndex: Int, + val target: OutboundSshTarget, val localProfile: ServerAdminProfileInfo, val serverProfile: ServerAdminProfileInfo, val diffLines: List @@ -502,11 +513,56 @@ private data class ExistingInstallInfo( val legacyAndroidDeployCandidate: Boolean = false, val preservedAndroidData: Boolean = false, val incompleteAndroidDeployCandidate: Boolean = false, + val updateRollbackState: ServerUpdateRollbackState = ServerUpdateRollbackState.None, val checkError: String? = null, val comparison: DeployServerComparison? = null ) { + val hasInstalledServer: Boolean + get() = serviceExists && binaryExists && accessDbExists && wgKeysExist + val hasAnyTrace: Boolean - get() = serviceExists || binaryExists || configDirExists || accessDbExists || wgKeysExist + get() = serviceExists || binaryExists || configDirExists || accessDbExists || wgKeysExist || active +} + +internal data class ServerUpdateRollbackMarkers( + val hadConfig: Boolean, + val hadBinary: Boolean, + val hadService: Boolean, + val wasActive: Boolean, + val wasEnabled: Boolean, +) + +internal sealed class ServerUpdateRollbackState { + data object None : ServerUpdateRollbackState() + data class PreparedValid(val markers: ServerUpdateRollbackMarkers) : ServerUpdateRollbackState() + data class PreparedCorrupted(val diagnostic: String) : ServerUpdateRollbackState() + data class UnknownState(val diagnostic: String) : ServerUpdateRollbackState() +} + +internal fun parseServerUpdateRollbackState(output: String): ServerUpdateRollbackState { + fun flag(name: String): Boolean = markerValue(output, name) == "1" + val diagnostic = markerValue(output, "WDTT_UPDATE_BACKUP_DIAGNOSTIC") + ?.replace('_', ' ') + ?.take(160) + .orEmpty() + return when (markerValue(output, "WDTT_UPDATE_BACKUP_STATUS")) { + "none" -> ServerUpdateRollbackState.None + "prepared_valid" -> ServerUpdateRollbackState.PreparedValid( + ServerUpdateRollbackMarkers( + hadConfig = flag("WDTT_UPDATE_BACKUP_HAD_CONFIG"), + hadBinary = flag("WDTT_UPDATE_BACKUP_HAD_BINARY"), + hadService = flag("WDTT_UPDATE_BACKUP_HAD_SERVICE"), + wasActive = flag("WDTT_UPDATE_BACKUP_WAS_ACTIVE"), + wasEnabled = flag("WDTT_UPDATE_BACKUP_WAS_ENABLED"), + ), + ) + "prepared_corrupted" -> ServerUpdateRollbackState.PreparedCorrupted( + diagnostic.ifBlank { "неполная или небезопасная структура копии" }, + ) + else -> ServerUpdateRollbackState.UnknownState( + diagnostic.ifBlank { "неизвестное состояние страховочной копии" }, + ) + } } internal enum class DeploymentOwnership { @@ -1091,7 +1147,7 @@ private fun outboundDialogServerStateSummary(snapshot: OutboundServerSnapshot, d private fun formatOutboundTimestamp(raw: String): String { val cleaned = raw.trim() if (cleaned.isBlank()) return "" - val ru = Locale("ru", "RU") + val ru = Locale.forLanguageTag("ru-RU") val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm", ru) val moscow = ZoneId.of("Europe/Moscow") val deviceZone = runCatching { ZoneId.systemDefault() }.getOrDefault(moscow) @@ -1111,7 +1167,7 @@ private fun formatOutboundTimestamp(raw: String): String { private fun formatOutboundCheckTime(millis: Long): String { if (millis <= 0L) return "" - val ru = Locale("ru", "RU") + val ru = Locale.forLanguageTag("ru-RU") val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm", ru) val moscow = ZoneId.of("Europe/Moscow") val deviceZone = runCatching { ZoneId.systemDefault() }.getOrDefault(moscow) @@ -1129,16 +1185,25 @@ private fun formatOutboundCheckTime(millis: Long): String { fun DeployTab( scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }, modifier: Modifier = Modifier, - visible: Boolean = true + visible: Boolean = true, + openInstallRequest: Int = 0, + openInstallProfile: Int? = null, + navigationRevision: Int = 0, + onOpenTunnel: (Int, Int) -> Unit = { _, _ -> }, + onProfileHeaderBounds: (Rect) -> Unit = {}, + onProfileHeaderBoundary: (Float) -> Unit = {}, ) { val context = LocalContext.current val scope = rememberCoroutineScope() val settingsStore = remember { SettingsStore(context) } val deployScrollState = rememberRememberedScrollState(scrollPosition) val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() } - var clientsSectionY by remember { mutableStateOf(0f) } - var outboundSectionY by remember { mutableStateOf(0f) } - var migrationSectionY by remember { mutableStateOf(0f) } + var clientsSectionTopInWindow by remember { mutableStateOf(null) } + var outboundSectionTopInWindow by remember { mutableStateOf(null) } + var migrationSectionTopInWindow by remember { mutableStateOf(null) } + var revealClientsRequested by remember { mutableStateOf(false) } + var revealOutboundRequested by remember { mutableStateOf(false) } + var revealMigrationRequested by remember { mutableStateOf(false) } var deployViewportTopInWindow by remember { mutableStateOf(null) } var migrationImportTopInWindow by remember { mutableStateOf(null) } var restoreScrollRequestId by remember { mutableIntStateOf(0) } @@ -1165,17 +1230,45 @@ fun DeployTab( LaunchedEffect(Unit) { DeployManager.init(context) } - val savedIp by settingsStore.deployIp.collectAsStateWithLifecycle(initialValue = "") val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0) val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) + val setupSnapshot by settingsStore.serverSetupSettings.collectAsStateWithLifecycle(initialValue = null) + val serverSettings = setupSnapshot?.takeIf { it.profileIndex == activeProfile } + val savedIp = serverSettings?.host.orEmpty() val currentActiveProfile by rememberUpdatedState(activeProfile) - val savedLogin by settingsStore.deployLogin.collectAsStateWithLifecycle(initialValue = "") - val savedPassword by settingsStore.deployPassword.collectAsStateWithLifecycle(initialValue = "") - val savedSshPrivateKey by settingsStore.deploySshPrivateKey.collectAsStateWithLifecycle(initialValue = "") - val savedSshKeyPassphrase by settingsStore.deploySshKeyPassphrase.collectAsStateWithLifecycle(initialValue = "") - val storedSshAuthMode by produceState(initialValue = null, settingsStore, activeProfile) { - settingsStore.deploySshAuthMode.collect { value = it } + val setupCompleted = serverSettings?.completed ?: false + val setupCompletion by settingsStore.deploySetupCompletion.collectAsStateWithLifecycle(initialValue = null) + var showFirstServerSetup by remember(activeProfile) { mutableStateOf(false) } + var setupInitial by remember(activeProfile) { mutableStateOf(null) } + var accessSaveJob by remember { mutableStateOf(null) } + var openingSetup by remember { mutableStateOf(false) } + var setupOpenError by remember(activeProfile) { mutableStateOf("") } + fun openSetup() { + val profile = activeProfile + openingSetup = true + setupOpenError = "" + scope.launch { + try { + accessSaveJob?.join() + val settings = settingsStore.readServerSetupSettings(profile) + if (currentActiveProfile != profile) return@launch + setupInitial = ServerSetupDraft(settings.host, settings.user.ifBlank { "root" }, settings.sshPassword, + settings.sshPort, settings.authMode, settings.privateKey, settings.keyPassphrase, + settings.mainPassword, settings.dns1, settings.dns2, settings.dtlsPort.toString(), + settings.wgPort.toString(), settings.localPort.toString(), settings.adminId, settings.botToken) + showFirstServerSetup = true + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Exception) { + if (currentActiveProfile == profile) setupOpenError = friendlyDeployError(e, "чтение настроек") + } finally { openingSetup = false } + } } + val savedLogin = serverSettings?.user ?: "" + val savedPassword = serverSettings?.sshPassword ?: "" + val savedSshPrivateKey = serverSettings?.privateKey ?: "" + val savedSshKeyPassphrase = serverSettings?.keyPassphrase ?: "" + val storedSshAuthMode = serverSettings?.authMode var sshAuthMode by rememberSaveable(activeProfile) { mutableStateOf(null) } val savedWireGuardExitSshPrivateKey by settingsStore.wireGuardExitSshPrivateKey.collectAsStateWithLifecycle(initialValue = "") val savedWireGuardExitSshKeyPassphrase by settingsStore.wireGuardExitSshKeyPassphrase.collectAsStateWithLifecycle(initialValue = "") @@ -1195,47 +1288,103 @@ fun DeployTab( initialValue = com.wdtt.plus.VpnDnsSettingsSnapshot(profileIndex = activeProfile) ) - var ip by remember { mutableStateOf("") } - var login by remember { mutableStateOf("") } - var password by remember { mutableStateOf("") } - var loginFocused by remember { mutableStateOf(false) } - var passwordFocused by remember { mutableStateOf(false) } + var ip by remember(activeProfile) { mutableStateOf("") } + var login by remember(activeProfile) { mutableStateOf("") } + var password by remember(activeProfile) { mutableStateOf("") } - val savedDns1 by settingsStore.deployDns1.collectAsStateWithLifecycle(initialValue = "1.1.1.1") - val savedDns2 by settingsStore.deployDns2.collectAsStateWithLifecycle(initialValue = "1.0.0.1") + val savedDns1 = serverSettings?.dns1 ?: "1.1.1.1" + val savedDns2 = serverSettings?.dns2 ?: "1.0.0.1" var dns1 by remember { mutableStateOf("1.1.1.1") } var dns2 by remember { mutableStateOf("1.0.0.1") } - val savedMainPass by settingsStore.deployMainPassword.collectAsStateWithLifecycle(initialValue = "") - val savedAdminId by settingsStore.deployAdminId.collectAsStateWithLifecycle(initialValue = "") - val savedBotToken by settingsStore.deployBotToken.collectAsStateWithLifecycle(initialValue = "") - val savedSshPort by settingsStore.deploySshPort.collectAsStateWithLifecycle(initialValue = "22") - val savedManualPorts by settingsStore.manualPortsEnabled.collectAsStateWithLifecycle(initialValue = false) - val savedServerDtlsPort by settingsStore.serverDtlsPort.collectAsStateWithLifecycle(initialValue = 56000) - val savedServerWgPort by settingsStore.serverWgPort.collectAsStateWithLifecycle(initialValue = 56001) - val savedListenPort by settingsStore.listenPort.collectAsStateWithLifecycle(initialValue = 9000) - val clientsSectionExpanded by remember(settingsStore) { + val savedMainPass = serverSettings?.mainPassword ?: "" + val savedAdminId = serverSettings?.adminId ?: "" + val savedBotToken = serverSettings?.botToken ?: "" + val savedSshPort = serverSettings?.sshPort ?: "22" + val savedManualPorts = serverSettings?.manualPorts ?: false + val savedServerDtlsPort = serverSettings?.dtlsPort ?: 56000 + val savedServerWgPort = serverSettings?.wgPort ?: 56001 + val savedListenPort = serverSettings?.localPort ?: 9000 + val storedClientsSectionExpanded by remember(settingsStore) { settingsStore.deployClientsSectionExpanded.map { it as Boolean? } }.collectAsStateWithLifecycle(initialValue = null) - val outboundSectionExpanded by remember(settingsStore) { + val storedOutboundSectionExpanded by remember(settingsStore) { settingsStore.deployOutboundSectionExpanded.map { it as Boolean? } }.collectAsStateWithLifecycle(initialValue = null) - val migrationSectionExpanded by remember(settingsStore) { + val storedMigrationSectionExpanded by remember(settingsStore) { settingsStore.deployMigrationSectionExpanded.map { it as Boolean? } }.collectAsStateWithLifecycle(initialValue = null) + + var clientsExpandedOverride by remember(activeProfile) { mutableStateOf(null) } + var outboundExpandedOverride by remember(activeProfile) { mutableStateOf(null) } + var migrationExpandedOverride by remember(activeProfile) { mutableStateOf(null) } + val clientsSectionExpanded = clientsExpandedOverride ?: storedClientsSectionExpanded + val outboundSectionExpanded = outboundExpandedOverride ?: storedOutboundSectionExpanded + val migrationSectionExpanded = migrationExpandedOverride ?: storedMigrationSectionExpanded + + suspend fun revealExpandedSection(sectionTop: () -> Float?) { + val top = sectionTop() ?: return + val viewportTop = deployViewportTopInWindow ?: return + val start = deployScrollState.value + val target = (start + top - viewportTop - topRevealOffsetPx).coerceAtLeast(0f) + // Follow the growing scroll range during expansion, starting on the first frame. + deployScrollState.scroll { + animate(0f, 1f, animationSpec = tween(300)) { progress, _ -> + val next = (start + (target - start) * progress) + .coerceIn(0f, deployScrollState.maxValue.toFloat()) + scrollBy(next - deployScrollState.value) + } + } + } + + LaunchedEffect(clientsSectionExpanded, revealClientsRequested) { + if (clientsSectionExpanded == true && revealClientsRequested) { + revealExpandedSection { clientsSectionTopInWindow } + revealClientsRequested = false + } + } + LaunchedEffect(outboundSectionExpanded, revealOutboundRequested) { + if (outboundSectionExpanded == true && revealOutboundRequested) { + revealExpandedSection { outboundSectionTopInWindow } + revealOutboundRequested = false + } + } + LaunchedEffect(migrationSectionExpanded, revealMigrationRequested) { + if (migrationSectionExpanded == true && revealMigrationRequested) { + revealExpandedSection { migrationSectionTopInWindow } + revealMigrationRequested = false + } + } val serverMigrationState by settingsStore.serverMigrationState.collectAsStateWithLifecycle(initialValue = null) - var showSecretsDialog by remember { mutableStateOf(false) } - var showSshKeyDialog by remember { mutableStateOf(false) } - var showSshAuthHelp by remember { mutableStateOf(false) } + var serverAction by rememberSaveable(activeProfile) { mutableStateOf("install") } + var handledInstallRequest by rememberSaveable { mutableIntStateOf(0) } + LaunchedEffect(openInstallRequest, openInstallProfile, activeProfile, visible) { + if (visible && (openInstallProfile == null || openInstallProfile == activeProfile) && openInstallRequest > handledInstallRequest) { + handledInstallRequest = openInstallRequest + serverAction = "install" + deployScrollState.scrollTo(0) + } + } + + var showServerAccessDialog by remember(activeProfile) { mutableStateOf(false) } + var showServerWorkflowHelp by remember(activeProfile) { mutableStateOf(false) } + var showSecretsDialog by remember(activeProfile) { mutableStateOf(false) } + var showSshKeyDialog by remember(activeProfile) { mutableStateOf(false) } + var showSshAuthHelp by remember(activeProfile) { mutableStateOf(false) } var showWireGuardExitSshKeyDialog by remember { mutableStateOf(false) } var showWireGuardExitSshHelp by remember { mutableStateOf(false) } var showUninstallDialog by remember { mutableStateOf(false) } - var pendingDeployRequest by remember { mutableStateOf(null) } + var pendingDeployRequest by remember(activeProfile) { mutableStateOf(null) } var pendingDeployImportRequest by remember { mutableStateOf(null) } var pendingDirectImportRequest by remember { mutableStateOf(null) } - var existingInstallInfo by remember { mutableStateOf(null) } + var pendingDeploySettings by remember(activeProfile) { + mutableStateOf?>(null) + } + var existingInstallInfo by remember(activeProfile) { mutableStateOf(null) } var isCheckingExistingInstall by remember { mutableStateOf(false) } + var rollbackResolutionBusy by remember { mutableStateOf(false) } + var rollbackResolutionMessage by rememberSaveable { mutableStateOf("") } var exportIncludeWgKeys by rememberSaveable { mutableStateOf(true) } var pendingExportBackup by remember { mutableStateOf(null) } var pendingExportDocument by remember { mutableStateOf(null) } @@ -1253,8 +1402,8 @@ fun DeployTab( var backupRetentionInput by rememberSaveable { mutableStateOf("14") } var pendingBackupDelete by remember { mutableStateOf(null) } var existingConnectBusy by remember { mutableStateOf(false) } - var existingConnectStatus by rememberSaveable { mutableStateOf("") } - var pendingExistingConnectionApply by remember { mutableStateOf(null) } + var existingConnectStatus by rememberSaveable(activeProfile) { mutableStateOf("") } + var pendingExistingConnectionApply by remember(activeProfile) { mutableStateOf(null) } var serverDiagnosticsBusy by remember { mutableStateOf(false) } var serverDiagnosticsReport by remember { mutableStateOf(null) } var serverDiagnosticsJob by remember { mutableStateOf(null) } @@ -1263,7 +1412,8 @@ fun DeployTab( var outboundBusy by remember { mutableStateOf(false) } var outboundProgressActive by remember { mutableStateOf(false) } var outboundActionTitle by remember { mutableStateOf("") } - var outboundStatus by rememberSaveable { mutableStateOf("") } + var outboundStatus by remember { mutableStateOf("") } + var outboundFeedback by remember { mutableStateOf(null) } var outboundStatusOwner by rememberSaveable { mutableStateOf(null) } var outboundSnapshot by remember { mutableStateOf(null) } var outboundSnapshotBusy by remember { mutableStateOf(false) } @@ -1334,18 +1484,22 @@ fun DeployTab( mutableStateOf(storedOutboundForms.forms.tunInterface) } - var showSuccessBanner by rememberSaveable { mutableStateOf(false) } - var successCountdown by rememberSaveable { mutableIntStateOf(5) } - - LaunchedEffect(showSuccessBanner) { - if (showSuccessBanner) { - while (successCountdown > 0) { - kotlinx.coroutines.delay(1000) - successCountdown-- - } - showSuccessBanner = false - } - } + val otherServerWindowOpen = serverAction != "install" || revealClientsRequested || revealOutboundRequested || revealMigrationRequested || + showServerAccessDialog || showServerWorkflowHelp || showSecretsDialog || + showSshKeyDialog || showSshAuthHelp || showWireGuardExitSshKeyDialog || showWireGuardExitSshHelp || + showUninstallDialog || showFirstServerSetup || outboundDialog != null || serverDiagnosticsReport != null || + existingInstallInfo != null || pendingExistingConnectionApply != null || pendingDeployImportRequest != null || + pendingDirectImportRequest != null || pendingBackupDelete != null || exportPasswordBackup != null || encryptedImportDocument != null + val completionNavigation = rememberServerInstallCompletionNavigation( + activeProfile, navigationRevision, visible, setupCompletion?.profileIndex, otherServerWindowOpen, onOpenTunnel, + ) + var showSuccessBanner by completionNavigation.showSuccessBanner + var successCountdown by completionNavigation.successCountdown + var successProfile by completionNavigation.successProfile + var firstInstallTunnelProfile by completionNavigation.firstInstallTunnelProfile + var firstInstallationProfile by completionNavigation.firstInstallationProfile + var firstInstallationNavigationRevision by completionNavigation.firstInstallationNavigationRevision + var firstInstallationNavigationCancelled by completionNavigation.firstInstallationNavigationCancelled val isDeploying by DeployManager.isDeploying.collectAsStateWithLifecycle() val deployProgress by DeployManager.deployProgress.collectAsStateWithLifecycle() @@ -1353,9 +1507,9 @@ fun DeployTab( val lastDeployResult by DeployManager.lastResult.collectAsStateWithLifecycle() val installedServerVersion by DeployManager.installedServerVersion.collectAsStateWithLifecycle() - LaunchedEffect(savedIp) { ip = savedIp } - LaunchedEffect(savedLogin) { login = savedLogin } - LaunchedEffect(savedPassword) { password = savedPassword } + LaunchedEffect(activeProfile, savedIp, showServerAccessDialog) { if (!showServerAccessDialog) ip = savedIp } + LaunchedEffect(activeProfile, savedLogin, showServerAccessDialog) { if (!showServerAccessDialog) login = savedLogin } + LaunchedEffect(activeProfile, savedPassword, showServerAccessDialog) { if (!showServerAccessDialog) password = savedPassword } LaunchedEffect(savedDns1) { dns1 = savedDns1 } LaunchedEffect(savedDns2) { dns2 = savedDns2 } LaunchedEffect(storedSshAuthMode) { @@ -1493,6 +1647,10 @@ fun DeployTab( } LaunchedEffect(activeProfile, outboundTargetKey) { serverDiagnosticsReport = null + serverDiagnosticsRunToken += 1L + serverDiagnosticsJob?.cancel() + serverDiagnosticsJob = null + serverDiagnosticsBusy = false } LaunchedEffect( activeProfile, @@ -1626,18 +1784,19 @@ fun DeployTab( } } + val ownerTunnelSnapshot by settingsStore.activeTunnelProfileContentUiSnapshot.collectAsStateWithLifecycle() fun currentOwnerProfile(): ServerAdminProfileInfo = buildOwnerProfile( vkHashes = savedVkHashes, secondaryVkHash = savedSecondaryVkHash, workersPerHash = savedWorkersPerHash, protocol = savedProtocol, - listenPort = savedListenPort, + listenPort = ownerTunnelSnapshot?.takeIf { it.profileIndex == activeProfile }?.listenPort ?: 9000, sni = savedSni, noDns = savedNoDns, vpnDnsSelectionId = savedVpnDns.selectionId, vpnDnsCustomServers = savedVpnDns.customServers, - dtlsPort = if (savedManualPorts) savedServerDtlsPort else 56000, - wgPort = if (savedManualPorts) savedServerWgPort else 56001, + dtlsPort = ownerTunnelSnapshot?.takeIf { it.profileIndex == activeProfile }?.let { if (it.manualPortsEnabled) it.serverDtlsPort else 56000 } ?: 56000, + wgPort = ownerTunnelSnapshot?.takeIf { it.profileIndex == activeProfile }?.let { if (it.manualPortsEnabled) it.serverWgPort else 56001 } ?: 56001, profileName = vpnProfileTransferName(activeProfile, profileNames) ) @@ -1676,7 +1835,7 @@ fun DeployTab( val target = backupAdminTarget if (target == null) { backupStatusMessage = if (savedMainPass.isBlank()) { - "Укажите главный пароль в разделе «Секреты»." + "Укажите главный пароль в разделе параметры сервера." } else { primarySshAccessIssue ?: "Проверьте SSH-доступ к серверу." } @@ -1790,7 +1949,8 @@ fun DeployTab( suspend fun applyExistingConnection( connection: ExistingServerConnection, - effectiveLogin: String, + profileIndex: Int, + target: OutboundSshTarget, profile: ServerAdminProfileInfo, source: OwnerProfileSource ) { @@ -1799,37 +1959,13 @@ fun DeployTab( listenPort = ports.third, ports = ports.asPortsSpec() ) - settingsStore.save( - peer = connection.host, - vkHashes = normalizedProfile.vkHashes, - secondaryVkHash = normalizedProfile.secondaryVkHash, - workersPerHash = normalizedProfile.workersPerHash, - protocol = normalizedProfile.protocol, - listenPort = normalizedProfile.listenPort, - sni = normalizedProfile.sni, - noDns = normalizedProfile.noDns + settingsStore.applyImportedServerConnection( + profileIndex, connection.host, connection.password, ports.first, ports.second, normalizedProfile, + ServerConnectionAccess(target.user, target.pass, target.port, target.privateKey, target.keyPassphrase, + if (target.allowPasswordAuthentication) "password" else "key", + connection.adminId, connection.botToken, connection.dns1, connection.dns2), ) - settingsStore.saveConnectionPassword(connection.password) - settingsStore.savePorts(ports.first, ports.second, ports.third) - settingsStore.saveManualPortsEnabled(ports != Triple(56000, 56001, 9000)) - settingsStore.saveDeploySecrets( - mainPass = savedMainPass, - adminId = connection.adminId, - botToken = connection.botToken, - sshPort = savedSshPort.ifBlank { "22" } - ) - settingsStore.saveDeploy(ip.trim(), effectiveLogin, password, savedSshPort.ifBlank { "22" }, connection.dns1, connection.dns2) - settingsStore.saveWdttLinkMode(false) - if (normalizedProfile.vpnDnsStored) { - settingsStore.saveVpnDnsSettings( - selectionId = normalizedProfile.vpnDnsSelectionId, - customServersRaw = normalizedProfile.vpnDnsCustomServers.joinToString(","), - profileIndex = activeProfile, - ) - } - vpnProfileRestorableName(normalizedProfile.profileName) - .takeIf { it.isNotBlank() } - ?.let { settingsStore.saveProfileName(activeProfile, it) } + if (currentActiveProfile != profileIndex) return existingConnectStatus = when (source) { OwnerProfileSource.Server -> "Готово: данные восстановлены с сервера в приложение. Сервер не изменялся. Адрес: ${connection.host}; порты: ${ports.first}, ${ports.second}, ${ports.third}." @@ -1838,10 +1974,19 @@ fun DeployTab( } fun launchDeploy(request: DeployRequest, mode: DeployMode) { + showSuccessBanner = false + firstInstallTunnelProfile = null val appContext = context.applicationContext val importPlan = selectedImportBackup?.let { ServerImportPlan(it, selectedImportMode) } + firstInstallationProfile = activeProfile.takeIf { mode == DeployMode.FreshInstall && importPlan == null } + firstInstallationNavigationRevision = navigationRevision.takeIf { firstInstallationProfile != null } + firstInstallationNavigationCancelled = false val outboundProfile = currentOutboundProfileForms() val deployProfile = activeProfile + val deployOwnerProfile = currentOwnerProfile().copy( + listenPort = request.localPort, + ports = Triple(request.dtlsPort, request.wgPort, request.localPort).asPortsSpec() + ) DeployManager.scope.launch { try { DeployManager.startDeploy() @@ -1873,7 +2018,9 @@ fun DeployTab( if (success) { settingsStore.markProfileServerMigrationComplete( profile = deployProfile, - level = latestServerMigrationLevel(BuildConfig.VERSION_CODE) + level = latestServerMigrationLevel(BuildConfig.VERSION_CODE), + host = request.host, + sshPort = request.sshPort, ) val restoredConnection = importPlan ?.takeIf { it.mode == ServerImportMode.Replace } @@ -1889,7 +2036,7 @@ fun DeployTab( ownerProfile = restoredConnection.adminProfile.copy(listenPort = restoredPorts.third) ) } - val ownerProfile = restoredConnection?.adminProfile ?: currentOwnerProfile() + val ownerProfile = restoredConnection?.adminProfile ?: deployOwnerProfile DeployManager.updateProgress( 0.97f, if (restoredConnection != null) { @@ -1934,6 +2081,14 @@ fun DeployTab( DeployManager.writeError("Outbound profile sync after deploy error: ${it.message}") TunnelManager.addDeployErrorLog("Профиль выходного IP после деплоя: ${friendlyDeployError(it, "сохранение")}") } + if (mode == DeployMode.FreshInstall && importPlan == null) { + settingsStore.saveServerSetup(deployProfile, request.host, request.user, request.pass, request.sshPort, + request.privateKey, request.keyPassphrase, if (request.allowPasswordAuthentication) "password" else "key", + request.mainPass, request.adminId, request.botToken, request.dns1, request.dns2, + request.dtlsPort, request.wgPort, request.localPort, completeFirstInstallation = true) + } else { + settingsStore.finishServerSetup(deployProfile) + } DeployManager.updateProgress(1f, "Готово!") kotlinx.coroutines.delay(DEPLOY_READY_HOLD_MS) DeployManager.stopDeploy("success") @@ -1941,8 +2096,11 @@ fun DeployTab( "Деплой успешно завершён. Серверная часть WDTT Plus " + "${DeployManager.installedServerVersion.value}, сервис активен." ) + successProfile = deployProfile + firstInstallTunnelProfile = null successCountdown = 5 - showSuccessBanner = true + // The initial installation first shows its one-time credentials; closing them starts the countdown. + showSuccessBanner = mode != DeployMode.FreshInstall || importPlan != null } } finally { try { appContext.startService(Intent(appContext, TunnelService::class.java).apply { action = "DEPLOY_STOP" }) } catch (_: Exception) {} @@ -1950,11 +2108,18 @@ fun DeployTab( } } - fun startDeployCheck(request: DeployRequest) { - val localOwnerProfile = currentOwnerProfile() + fun startDeployCheck(request: DeployRequest, requireExistingServer: Boolean = false) { + showSuccessBanner = false + firstInstallTunnelProfile = null + val checkProfile = activeProfile + val localOwnerProfile = currentOwnerProfile().copy( + listenPort = request.localPort, + ports = Triple(request.dtlsPort, request.wgPort, request.localPort).asPortsSpec() + ) val localOutboundProfile = currentOutboundProfileForms() + isCheckingExistingInstall = true + pendingDeploySettings = null scope.launch { - isCheckingExistingInstall = true try { var info = checkExistingInstall( host = request.host, @@ -1968,6 +2133,28 @@ fun DeployTab( port = request.sshPort, mainPassword = request.mainPass, ) + if (currentActiveProfile != checkProfile) return@launch + settingsStore.recordProfileServerInstallation(checkProfile, request.host, request.sshPort, info.hasInstalledServer) + if (info.updateRollbackState !is ServerUpdateRollbackState.None) { + val validation = when (val rollback = info.updateRollbackState) { + is ServerUpdateRollbackState.PreparedValid -> "prepared_valid" + is ServerUpdateRollbackState.PreparedCorrupted -> + "prepared_corrupted:${rollback.diagnostic}" + is ServerUpdateRollbackState.UnknownState -> + "unknown_state:${rollback.diagnostic}" + ServerUpdateRollbackState.None -> "none" + } + DeployManager.writeError( + "Server update rollback backup found; validation=$validation", + ) + TunnelManager.addDeployErrorLog( + "На сервере найдена страховочная копия обновления: $validation", + ) + pendingDeployRequest = request + existingInstallInfo = info + rollbackResolutionMessage = "" + return@launch + } if (info.hasAnyTrace) { val comparison = runCatching { compareDeployWithServer( @@ -1983,13 +2170,23 @@ fun DeployTab( checkError = friendlyDeployError(it, "сверка данных перед установкой") ) } + if (currentActiveProfile != checkProfile) return@launch + val currentOwner = currentOwnerProfile().copy(listenPort = request.localPort, + ports = Triple(request.dtlsPort, request.wgPort, request.localPort).asPortsSpec()) + check(currentOwner == localOwnerProfile && currentOutboundProfileForms() == localOutboundProfile) { + "Локальные настройки изменились. Повторите проверку сервера." + } + pendingDeploySettings = localOwnerProfile to localOutboundProfile info = info.copy(comparison = comparison) pendingDeployRequest = request existingInstallInfo = info + } else if (requireExistingServer) { + openSetup() } else { launchDeploy(request, DeployMode.FreshInstall) } } catch (e: Exception) { + if (currentActiveProfile != checkProfile) return@launch val friendly = friendlyDeployError(e, "проверка сервера") DeployManager.writeError("Pre-deploy check error: ${e.message}") TunnelManager.addDeployErrorLog("Проверка сервера перед деплоем: $friendly") @@ -2009,10 +2206,34 @@ fun DeployTab( } } + fun runRollbackResolution(action: ServerUpdateRollbackAction) { + val request = pendingDeployRequest ?: return + if (rollbackResolutionBusy) return + scope.launch { + rollbackResolutionBusy = true + rollbackResolutionMessage = "Выполняется безопасная проверка сервера..." + runCatching { resolveServerUpdateRollback(request, action) } + .onSuccess { message -> + rollbackResolutionMessage = message + TunnelManager.addDeploySuccessLog(message) + Toast.makeText(context, message, Toast.LENGTH_LONG).show() + pendingDeployRequest = null + existingInstallInfo = null + startDeployCheck(request) + } + .onFailure { error -> + val message = friendlyDeployError(error, "восстановление после обновления") + rollbackResolutionMessage = message + TunnelManager.addDeployErrorLog("Страховочная копия обновления: $message") + } + rollbackResolutionBusy = false + } + } + fun currentOutboundTarget(): OutboundSshTarget? { if (!primarySshAccessReady) { outboundStatus = primarySshAccessIssue - ?: "Проверьте доступ к серверу в верхнем блоке «Деплой»." + ?: "Проверьте доступ к серверу в настройках SSH." outboundStatusOwner = outboundDialog?.name return null } @@ -2036,10 +2257,13 @@ fun DeployTab( tunCandidatesBusy = true outboundStatus = "Ищу доступные TUN-интерфейсы на сервере..." outboundStatusOwner = OutboundDialog.TunInterface.name - scope.launch { + val capture = RemoteCommandCapture(listOf(target.pass, savedMainPass, localProxyPasswordInput, externalProxyPasswordInput, wireGuardExitPasswordInput)) + var feedbackCategory = RemoteLogCategory.Info + scope.launch(remoteCommandOutputCapture.asContextElement(capture)) { try { val candidates = discoverTunInterfaces(target) if (currentOutboundTargetKey != requestTargetKey) return@launch + if (candidates.isEmpty()) feedbackCategory = RemoteLogCategory.Warning tunCandidates = candidates outboundStatus = if (candidates.isEmpty()) { "Автоматически определить TUN-интерфейсы не удалось. Введите точное имя вручную." @@ -2048,11 +2272,17 @@ fun DeployTab( } outboundStatusOwner = OutboundDialog.TunInterface.name } catch (e: Exception) { + capture.append(e.message.orEmpty()) + feedbackCategory = RemoteLogCategory.Error if (currentOutboundTargetKey != requestTargetKey) return@launch tunCandidates = emptyList() - outboundStatus = "Не удалось получить список TUN-интерфейсов: ${friendlyDeployError(e, "поиск TUN-интерфейсов")}. Имя можно ввести вручную." + outboundStatus = "Не удалось получить список TUN-интерфейсов: ${outboundErrorSummary(capture.sanitize(friendlyDeployError(e, "поиск TUN-интерфейсов")))}. Имя можно ввести вручную." outboundStatusOwner = OutboundDialog.TunInterface.name } finally { + if (currentOutboundTargetKey == requestTargetKey) { + outboundStatus = capture.sanitize(outboundStatus) + outboundFeedback = OutboundActionFeedback(outboundStatus, feedbackCategory, capture.text()) + } if (currentOutboundTargetKey == requestTargetKey) tunCandidatesBusy = false } } @@ -2116,7 +2346,9 @@ fun DeployTab( outboundStatus = "Проверяю, какой выходной IP/прокси сейчас активен на сервере..." outboundStatusOwner = null } - scope.launch { + val capture = RemoteCommandCapture(listOf(target.pass, savedMainPass, localProxyPasswordInput, externalProxyPasswordInput, wireGuardExitPasswordInput)) + var feedbackCategory = RemoteLogCategory.Info + scope.launch(remoteCommandOutputCapture.asContextElement(capture)) { try { val snapshot = readOutboundServerSnapshot(context, target) val accepted = acceptOutboundSnapshot(requestTargetKey, snapshot) @@ -2125,13 +2357,19 @@ fun DeployTab( outboundStatusOwner = null } } catch (e: Exception) { + capture.append(e.message.orEmpty()) + feedbackCategory = RemoteLogCategory.Error recordOutboundCheckFailure(requestTargetKey, e) if (showStatus && currentOutboundTargetKey == requestTargetKey) { - outboundStatus = "Не удалось прочитать состояние выходного IP: ${friendlyDeployError(e, "выходной IP")}" + outboundStatus = "Не удалось прочитать состояние выходного IP: ${outboundErrorSummary(capture.sanitize(friendlyDeployError(e, "выходной IP")))}" outboundStatusOwner = null } DeployManager.writeError("Outbound state refresh failed: ${e.message}") } finally { + if (currentOutboundTargetKey == requestTargetKey && showStatus) { + outboundStatus = capture.sanitize(outboundStatus) + outboundFeedback = OutboundActionFeedback(outboundStatus, feedbackCategory, capture.text()) + } outboundSnapshotBusy = false DeployManager.updateProgress(0f, "") } @@ -2154,7 +2392,9 @@ fun DeployTab( DeployManager.updateProgress(0.02f, title) outboundStatus = "$title..." outboundStatusOwner = owner - scope.launch { + val capture = RemoteCommandCapture(listOf(target.pass, savedMainPass, localProxyPasswordInput, externalProxyPasswordInput, wireGuardExitPasswordInput)) + outboundFeedback = null + scope.launch(remoteCommandOutputCapture.asContextElement(capture)) { try { if (preflightRouteMode != null) { DeployManager.updateProgress(0.04f, "Проверяю текущий выход перед переключением...") @@ -2162,6 +2402,8 @@ fun DeployTab( if (!acceptOutboundSnapshot(requestTargetKey, before)) return@launch before.routeConflictMessage?.let { conflict -> outboundStatus = "Установка остановлена. $conflict" + outboundFeedback = OutboundActionFeedback(outboundStatus, RemoteLogCategory.Warning, capture.text()) + TunnelManager.addDeployMessageLog(outboundStatus, warning = true) outboundStatusOwner = owner return@launch } @@ -2177,15 +2419,27 @@ fun DeployTab( }.getOrNull() val afterWarning = afterSnapshot?.routeConflictMessage ?: afterSnapshot?.outboundModeMismatchWarning() - outboundStatus = listOfNotNull( + ?: if (afterSnapshot == null) "Действие завершено, но обновить состояние сервера не удалось. Повторите проверку." else null + val resultText = listOfNotNull( actionResult, afterWarning?.let { "Проверьте сервер: $it" } ).joinToString("\n") + if (capture.text().isBlank()) capture.append(actionResult) + val warning = afterWarning != null || actionResult.lineSequence().any { + classifyRemoteCommandLine(it).category == RemoteLogCategory.Warning + } + outboundStatus = outboundResultSummary(capture.sanitize(resultText)) + outboundFeedback = OutboundActionFeedback( + outboundStatus, if (warning) RemoteLogCategory.Warning else RemoteLogCategory.Info, capture.text() + ) outboundStatusOwner = owner + TunnelManager.addDeployMessageLog(outboundStatus, warning) onSuccess?.invoke() } catch (e: Exception) { - val friendly = friendlyDeployError(e, "выходной IP") - outboundStatus = "$title: $friendly" + val friendly = outboundErrorSummary(capture.sanitize(friendlyDeployError(e, "выходной IP"))) + capture.append(e.message.orEmpty()) + outboundStatus = friendly + outboundFeedback = OutboundActionFeedback(friendly, RemoteLogCategory.Error, capture.text()) outboundStatusOwner = owner DeployManager.writeError("Ошибка действия «$title»: $friendly") TunnelManager.addDeployErrorLog("$title: $friendly") @@ -2241,18 +2495,26 @@ fun DeployTab( outboundStatus = "Читаю настройки выходного IP и прокси с сервера..." outboundStatusOwner = null DeployManager.updateProgress(0.02f, "Читаю настройки выходного IP и прокси с сервера...") - scope.launch { + val capture = RemoteCommandCapture(listOf(target.pass, savedMainPass, localProxyPasswordInput, externalProxyPasswordInput, wireGuardExitPasswordInput)) + var feedbackCategory = RemoteLogCategory.Info + scope.launch(remoteCommandOutputCapture.asContextElement(capture)) { try { val snapshot = readOutboundServerSnapshot(context, target) if (!acceptOutboundSnapshot(requestTargetKey, snapshot)) return@launch applyOutboundSnapshot(snapshot) outboundStatus = outboundRestoreSummary(snapshot) } catch (e: Exception) { + capture.append(e.message.orEmpty()) + feedbackCategory = RemoteLogCategory.Error recordOutboundCheckFailure(requestTargetKey, e) - outboundStatus = "Не удалось прочитать настройки выходного IP с сервера: ${friendlyDeployError(e, "выходной IP")}" + outboundStatus = "Не удалось прочитать настройки выходного IP с сервера: ${outboundErrorSummary(capture.sanitize(friendlyDeployError(e, "выходной IP")))}" outboundStatusOwner = null DeployManager.writeError("Outbound profile restore failed: ${e.message}") } finally { + if (currentOutboundTargetKey == requestTargetKey) { + outboundStatus = capture.sanitize(outboundStatus) + outboundFeedback = OutboundActionFeedback(outboundStatus, feedbackCategory, capture.text()) + } outboundBusy = false outboundSnapshotBusy = false outboundProgressActive = false @@ -2275,7 +2537,7 @@ fun DeployTab( title = "SSH-доступ", status = "не готов", details = issue, - recommendation = "Исправьте адрес, порт или выбранный способ входа в блоке «Установка на сервер», затем повторите диагностику.", + recommendation = "Откройте SSH в «Деплой», исправьте адрес, порт или способ входа, затем повторите диагностику.", profileName = diagnosticsProfileName, profileIndex = diagnosticsProfile ) @@ -2296,18 +2558,32 @@ fun DeployTab( Toast.makeText(context, "Выполняется диагностика сервера", Toast.LENGTH_SHORT).show() serverDiagnosticsJob = scope.launch { val report = try { - collectServerDiagnostics( - target = target, - selectedAuthMode = selectedSshAuthMode, + withTimeout(95_000L) { + collectServerDiagnostics( + target = target, + selectedAuthMode = selectedSshAuthMode, + profileName = diagnosticsProfileName, + profileIndex = diagnosticsProfile, + expectedDtlsPort = savedServerDtlsPort, + expectedWgPort = savedServerWgPort, + expectedClientPort = savedListenPort, + connectionProfile = runCatching { settingsStore.tunnelProfileSnapshot(diagnosticsProfile) }.getOrNull(), + ) + } + } catch (error: TimeoutCancellationException) { + serverDiagnosticsErrorReport( + title = "Серверная диагностика", + status = "время ожидания истекло", + details = "Проверка не завершилась за 95 секунд. SSH-канал остановлен; состояние сервера не изменено.", + recommendation = "Повторите проверку при стабильном соединении. Если ошибка сохраняется, проверьте доступ к VPS без другого VPN.", profileName = diagnosticsProfileName, profileIndex = diagnosticsProfile, - expectedDtlsPort = savedServerDtlsPort, - expectedWgPort = savedServerWgPort, - expectedClientPort = savedListenPort ) + } catch (error: CancellationException) { + throw error } catch (error: Exception) { serverDiagnosticsErrorReport( - title = "SSH-подключение", + title = "Серверная диагностика", status = "не удалось", details = friendlyDeployError(error, "диагностика сервера"), recommendation = "Проверьте логин, пароль или SSH-ключ, порт SSH и доступность сервера из сети.", @@ -2399,9 +2675,9 @@ fun DeployTab( } } + Box(modifier = modifier.fillMaxSize()) { Column( - modifier = modifier - .fillMaxSize() + modifier = Modifier.fillMaxSize() .focusGroup() .padding(16.dp) .onGloballyPositioned { @@ -2412,11 +2688,15 @@ fun DeployTab( ) { Text( "Настройки сервера (${vpnProfileDisplayName(activeProfile, profileNames)})", + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp) + .wrapContentHeight(Alignment.CenterVertically) + .onGloballyPositioned { onProfileHeaderBounds(it.boundsInWindow()) }, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), color = MaterialTheme.colorScheme.onSurface ) if ( + serverMigrationState?.profileIndex == activeProfile && serverMigrationState?.profileUpdateRequired == true && hasManagedServerCredentials( host = savedIp, @@ -2450,7 +2730,7 @@ fun DeployTab( color = MaterialTheme.colorScheme.onTertiaryContainer ) Text( - "Для профиля «${vpnProfileDisplayName(activeProfile, profileNames)}» выполните установку сервера с сохранением данных. После успешной установки это напоминание исчезнет.", + "Для профиля «${vpnProfileDisplayName(activeProfile, profileNames)}» выберите «Установить» → «Обновить сервер» → «Обновить с сохранением». После успешного обновления это напоминание исчезнет.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onTertiaryContainer ) @@ -2462,223 +2742,119 @@ fun DeployTab( val importCanProvideMainPassword = selectedImportMode == ServerImportMode.Replace && selectedImportBackup?.mainPassword?.isNotBlank() == true val deploySecretsReady = savedMainPass.isNotBlank() || importCanProvideMainPassword - val deploySecretsMissing = !deploySecretsReady - val secretsDetails = buildList { - add("пароль") - if (savedDns1 != "1.1.1.1" || savedDns2 != "1.0.0.1") add("DNS") - if (savedSshPort.isNotBlank() && savedSshPort != "22") add("SSH") - if (savedManualPorts) add("порты") - }.joinToString(", ") - - // ═══ Установка сервера ═══ + val serverWorkflowBusy = isDeploying || isCheckingExistingInstall || serverDiagnosticsBusy || migrationBusy || existingConnectBusy || openingSetup || serverSettings == null || ownerTunnelSnapshot?.profileIndex != activeProfile + val selectedSettingsReady = if (serverAction == "install") deploySecretsReady else savedMainPass.isNotBlank() + val updateCandidate = offersServerUpdate(setupCompleted, primarySshAccessReady, savedMainPass) AppSectionCard( + modifier = Modifier.onGloballyPositioned { onProfileHeaderBoundary(it.boundsInWindow().top) }, contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp) + verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - "Установка на сервер", - style = MaterialTheme.typography.titleSmall, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onSurface - ) - val diagnosticsActionEnabled = !isDeploying && !isCheckingExistingInstall && !migrationBusy - IconButton( - onClick = { - if (serverDiagnosticsBusy) { - cancelServerDiagnostics() - } else { - runServerDiagnostics() - } - }, - enabled = serverDiagnosticsBusy || diagnosticsActionEnabled, - modifier = Modifier.size(40.dp), - colors = IconButtonDefaults.iconButtonColors( - contentColor = MaterialTheme.colorScheme.primary, - disabledContentColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.42f) - ) - ) { - if (serverDiagnosticsBusy) { - CircularProgressIndicator( - modifier = Modifier.size(18.dp), - strokeWidth = 2.dp, - color = MaterialTheme.colorScheme.primary - ) - } else { - Icon( - Icons.Default.Search, - contentDescription = "Диагностика сервера", - tint = MaterialTheme.colorScheme.primary, - modifier = Modifier.size(21.dp) - ) - } - } - } - - OutlinedTextField( - value = ip, - onValueChange = { - ip = it.filter { c -> !c.isWhitespace() } - if (ip.isBlank() || ip.isValidPublicHost()) { - scope.launch { settingsStore.saveDeploy(ip.trim(), login, password, savedSshPort, dns1, dns2) } - } - }, - label = { Text("IP сервера или домен (без порта)") }, - placeholder = { Text("site.ru или 1.2.3.4") }, - singleLine = true, - isError = ip.isNotBlank() && !isServerAddressValid, - supportingText = { - if (ip.isNotBlank() && !isServerAddressValid) { - Text("Укажите домен или IPv4 без https://, без / и без порта") - } - }, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - enabled = !isDeploying, - ) - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text("Способ входа на сервер", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold) - IconButton( - onClick = { showSshAuthHelp = true }, - modifier = Modifier.size(32.dp).remoteHelpFocus(), - ) { - Icon(Icons.AutoMirrored.Filled.HelpOutline, contentDescription = "Как работает вход по SSH", modifier = Modifier.size(20.dp)) - } - } - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - listOf("password" to "Пароль", "key" to "SSH-ключ").forEachIndexed { index, (mode, label) -> - SegmentedButton( - selected = selectedSshAuthMode == mode, - onClick = { - sshAuthMode = mode - existingConnectStatus = "" - scope.launch { settingsStore.saveDeploySshAuthMode(mode) } - }, - shape = SegmentedButtonDefaults.itemShape(index, 2), - enabled = !isDeploying, - icon = { - StableSegmentedButtonIcon(selected = selectedSshAuthMode == mode) - }, - ) { - Text( - label, - modifier = Modifier.fillMaxWidth(), - maxLines = 1, - textAlign = TextAlign.Center, - ) - } - } - } - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(12.dp) - ) { - OutlinedTextField( - value = login, - onValueChange = { - login = it.filter { c -> !c.isWhitespace() } - if (ip.isBlank() || ip.isValidPublicHost()) { - scope.launch { settingsStore.saveDeploy(ip.trim(), login, password, savedSshPort, dns1, dns2) } - } - }, - label = { Text("Логин") }, - placeholder = { Text("root") }, - singleLine = true, - visualTransformation = if (loginFocused) VisualTransformation.None else PasswordVisualTransformation(), - modifier = Modifier - .weight(1f) - .onFocusChanged { loginFocused = it.isFocused }, - shape = RoundedCornerShape(16.dp), - enabled = !isDeploying, - ) - OutlinedTextField( - value = password, - onValueChange = { - password = it - if (ip.isBlank() || ip.isValidPublicHost()) { - scope.launch { settingsStore.saveDeploy(ip.trim(), login, password, savedSshPort, dns1, dns2) } - } - }, - label = { Text(if (selectedSshAuthMode == "key") "Пароль sudo" else "Пароль SSH") }, - placeholder = { Text(if (selectedSshAuthMode == "key") "необязательно" else "password") }, - singleLine = true, - visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(), - modifier = Modifier - .weight(1f) - .onFocusChanged { passwordFocused = it.isFocused }, - shape = RoundedCornerShape(16.dp), - enabled = !isDeploying, - ) - } - - if (selectedSshAuthMode == "key") { - OutlinedButton( - onClick = { showSshKeyDialog = true }, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - colors = ButtonDefaults.outlinedButtonColors( - containerColor = if (!hasSshAuthentication) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.surface, - contentColor = if (!hasSshAuthentication) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onSurface - ), - border = BorderStroke( - 1.dp, - if (!hasSshAuthentication) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f) - ) - ) { - Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(8.dp)) + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Text( - when { - savedSshPrivateKey.isNotBlank() && password.isNotBlank() -> "SSH-ключ добавлен · пароль sudo указан" - savedSshPrivateKey.isNotBlank() -> "SSH-ключ добавлен" - else -> "Добавить приватный SSH-ключ" - }, - modifier = Modifier.weight(1f), - fontWeight = FontWeight.SemiBold + if (serverAction == "install") "Установка на сервер" else "Подключение к серверу", + modifier = Modifier.weight(1f, fill = false), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, ) + HintIconButton(hint = "Установка и подключение: справка", onClick = { showServerWorkflowHelp = true }, modifier = Modifier.size(36.dp).remoteHelpFocus()) { + Icon(Icons.AutoMirrored.Filled.HelpOutline, "Установка и подключение: справка", Modifier.size(20.dp)) + } + } + CheckActionIcon( + checking = serverDiagnosticsBusy, + enabled = serverDiagnosticsBusy || !serverWorkflowBusy, + idleIcon = Icons.Default.Search, + description = "Проверить сервер", + cancelDescription = "Остановить проверку сервера", + onClick = { if (serverDiagnosticsBusy) cancelServerDiagnostics() else runServerDiagnostics() }, + ) + HintIconButton(hint = "Удаление сервера: открыть подтверждение", + onClick = { showUninstallDialog = true }, + enabled = !serverWorkflowBusy && primarySshAccessReady, + modifier = Modifier.size(40.dp).remoteIconButtonFocus(enabled = !serverWorkflowBusy && primarySshAccessReady), + ) { + Icon(Icons.Default.Delete, "Удаление сервера: открыть подтверждение", Modifier.size(20.dp)) } } - if (primarySshPort !in 1..65535) { - InlineActionMessage("Откройте «Секреты» и укажите корректный SSH-порт от 1 до 65535.") - } - - OutlinedButton( - onClick = { showSecretsDialog = true }, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - colors = ButtonDefaults.outlinedButtonColors( - containerColor = if (deploySecretsMissing) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.surface, - contentColor = if (deploySecretsMissing) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onSurface - ), - border = BorderStroke( - 1.dp, - if (deploySecretsMissing) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f) - ) - ) { - Icon(Icons.Default.Key, null, Modifier.size(18.dp)) - Spacer(Modifier.width(8.dp)) + if (serverDiagnosticsBusy) { Text( - "Секреты ($secretsDetails)", - modifier = Modifier.weight(1f), - fontWeight = FontWeight.SemiBold + "Проверяю VPS. Обычно это занимает до минуты; проверка остановится через 95 секунд. Чтобы отменить её раньше, нажмите ×.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - - Row( - modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min), - horizontalArrangement = Arrangement.spacedBy(12.dp) - ) { - Button( + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { + listOf("install" to "Установить", "connect" to "Подключить").forEachIndexed { index, (mode, label) -> + SegmentedButton( + selected = serverAction == mode, + onClick = { serverAction = mode }, + enabled = !serverWorkflowBusy, + shape = SegmentedButtonDefaults.itemShape(index, 2), + icon = { StableSegmentedButtonIcon(selected = serverAction == mode) }, + ) { + Text(label, maxLines = 1, textAlign = TextAlign.Center) + } + } + } + Text( + if (serverAction == "install") "Установка или обновление WDTT на своём сервере." + else "Получение настроек готового сервера без его изменения.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(ip.ifBlank { "Сервер не указан" }, style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text( + if (primarySshAccessReady) "SSH · ${if (selectedSshAuthMode == "key") "ключ" else "пароль"} · порт $primarySshPort" + else "Нужны настройки SSH", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + ServerSetupIcon( + icon = Icons.Default.Key, label = "SSH", description = "Доступ к серверу", + needsAttention = !primarySshAccessReady, enabled = !serverWorkflowBusy, + onClick = { showServerAccessDialog = true }, + ) + ServerSetupIcon( + icon = Icons.Default.Settings, label = "Параметры", + description = if (serverAction == "install") "Параметры установки" else "Главный пароль администратора", + needsAttention = !selectedSettingsReady, enabled = !serverWorkflowBusy, + onClick = { showSecretsDialog = true }, + ) + } + if ((!primarySshAccessReady || !selectedSettingsReady) && (setupCompleted || serverAction == "connect" || selectedImportBackup != null)) { + Text( + when { + !primarySshAccessReady -> primarySshAccessIssue ?: "Заполните настройки SSH." + serverAction == "install" -> "Укажите главный пароль в параметрах установки." + else -> "Укажите главный пароль администратора в параметрах подключения." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + if (serverAction == "install") { + if (setupOpenError.isNotBlank()) InlineActionMessage(setupOpenError) + if (!updateCandidate && selectedImportBackup == null) { + Button(onClick = { openSetup() }, enabled = !serverWorkflowBusy, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), shape = RoundedCornerShape(16.dp)) { + Text( + if (ip.isBlank() && savedIp.isBlank() && savedPassword.isBlank() && + savedSshPrivateKey.isBlank() && savedPeer.isBlank() && + savedConnectionPassword.isBlank() && savedVkHashes.isBlank() && + savedMainPass.isBlank() && savedAdminId.isBlank() && savedBotToken.isBlank() + ) "Установка сервера" else "Настроить сервер", + fontWeight = FontWeight.Bold, + ) + } + Text("Мастер поможет установить WDTT и проверит, есть ли на VPS прежние данные. Готовый сервер можно подключить кнопкой «Подключить» выше.", style = MaterialTheme.typography.bodySmall) + } else Button( onClick = { if (!primarySshAccessReady || !deploySecretsReady) return@Button val effectiveLogin = if (login.isBlank()) "root" else login @@ -2709,13 +2885,13 @@ fun DeployTab( if (selectedImportBackup != null) { pendingDeployImportRequest = request } else { - startDeployCheck(request) + startDeployCheck(request, requireExistingServer = true) } }, - modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 50.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), shape = RoundedCornerShape(16.dp), colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary), - enabled = !isDeploying && !isCheckingExistingInstall && !migrationBusy && primarySshAccessReady && deploySecretsReady, + enabled = !serverWorkflowBusy && primarySshAccessReady && deploySecretsReady, contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) ) { if (isDeploying || isCheckingExistingInstall) { @@ -2728,155 +2904,362 @@ fun DeployTab( when { isDeploying -> "Установка" isCheckingExistingInstall -> "Проверка..." - else -> "Установить" + else -> if (selectedImportBackup != null) "Установить" else "Обновить сервер" }, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center ) } - - Button( - onClick = { - if (!primarySshAccessReady) return@Button - showUninstallDialog = true - }, - modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 50.dp), - shape = RoundedCornerShape(16.dp), - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.error, - contentColor = MaterialTheme.colorScheme.onError - ), - enabled = !isDeploying && primarySshAccessReady, - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) - ) { - Icon(Icons.Default.Delete, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text( - "Удалить", - fontWeight = FontWeight.Bold, - textAlign = TextAlign.Center + if (updateCandidate && selectedImportBackup == null && !serverWorkflowBusy) { + TextButton(onClick = { openSetup() }, modifier = Modifier.fillMaxWidth()) { + Text("Изменить настройки") + } + } + if (isCheckingExistingInstall || (isDeploying && !migrationBusy)) { + DeployProgressPanel( + title = if (isCheckingExistingInstall) "Проверяю сервер перед установкой..." else currentStep, + progress = animatedProgress, + determinate = !isCheckingExistingInstall ) } - } - if (isCheckingExistingInstall || (isDeploying && !migrationBusy)) { - DeployProgressPanel( - title = if (isCheckingExistingInstall) "Проверяю сервер перед установкой..." else currentStep, - progress = animatedProgress, - determinate = !isCheckingExistingInstall - ) - } + if (!isDeploying && + !isCheckingExistingInstall && + lastDeployResult.isNotBlank() && + !lastDeployResult.equals("success", ignoreCase = true) + ) { + DeployResultPanel( + result = lastDeployResult, + lastStep = currentStep + ) + } - if (!isDeploying && - !isCheckingExistingInstall && - lastDeployResult.isNotBlank() && - !lastDeployResult.equals("success", ignoreCase = true) - ) { - DeployResultPanel( - result = lastDeployResult, - lastStep = currentStep - ) - } - - if (showSuccessBanner) { - DeploySuccessBanner( - successCountdown = successCountdown, - serverVersion = installedServerVersion - ) + if (showSuccessBanner && successProfile == activeProfile) { + DeploySuccessBanner( + successCountdown = successCountdown, + serverVersion = installedServerVersion, + openTunnelAfterCountdown = firstInstallTunnelProfile == activeProfile + ) + } + } else { + Button( + onClick = { + if (!primarySshAccessReady) { + existingConnectStatus = primarySshAccessIssue + ?: "Проверьте доступ к серверу в настройках SSH." + return@Button + } + if (savedMainPass.isBlank()) { + existingConnectStatus = "Укажите главный пароль администратора в параметрах сервера, затем повторите подключение." + return@Button + } + val connectProfile = activeProfile + val target = OutboundSshTarget(ip.trim(), login.ifBlank { "root" }, sshCredentials.password, + sshCredentials.privateKey, sshCredentials.privateKeyPassphrase, sshCredentials.allowPasswordAuthentication, + primarySshPort, savedMainPass) + val localProfile = currentOwnerProfile() + val localPeer = savedPeer + val localPassword = savedConnectionPassword + val localAdminId = savedAdminId + val localBotToken = savedBotToken + val localDns1 = dns1 + val localDns2 = dns2 + existingConnectBusy = true + existingConnectStatus = "Проверяю главный пароль и читаю настройки сервера..." + scope.launch { + try { + val connection = readExistingServerConnection( + host = target.host, + user = target.user, + credentials = target.credentials, + port = target.port, + adminMainPassword = target.mainPassword + ) + if (currentActiveProfile != connectProfile) return@launch + val serverProfile = connection.adminProfile + val diffLines = existingConnectionDiffLines( + connection = connection, + localPeer = localPeer, + localConnectionPassword = localPassword, + localAdminId = localAdminId, + localBotToken = localBotToken, + localDns1 = localDns1, + localDns2 = localDns2, + localProfile = localProfile + ) + if (diffLines.isNotEmpty()) { + pendingExistingConnectionApply = PendingExistingConnectionApply( + connection = connection, + profileIndex = connectProfile, + target = target, + localProfile = localProfile, + serverProfile = serverProfile, + diffLines = diffLines + ) + existingConnectStatus = "Данные сервера отличаются от локальных полей. Проверьте изменения перед восстановлением." + } else { + val profile = if (serverProfile.hasSavedFields) serverProfile else localProfile + val source = if (serverProfile.hasSavedFields) OwnerProfileSource.Server else OwnerProfileSource.LocalOnly + applyExistingConnection(connection, connectProfile, target, profile, source) + } + } catch (e: Exception) { + if (currentActiveProfile != connectProfile) return@launch + existingConnectStatus = "Ошибка подключения к готовому серверу: ${friendlyDeployError(e, "подключение")}" + DeployManager.writeError("Existing server connect error: ${e.message}") + } finally { + existingConnectBusy = false + } + } + }, + enabled = !serverWorkflowBusy && primarySshAccessReady && savedMainPass.isNotBlank(), + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + if (existingConnectBusy) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + } else { + Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) + } + Spacer(Modifier.width(8.dp)) + Text("Подключиться", fontWeight = FontWeight.SemiBold) + } + if (existingConnectStatus.isNotBlank()) { + InlineActionMessage(existingConnectStatus) + } } } - AppSectionCard( - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp) - ) { - Text( - "Подключение к готовому серверу", - style = MaterialTheme.typography.titleSmall, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onSurface - ) - Text( - "Подключение без установки работает только в направлении сервер → приложение: WDTT Plus проверяет главный пароль, показывает отличия и после подтверждения заполняет локальные поля. На сервер ничего не записывается, пользовательские доступы не меняются.\n\nНаправление приложение → сервер используется при установке с сохранением данных или с нуля. Настройки выходного IP восстанавливаются отдельно кнопкой «Загрузить настройки» в соответствующем блоке.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - OutlinedButton( - onClick = { - if (!primarySshAccessReady) { - existingConnectStatus = primarySshAccessIssue - ?: "Проверьте доступ к серверу в верхнем блоке «Деплой»." - return@OutlinedButton + if (showServerAccessDialog) { + SettingsDialogLayout( + title = "Доступ к серверу", + onDismiss = { showServerAccessDialog = false }, + onHelp = { showSshAuthHelp = true }, + ) { + var loginFocused by remember { mutableStateOf(false) } + var passwordFocused by remember { mutableStateOf(false) } + var sshPortInput by rememberSaveable(activeProfile) { mutableStateOf(savedSshPort.ifBlank { "22" }) } + val accessProfile = activeProfile + fun saveAccess() { + val host = ip.trim(); val user = login; val pass = password; val port = sshPortInput + val previousSave = accessSaveJob + accessSaveJob = scope.launch { + previousSave?.join() + settingsStore.saveServerAccess(accessProfile, host, user, pass, port) } - if (savedMainPass.isBlank()) { - existingConnectStatus = "Укажите главный пароль администратора в «Секретах», затем повторите подключение." - return@OutlinedButton - } - val effectiveLogin = if (login.isBlank()) "root" else login - existingConnectBusy = true - existingConnectStatus = "Проверяю главный пароль и читаю настройки сервера..." - scope.launch { - try { - val connection = readExistingServerConnection( - host = ip.trim(), - user = effectiveLogin, - credentials = sshCredentials, - port = primarySshPort, - adminMainPassword = savedMainPass + } + Text("Настройки сохраняются сразу и используются для установки, подключения и управления сервером.", + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + OutlinedTextField( + value = ip, + onValueChange = { + ip = it.filter { c -> !c.isWhitespace() } + saveAccess() + }, + label = { Text("IP сервера или домен (без порта)") }, + placeholder = { Text("site.ru или 1.2.3.4") }, + singleLine = true, + isError = ip.isNotBlank() && !isServerAddressValid, + supportingText = { + if (ip.isNotBlank() && !isServerAddressValid) { + Text("Укажите домен или IPv4 без https://, без / и без порта") + } + }, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + enabled = !serverWorkflowBusy, + ) + + Text("Способ входа", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold) + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + listOf("password" to "Пароль", "key" to "SSH-ключ").forEachIndexed { index, (mode, label) -> + SegmentedButton( + selected = selectedSshAuthMode == mode, + onClick = { + sshAuthMode = mode + existingConnectStatus = "" + val previousSave = accessSaveJob + accessSaveJob = scope.launch { previousSave?.join(); settingsStore.saveDeploySshAuthMode(mode, accessProfile) } + }, + shape = SegmentedButtonDefaults.itemShape(index, 2), + enabled = !serverWorkflowBusy, + icon = { + StableSegmentedButtonIcon(selected = selectedSshAuthMode == mode) + }, + ) { + Text( + label, + modifier = Modifier.fillMaxWidth(), + maxLines = 1, + textAlign = TextAlign.Center, ) - val localProfile = currentOwnerProfile() - val serverProfile = connection.adminProfile - val diffLines = existingConnectionDiffLines( - connection = connection, - localPeer = savedPeer, - localConnectionPassword = savedConnectionPassword, - localAdminId = savedAdminId, - localBotToken = savedBotToken, - localDns1 = dns1, - localDns2 = dns2, - localProfile = localProfile - ) - if (diffLines.isNotEmpty()) { - pendingExistingConnectionApply = PendingExistingConnectionApply( - connection = connection, - effectiveLogin = effectiveLogin, - localProfile = localProfile, - serverProfile = serverProfile, - diffLines = diffLines - ) - existingConnectStatus = "Данные сервера отличаются от локальных полей. Проверьте изменения перед восстановлением." - } else { - val profile = if (serverProfile.hasSavedFields) serverProfile else localProfile - val source = if (serverProfile.hasSavedFields) OwnerProfileSource.Server else OwnerProfileSource.LocalOnly - applyExistingConnection(connection, effectiveLogin, profile, source) - } - } catch (e: Exception) { - existingConnectStatus = "Ошибка подключения к готовому серверу: ${friendlyDeployError(e, "подключение")}" - DeployManager.writeError("Existing server connect error: ${e.message}") - } finally { - existingConnectBusy = false } } - }, - enabled = !isDeploying && !isCheckingExistingInstall && !migrationBusy && !existingConnectBusy, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp) - ) { - if (existingConnectBusy) { - CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) - } else { - Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) } - Spacer(Modifier.width(8.dp)) - Text("Подключиться (без установки)", fontWeight = FontWeight.SemiBold) - } - if (existingConnectStatus.isNotBlank()) { - InlineActionMessage(existingConnectStatus) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + OutlinedTextField( + value = login, + onValueChange = { + login = it.filter { c -> !c.isWhitespace() } + saveAccess() + }, + label = { Text("Логин") }, + placeholder = { Text("root") }, + singleLine = true, + visualTransformation = if (loginFocused) VisualTransformation.None else PasswordVisualTransformation(), + modifier = Modifier + .weight(1f) + .onFocusChanged { loginFocused = it.isFocused }, + shape = RoundedCornerShape(16.dp), + enabled = !serverWorkflowBusy, + ) + OutlinedTextField( + value = password, + onValueChange = { + password = it + saveAccess() + }, + label = { Text(if (selectedSshAuthMode == "key") "Пароль sudo" else "Пароль SSH") }, + placeholder = { Text(if (selectedSshAuthMode == "key") "необязательно" else "password") }, + singleLine = true, + visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(), + modifier = Modifier + .weight(1f) + .onFocusChanged { passwordFocused = it.isFocused }, + shape = RoundedCornerShape(16.dp), + enabled = !serverWorkflowBusy, + ) + } + + if (selectedSshAuthMode == "key") { + OutlinedButton( + onClick = { showSshKeyDialog = true }, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (!hasSshAuthentication) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.surface, + contentColor = if (!hasSshAuthentication) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onSurface + ), + border = BorderStroke( + 1.dp, + if (!hasSshAuthentication) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f) + ) + ) { + Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text( + when { + savedSshPrivateKey.isNotBlank() && password.isNotBlank() -> "SSH-ключ добавлен · пароль sudo указан" + savedSshPrivateKey.isNotBlank() -> "SSH-ключ добавлен" + else -> "Добавить приватный SSH-ключ" + }, + modifier = Modifier.weight(1f), + fontWeight = FontWeight.SemiBold + ) + } + } + + OutlinedTextField( + value = sshPortInput, + onValueChange = { value -> + sshPortInput = value.filter(Char::isDigit).take(5) + saveAccess() + }, + label = { Text("Порт SSH") }, singleLine = true, + enabled = !serverWorkflowBusy, + placeholder = { Text("22") }, + isError = sshPortInput.isNotBlank() && (sshPortInput.toIntOrNull() ?: 0) !in 1..65535, + modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), + keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number), + ) + primarySshAccessIssue?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) } } } + if (showFirstServerSetup && visible) { + val setupProfile = activeProfile + var reviewedLocalSettings by remember(setupProfile) { + mutableStateOf?>(null) + } + FirstServerSetupDialog( + initial = checkNotNull(setupInitial), + onDismiss = { showFirstServerSetup = false }, + onProbe = { draft -> + check(currentActiveProfile == setupProfile) { "Выбран другой профиль. Откройте настройку заново." } + val info = checkExistingInstall(draft.host.trim(), draft.user.ifBlank { "root" }, + sshCredentialsForMode(draft.authMode, draft.sshPassword, draft.privateKey, draft.keyPassphrase), + draft.sshPort.ifBlank { "22" }.toInt(), "") + check(currentActiveProfile == setupProfile) { "Выбран другой профиль. Откройте настройку заново." } + settingsStore.recordProfileServerInstallation(setupProfile, draft.host, draft.sshPort.ifBlank { "22" }.toInt(), info.hasInstalledServer) + classifyFirstServerSetup(info.hasAnyTrace, existingInstallOwnershipFromFlags( + info.standaloneManaged, info.androidDeployManaged, info.legacyAndroidDeployCandidate, + info.preservedAndroidData, info.incompleteAndroidDeployCandidate), + info.updateRollbackState !is ServerUpdateRollbackState.None) + ?: error("Найдены компоненты WDTT неизвестного происхождения. Автоматическая установка заблокирована. Проверьте сервер по значку лупы; готовый сервер можно подключить без установки.") + }, + onReview = { draft, kind -> + check(currentActiveProfile == setupProfile) { "Выбран другой профиль. Откройте настройку заново." } + val request = draft.request() + val localSettings = currentOwnerProfile() to currentOutboundProfileForms() + reviewedLocalSettings = null + val info = checkExistingInstall(request.host, request.user, + SshCredentials(request.pass, request.privateKey, request.keyPassphrase, request.allowPasswordAuthentication), + request.sshPort, request.mainPass) + val currentKind = classifyFirstServerSetup(info.hasAnyTrace, existingInstallOwnershipFromFlags( + info.standaloneManaged, info.androidDeployManaged, info.legacyAndroidDeployCandidate, + info.preservedAndroidData, info.incompleteAndroidDeployCandidate), + info.updateRollbackState !is ServerUpdateRollbackState.None) + check(currentActiveProfile == setupProfile) { "Выбран другой профиль. Откройте настройку заново." } + check(currentKind == kind) { "Состояние сервера изменилось. Вернитесь к шагу «Доступ» и проверьте VPS снова." } + settingsStore.recordProfileServerInstallation(setupProfile, request.host, request.sshPort, info.hasInstalledServer) + if (kind in setOf(ServerSetupKind.FRESH, ServerSetupKind.STANDALONE, ServerSetupKind.RECOVERY)) { + reviewedLocalSettings = localSettings + ServerSetupReview() + } else { + val ownerProfile = localSettings.first.copy( + listenPort = request.localPort, + ports = Triple(request.dtlsPort, request.wgPort, request.localPort).asPortsSpec() + ) + val comparison = compareDeployWithServer(context, request, ownerProfile, + localSettings.second, info.accessDbExists) + check(currentActiveProfile == setupProfile) { "Выбран другой профиль. Откройте настройку заново." } + check(comparison.checkError == null) { + "Не удалось сравнить настройки с сервером: ${comparison.checkError}. Повторите проверку перед установкой." + } + check(localSettings == (currentOwnerProfile() to currentOutboundProfileForms())) { + "Локальные настройки изменились. Повторите сравнение." + } + reviewedLocalSettings = localSettings + ServerSetupReview(comparison.overwriteLines, comparison.notes) + } + }, + onInstall = { draft, kind -> + check(reviewedLocalSettings == (currentOwnerProfile() to currentOutboundProfileForms())) { + "Локальные настройки изменились. Повторите сравнение." + } + check(currentActiveProfile == setupProfile) { "Выбран другой профиль. Откройте настройку заново." } + val request = draft.request() + settingsStore.saveServerSetup(setupProfile, request.host, request.user, draft.sshPassword, request.sshPort, + draft.privateKey, draft.keyPassphrase, draft.authMode, request.mainPass, + request.adminId, request.botToken, request.dns1, request.dns2, + request.dtlsPort, request.wgPort, request.localPort) + check(currentActiveProfile == setupProfile) { "Выбран другой профиль. Настройки сохранены в исходном профиле; установка не запущена." } + ip = request.host; login = request.user; password = draft.sshPassword + dns1 = request.dns1; dns2 = request.dns2; sshAuthMode = draft.authMode + showFirstServerSetup = false + if (kind == ServerSetupKind.STANDALONE) serverAction = "connect" + else startDeployCheck(request) + }, + ) + } + ServerSetupCompletionSection(settingsStore, setupCompletion, activeProfile, visible, + isDeploying, completionNavigation, otherServerWindowOpen) + if (showServerWorkflowHelp) ServerWorkflowHelpDialog { showServerWorkflowHelp = false } pendingExistingConnectionApply?.let { pending -> - AlertDialog( + BoundedAlertDialog( onDismissRequest = { if (!existingConnectBusy) { pendingExistingConnectionApply = null @@ -2922,6 +3305,7 @@ fun DeployTab( existingConnectStatus = "Восстанавливаю данные с сервера в приложение..." scope.launch { try { + check(currentActiveProfile == selected.profileIndex) { "Выбран другой профиль. Повторите подключение." } val source = if (selected.serverProfile.hasSavedFields) { OwnerProfileSource.Server } else { @@ -2929,7 +3313,8 @@ fun DeployTab( } applyExistingConnection( connection = selected.connection, - effectiveLogin = selected.effectiveLogin, + profileIndex = selected.profileIndex, + target = selected.target, profile = if (selected.serverProfile.hasSavedFields) selected.serverProfile else selected.localProfile, source = source ) @@ -2963,15 +3348,16 @@ fun DeployTab( enabled = visible && !isDeploying && !isCheckingExistingInstall && !migrationBusy && !outboundBusy, hostValid = isServerAddressValid, expanded = clientsExpanded, - modifier = Modifier.onGloballyPositioned { clientsSectionY = it.positionInParent().y }, + modifier = Modifier.onGloballyPositioned { + clientsSectionTopInWindow = it.boundsInWindow().top + }, onExpandedChange = { expanded -> + clientsExpandedOverride = expanded + revealClientsRequested = expanded scope.launch { settingsStore.saveDeployClientsSectionExpanded(expanded) } }, onExpanded = { - scope.launch { - kotlinx.coroutines.delay(80) - deployScrollState.animateScrollTo((clientsSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0)) - } + revealClientsRequested = true } ) } @@ -2984,21 +3370,20 @@ fun DeployTab( lastCheckAttemptAt = outboundLastCheckAttemptAt, lastCheckError = outboundLastCheckError, status = if (outboundDialog == null && outboundStatusOwner == null) outboundStatus else "", + feedback = outboundFeedback, actionTitle = outboundActionTitle, accessIssue = primarySshAccessIssue, enabled = !isDeploying && !migrationBusy && !outboundBusy && !outboundSnapshotBusy, directEnabled = canReturnDirect(outboundSnapshot), expanded = outboundExpanded, - modifier = Modifier.onGloballyPositioned { outboundSectionY = it.positionInParent().y }, + modifier = Modifier.onGloballyPositioned { + outboundSectionTopInWindow = it.boundsInWindow().top + }, onToggleExpanded = { val willExpand = !outboundExpanded + outboundExpandedOverride = willExpand + revealOutboundRequested = willExpand scope.launch { settingsStore.saveDeployOutboundSectionExpanded(willExpand) } - if (willExpand) { - scope.launch { - kotlinx.coroutines.delay(80) - deployScrollState.animateScrollTo((outboundSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0)) - } - } }, onOpen = { openOutboundDialog(it) }, onRestore = { restoreOutboundFromServer() }, @@ -3013,6 +3398,7 @@ fun DeployTab( OutboundDialog.LocalProxy -> LocalProxyDialog( busy = outboundBusy, status = dialogStatus(OutboundDialog.LocalProxy), + feedback = outboundFeedback, actionTitle = outboundActionTitle, progressTitle = if (outboundProgressActive) currentStep else "", progress = deployProgress, @@ -3069,6 +3455,7 @@ fun DeployTab( OutboundDialog.ExternalProxy -> ExternalProxyDialog( busy = outboundBusy, status = dialogStatus(OutboundDialog.ExternalProxy), + feedback = outboundFeedback, actionTitle = outboundActionTitle, progressTitle = if (outboundProgressActive) currentStep else "", progress = deployProgress, @@ -3125,6 +3512,7 @@ fun DeployTab( busy = outboundBusy, candidatesBusy = tunCandidatesBusy, status = dialogStatus(OutboundDialog.TunInterface), + feedback = outboundFeedback, actionTitle = outboundActionTitle, progressTitle = if (outboundProgressActive) currentStep else "", progress = deployProgress, @@ -3178,6 +3566,7 @@ fun DeployTab( OutboundDialog.WireGuardVps -> WireGuardExitVpsDialog( busy = outboundBusy, status = dialogStatus(OutboundDialog.WireGuardVps), + feedback = outboundFeedback, actionTitle = outboundActionTitle, progressTitle = if (outboundProgressActive) currentStep else "", progress = deployProgress, @@ -3274,6 +3663,7 @@ fun DeployTab( OutboundDialog.FreeWarp -> FreeWarpDialog( busy = outboundBusy, status = dialogStatus(OutboundDialog.FreeWarp), + feedback = outboundFeedback, actionTitle = outboundActionTitle, progressTitle = if (outboundProgressActive) currentStep else "", progress = deployProgress, @@ -3326,6 +3716,7 @@ fun DeployTab( OutboundDialog.ImportedWireGuard -> ImportedWireGuardDialog( busy = outboundBusy, status = dialogStatus(OutboundDialog.ImportedWireGuard), + feedback = outboundFeedback, actionTitle = outboundActionTitle, progressTitle = if (outboundProgressActive) currentStep else "", progress = deployProgress, @@ -3377,6 +3768,7 @@ fun DeployTab( OutboundDialog.Diagnostics -> OutboundDiagnosticsDialog( busy = outboundBusy, status = dialogStatus(OutboundDialog.Diagnostics), + feedback = outboundFeedback, actionTitle = outboundActionTitle, progressTitle = if (outboundProgressActive) currentStep else "", progress = deployProgress, @@ -3391,29 +3783,27 @@ fun DeployTab( if (showSecretsDialog) { DeploySecretsDialog( settingsStore = settingsStore, + profileIndex = activeProfile, initialMainPass = savedMainPass, initialAdminId = savedAdminId, initialBotToken = savedBotToken, - initialSshPort = savedSshPort, initialDns1 = dns1, initialDns2 = dns2, initialManualPortsEnabled = savedManualPorts, initialServerDtlsPort = savedServerDtlsPort.toString(), initialServerWgPort = savedServerWgPort.toString(), - deployIp = ip.trim(), - deployLogin = login, - deployPassword = password, onSaved = { _, _ -> }, - onDismiss = { showSecretsDialog = false } + onDismiss = { showSecretsDialog = false }, + connectionOnly = serverAction == "connect", ) } - serverDiagnosticsReport?.let { report -> + serverDiagnosticsReport?.takeIf { visible }?.let { report -> DeviceCompatibilityDialog( report = report, title = "Диагностика сервера", - subtitle = "Проверка подключается к серверу выбранным способом SSH и собирает безопасные сведения об ОС, systemd, сети, диске, памяти, WDTT-службах и компонентах внешнего выхода.", - note = "Пароли, приватные ключи, токены бота, WireGuard private key и содержимое конфигов не выводятся. Если какая-то команда отсутствует на конкретной Linux-системе, пункт помечается как недоступный, а не считается утечкой или ошибкой.", + subtitle = "Состояние выбранного VPS: служба WDTT, порты, маршрутизация, система и доступ сервера к интернету. При недоступном SSH проверка через работающий WDTT показывает только основные сведения.", + note = "Пароли, приватные ключи и токены не включаются в отчёт. Недоступные проверки отмечены отдельно; неполный ответ не подтверждает исправность сервера.", onDismiss = { serverDiagnosticsReport = null }, onCopy = { val clipboard = context.getSystemService(ClipboardManager::class.java) @@ -3435,7 +3825,9 @@ fun DeployTab( ) AppSectionCard( - modifier = Modifier.onGloballyPositioned { migrationSectionY = it.positionInParent().y }, + modifier = Modifier.onGloballyPositioned { + migrationSectionTopInWindow = it.boundsInWindow().top + }, contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(0.dp) ) { @@ -3446,13 +3838,9 @@ fun DeployTab( .remoteFocusOutline(RoundedCornerShape(24.dp)) .clickable { val willExpand = !migrationExpanded + migrationExpandedOverride = willExpand + revealMigrationRequested = willExpand scope.launch { settingsStore.saveDeployMigrationSectionExpanded(willExpand) } - if (willExpand) { - scope.launch { - kotlinx.coroutines.delay(80) - deployScrollState.animateScrollTo((migrationSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0)) - } - } } .padding(vertical = 2.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), @@ -3487,8 +3875,8 @@ fun DeployTab( AnimatedVisibility( visible = migrationExpanded, - 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), @@ -3506,7 +3894,7 @@ fun DeployTab( statusMessage = backupStatusMessage, accessIssue = when { !primarySshAccessReady -> primarySshAccessIssue - savedMainPass.isBlank() -> "Укажите главный пароль в разделе «Секреты»." + savedMainPass.isBlank() -> "Укажите главный пароль в разделе параметры сервера." else -> null }, enabledInput = backupEnabledInput, @@ -3784,6 +4172,7 @@ fun DeployTab( } if (showSshKeyDialog) { + val keyProfile = activeProfile SshPrivateKeyDialog( title = "SSH-ключ основного сервера", initialPrivateKey = savedSshPrivateKey, @@ -3792,9 +4181,10 @@ fun DeployTab( user = login.ifBlank { "root" }, port = primarySshPort, onSave = { privateKey, passphrase -> - scope.launch { - settingsStore.saveDeploySshKey(privateKey, passphrase) - if (privateKey.isNotBlank()) settingsStore.saveDeploySshAuthMode("key") + val previousSave = accessSaveJob + accessSaveJob = scope.launch { + previousSave?.join() + settingsStore.saveDeploySshKey(privateKey, passphrase, keyProfile) showSshKeyDialog = false } }, @@ -3933,27 +4323,62 @@ fun DeployTab( val deployRequest = pendingDeployRequest val installInfo = existingInstallInfo if (deployRequest != null && installInfo != null) { - ExistingInstallDialog( - info = installInfo, - importMode = selectedImportBackup?.let { selectedImportMode }, - onDismiss = { - pendingDeployRequest = null - existingInstallInfo = null - }, - onPreserve = { - pendingDeployRequest = null - existingInstallInfo = null - launchDeploy(deployRequest, DeployMode.PreserveData) - }, - onReset = { - pendingDeployRequest = null - existingInstallInfo = null - launchDeploy(deployRequest, DeployMode.ResetAll) - } - ) + val rollbackState = installInfo.updateRollbackState + if (rollbackState !is ServerUpdateRollbackState.None) { + ServerUpdateRollbackDialog( + state = rollbackState, + busy = rollbackResolutionBusy, + statusMessage = rollbackResolutionMessage, + onDismiss = { + if (!rollbackResolutionBusy) { + pendingDeployRequest = null + existingInstallInfo = null + rollbackResolutionMessage = "" + } + }, + onRestore = { + runRollbackResolution(ServerUpdateRollbackAction.RestorePrevious) + }, + onKeepCurrent = { + runRollbackResolution(ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup) + }, + ) + } else { + ExistingInstallDialog( + info = installInfo, + importMode = selectedImportBackup?.let { selectedImportMode }, + onDismiss = { + pendingDeployRequest = null + existingInstallInfo = null + }, + onPreserve = { + pendingDeployRequest = null + existingInstallInfo = null + val owner = currentOwnerProfile().copy(listenPort = deployRequest.localPort, + ports = Triple(deployRequest.dtlsPort, deployRequest.wgPort, deployRequest.localPort).asPortsSpec()) + if (pendingDeploySettings == (owner to currentOutboundProfileForms())) { + launchDeploy(deployRequest, DeployMode.PreserveData) + } else { + startDeployCheck(deployRequest, requireExistingServer = true) + } + }, + onReset = { + pendingDeployRequest = null + existingInstallInfo = null + val owner = currentOwnerProfile().copy(listenPort = deployRequest.localPort, + ports = Triple(deployRequest.dtlsPort, deployRequest.wgPort, deployRequest.localPort).asPortsSpec()) + if (pendingDeploySettings == (owner to currentOutboundProfileForms())) { + launchDeploy(deployRequest, DeployMode.ResetAll) + } else { + startDeployCheck(deployRequest, requireExistingServer = true) + } + } + ) + } } } + } } @Composable @@ -4066,7 +4491,7 @@ private fun DeployResultPanel( } @Composable -private fun DeploySuccessBanner(successCountdown: Int, serverVersion: String) { +private fun DeploySuccessBanner(successCountdown: Int, serverVersion: String, openTunnelAfterCountdown: Boolean) { Surface( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), @@ -4088,7 +4513,8 @@ private fun DeploySuccessBanner(successCountdown: Int, serverVersion: String) { style = MaterialTheme.typography.bodyMedium ) Text( - text = "Серверная часть: WDTT Plus $serverVersion", + text = if (openTunnelAfterCountdown) "Переход на вкладку «Туннель» через $successCountdown с" + else "Серверная часть: WDTT Plus $serverVersion", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall ) @@ -4105,6 +4531,7 @@ private fun OutboundRoutingSection( lastCheckAttemptAt: Long, lastCheckError: String, status: String, + feedback: OutboundActionFeedback?, actionTitle: String, accessIssue: String?, enabled: Boolean, @@ -4172,8 +4599,8 @@ private fun OutboundRoutingSection( 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), @@ -4292,7 +4719,7 @@ private fun OutboundRoutingSection( } } if (status.isNotBlank()) { - InlineActionMessage(status) + if (feedback?.summary == status) OutboundActionMessage(feedback) else InlineActionMessage(status) } OutlinedButton( onClick = { onOpen(OutboundDialog.Diagnostics) }, @@ -4534,6 +4961,7 @@ private fun outboundIndicatorColor(state: OutboundModeVisualState): Color = when private fun LocalProxyDialog( busy: Boolean, status: String, + feedback: OutboundActionFeedback?, actionTitle: String, progressTitle: String, progress: Float, @@ -4557,7 +4985,7 @@ private fun LocalProxyDialog( var confirmRemove by rememberSaveable { mutableStateOf(false) } val port = portInput.toIntOrNull()?.takeIf { it in 1..65533 } val credentialsIssue = localProxyCredentialsIssue(loginInput, passwordInput) - OutboundDialogFrame("Прокси на этом VPS", status, progressTitle, progress, onDismiss) { + OutboundDialogFrame("Прокси на этом VPS", status, progressTitle, progress, onDismiss, feedback) { OutboundDialogStateBanner(indicator) Text( "На этом же VPS будут созданы два входа с одним логином и паролем: SOCKS5 и HTTP. Это удобно как прокси, но IP не маскирует: наружу будет виден текущий сервер.", @@ -4661,7 +5089,7 @@ private fun LocalProxyDialog( } } if (confirmRemove) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = { if (!busy) confirmRemove = false }, title = { Text("Удалить прокси с этого VPS?") }, text = { @@ -4689,6 +5117,7 @@ private fun LocalProxyDialog( private fun ExternalProxyDialog( busy: Boolean, status: String, + feedback: OutboundActionFeedback?, actionTitle: String, progressTitle: String, progress: Float, @@ -4716,7 +5145,7 @@ private fun ExternalProxyDialog( val port = portInput.toIntOrNull()?.takeIf { it in 1..65535 } val hostValid = hostInput.isValidPublicHost() val credentialsIssue = externalProxyCredentialsIssue(loginInput, passwordInput) - OutboundDialogFrame("Внешний TCP-прокси", status, progressTitle, progress, onDismiss) { + OutboundDialogFrame("Внешний TCP-прокси", status, progressTitle, progress, onDismiss, feedback) { OutboundDialogStateBanner(indicator) Text( "WDTT будет отправлять обычные TCP-подключения пользователей через выбранный прокси. UDP, QUIC и часть голосового/звонкового трафика могут идти напрямую.", @@ -4799,7 +5228,8 @@ private fun ExternalProxyDialog( onClick = onDisable, enabled = !busy && disableEnabled, modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp) + shape = RoundedCornerShape(16.dp), + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp) ) { val disabling = actionTitle.contains("Возвращаю", ignoreCase = true) if (disabling) { @@ -4812,14 +5242,15 @@ private fun ExternalProxyDialog( onClick = { confirmDelete = true }, enabled = !busy && deleteEnabled, modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp) + shape = RoundedCornerShape(16.dp), + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp) ) { Text("Удалить") } } } if (confirmDelete) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = { if (!busy) confirmDelete = false }, title = { Text("Удалить настройки внешнего прокси?") }, text = { @@ -4845,6 +5276,7 @@ private fun ExternalProxyDialog( private fun WireGuardExitVpsDialog( busy: Boolean, status: String, + feedback: OutboundActionFeedback?, actionTitle: String, progressTitle: String, progress: Float, @@ -4879,7 +5311,7 @@ private fun WireGuardExitVpsDialog( val hostValid = hostInput.isValidPublicHost() val sshPort = sshPortInput.toIntOrNull()?.takeIf { it in 1..65535 } val wgPort = wgPortInput.toIntOrNull()?.takeIf { it in 1..65535 } - OutboundDialogFrame("Выход через другой сервер", status, progressTitle, progress, onDismiss) { + OutboundDialogFrame("Выход через другой сервер", status, progressTitle, progress, onDismiss, feedback) { OutboundDialogStateBanner(indicator) Text( "WDTT Plus подключит текущий сервер к другому VPS по WireGuard и будет выпускать пользователей WDTT в интернет через этот второй сервер. Это самый понятный вариант для отдельного выходного IP.", @@ -4888,11 +5320,11 @@ private fun WireGuardExitVpsDialog( ) Row( modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, + horizontalArrangement = Arrangement.spacedBy(2.dp), verticalAlignment = Alignment.CenterVertically ) { - Text("Вход на дополнительный VPS", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold) - IconButton( + Text("Вход на дополнительный VPS", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f, fill = false)) + HintIconButton(hint = "Как работает вход по SSH", onClick = onSshHelp, modifier = Modifier.size(32.dp).remoteHelpFocus(), ) { @@ -5034,7 +5466,7 @@ private fun WireGuardExitVpsDialog( } } if (confirmDelete) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = { if (!busy) confirmDelete = false }, title = { Text("Удалить выход через другой сервер?") }, text = { @@ -5062,6 +5494,7 @@ private fun WireGuardExitVpsDialog( private fun FreeWarpDialog( busy: Boolean, status: String, + feedback: OutboundActionFeedback?, actionTitle: String, progressTitle: String, progress: Float, @@ -5087,7 +5520,7 @@ private fun FreeWarpDialog( var confirmDelete by rememberSaveable { mutableStateOf(false) } var confirmReset by rememberSaveable { mutableStateOf(false) } val mtu = mtuInput.toIntOrNull()?.takeIf { it in 1280..1500 } - OutboundDialogFrame("Бесплатный WARP", status, progressTitle, progress, onDismiss) { + OutboundDialogFrame("Бесплатный WARP", status, progressTitle, progress, onDismiss, feedback) { OutboundDialogStateBanner(indicator) Text( "WDTT Plus автоматически зарегистрирует бесплатный Cloudflare WARP и направит через него только трафик WDTT-пользователей. Второй сервер и готовый конфиг не нужны.", @@ -5262,7 +5695,7 @@ private fun FreeWarpDialog( } } if (confirmReset) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = { confirmReset = false }, title = { Text("Сбросить регистрацию WARP?") }, text = { @@ -5280,7 +5713,7 @@ private fun FreeWarpDialog( ) } if (confirmDelete) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = { confirmDelete = false }, title = { Text("Удалить бесплатный WARP?") }, text = { @@ -5304,6 +5737,7 @@ private fun TunInterfaceDialog( busy: Boolean, candidatesBusy: Boolean, status: String, + feedback: OutboundActionFeedback?, actionTitle: String, progressTitle: String, progress: Float, @@ -5325,7 +5759,7 @@ private fun TunInterfaceDialog( var showSetupHelp by rememberSaveable { mutableStateOf(false) } val normalizedInterface = interfaceInput.trim() val interfaceIssue = tunInterfaceSelectionIssue(normalizedInterface, candidates) - OutboundDialogFrame("Существующий TUN-интерфейс", status, progressTitle, progress, onDismiss) { + OutboundDialogFrame("Существующий TUN-интерфейс", status, progressTitle, progress, onDismiss, feedback) { OutboundDialogStateBanner(indicator) Text( "Использует уже подготовленный на сервере TUN. WDTT Plus добавляет только собственные маршруты клиентской подсети и не меняет конфигурацию Xray, sing-box или другой службы.", @@ -5339,15 +5773,16 @@ private fun TunInterfaceDialog( ) Row( modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, + horizontalArrangement = Arrangement.spacedBy(2.dp), verticalAlignment = Alignment.CenterVertically ) { Text( "Подготовка внешнего TUN", style = MaterialTheme.typography.labelLarge, - fontWeight = FontWeight.SemiBold + fontWeight = FontWeight.SemiBold, + modifier = Modifier.weight(1f, fill = false) ) - IconButton( + HintIconButton(hint = "Как подготовить TUN-интерфейс", onClick = { showSetupHelp = true }, enabled = !busy, modifier = Modifier.size(32.dp).remoteHelpFocus(enabled = !busy) @@ -5473,61 +5908,19 @@ private fun TunInterfaceDialog( } } if (showSetupHelp) { - val configuration = LocalConfiguration.current - val television = isTelevisionDevice() - val helpScrollState = rememberScrollState() - val helpMaxHeight = if (television) { - (configuration.screenHeightDp.dp * 0.72f).coerceAtMost(620.dp) - } else { - (configuration.screenHeightDp.dp * 0.56f).coerceAtMost(460.dp) + SettingsDialogLayout( + title = "Как подготовить TUN-интерфейс", + onDismiss = { showSetupHelp = false }, + ) { + Text("1. Создайте и запустите TUN-интерфейс в Xray, sing-box или другом приложении на этом сервере.") + Text("2. Настройте правила маршрутизации внутри этого приложения. Для правил по доменам включите распознавание доменов там же. WDTT Plus не меняет эти настройки.") + Text("3. Вернитесь сюда, обновите кандидатов и выберите имя поднятого интерфейса. Если его нет в списке, введите точное имя вручную. Системные интерфейсы сервера использовать нельзя.") + Text("4. После включения проверьте выход. Если внешний TUN остановится, клиентский трафик WDTT будет заблокирован до его восстановления или возврата в прямой режим.") + Text("5. Пока открыт блок или окно TUN, WDTT Plus перечитывает состояние сервера каждые 10 секунд. Если внешний TUN пропадёт, приложение покажет предупреждение, а трафик WDTT останется заблокированным до восстановления TUN или возврата в прямой режим.") } - AlertDialog( - onDismissRequest = { showSetupHelp = false }, - modifier = Modifier.televisionDialogWidth(television), - title = { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.Top - ) { - Text( - "Как подготовить TUN-интерфейс", - modifier = Modifier.weight(1f) - ) - IconButton( - onClick = { showSetupHelp = false }, - modifier = Modifier.size(36.dp).remoteIconButtonFocus() - ) { - Icon( - Icons.Default.Close, - contentDescription = "Закрыть", - modifier = Modifier.size(22.dp) - ) - } - } - }, - text = { - Column( - modifier = Modifier - .heightIn(max = helpMaxHeight) - .verticalScroll(helpScrollState) - .tvDpadScrollable(helpScrollState, television), - verticalArrangement = Arrangement.spacedBy(10.dp) - ) { - Text("1. Создайте и запустите TUN-интерфейс в Xray, sing-box или другом приложении на этом сервере.") - Text("2. Настройте правила маршрутизации внутри этого приложения. Для правил по доменам включите распознавание доменов там же. WDTT Plus не меняет эти настройки.") - Text("3. Вернитесь сюда, обновите кандидатов и выберите имя поднятого интерфейса. Если его нет в списке, введите точное имя вручную. Системные интерфейсы сервера использовать нельзя.") - Text("4. После включения проверьте выход. Если внешний TUN остановится, клиентский трафик WDTT будет заблокирован до его восстановления или возврата в прямой режим.") - Text("5. Пока открыт блок или окно TUN, WDTT Plus перечитывает состояние сервера каждые 10 секунд. Если внешний TUN пропадёт, приложение покажет предупреждение, а трафик WDTT останется заблокированным до восстановления TUN или возврата в прямой режим.") - } - }, - confirmButton = { - TextButton(onClick = { showSetupHelp = false }) { Text("Понятно") } - }, - properties = DialogProperties(usePlatformDefaultWidth = !television), - ) } if (confirmDelete) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = { if (!busy) confirmDelete = false }, title = { Text("Удалить настройку TUN-выхода?") }, text = { @@ -5553,6 +5946,7 @@ private fun TunInterfaceDialog( private fun ImportedWireGuardDialog( busy: Boolean, status: String, + feedback: OutboundActionFeedback?, actionTitle: String, progressTitle: String, progress: Float, @@ -5573,7 +5967,7 @@ private fun ImportedWireGuardDialog( var configText by rememberSaveable(initialConfig) { mutableStateOf(initialConfig) } var confirmDelete by rememberSaveable { mutableStateOf(false) } val valid = configText.isNotBlank() && validateWireGuardConfigText(configText).isSuccess - OutboundDialogFrame("VPN/WireGuard-файл", status, progressTitle, progress, onDismiss) { + OutboundDialogFrame("VPN/WireGuard-файл", status, progressTitle, progress, onDismiss, feedback) { OutboundDialogStateBanner(indicator) Text( "Можно выбрать готовый WireGuard .conf от VPN-провайдера, собственного WARP/WARP+ или другой совместимой службы. Для автоматической бесплатной регистрации WARP используйте отдельный вариант «Бесплатный WARP».", @@ -5670,7 +6064,7 @@ private fun ImportedWireGuardDialog( } } if (confirmDelete) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = { if (!busy) confirmDelete = false }, title = { Text("Удалить VPN/WireGuard-файл?") }, text = { @@ -5698,6 +6092,7 @@ private fun ImportedWireGuardDialog( private fun OutboundDiagnosticsDialog( busy: Boolean, status: String, + feedback: OutboundActionFeedback?, actionTitle: String, progressTitle: String, progress: Float, @@ -5706,7 +6101,7 @@ private fun OutboundDiagnosticsDialog( onRun: () -> Unit, onCleanup: () -> Unit ) { - OutboundDialogFrame("Диагностика выхода WDTT", status, progressTitle, progress, onDismiss) { + OutboundDialogFrame("Диагностика выхода WDTT", status, progressTitle, progress, onDismiss, feedback) { Text( "Диагностика показывает, какой выход сейчас включён, какой внешний IP видит сервер и какие сетевые правила применены для WDTT.", style = MaterialTheme.typography.bodySmall, @@ -5777,6 +6172,7 @@ private fun OutboundDialogFrame( progressTitle: String, progress: Float, onDismiss: () -> Unit, + feedback: OutboundActionFeedback?, content: @Composable ColumnScope.() -> Unit ) { val scrollState = rememberScrollState() @@ -5810,7 +6206,7 @@ private fun OutboundDialogFrame( } } } - androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) { + BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = onDismiss) { BoxWithConstraints( modifier = Modifier.fillMaxSize().padding(8.dp), contentAlignment = Alignment.Center @@ -5866,10 +6262,9 @@ private fun OutboundDialogFrame( } } if (status.isNotBlank()) { - InlineActionMessage( - status = status, - modifier = Modifier.onGloballyPositioned { statusBounds = it.boundsInWindow() } - ) + val resultModifier = Modifier.onGloballyPositioned { statusBounds = it.boundsInWindow() } + if (feedback?.summary == status) OutboundActionMessage(feedback, resultModifier) + else InlineActionMessage(status, resultModifier) } Spacer(Modifier.height(4.dp)) } @@ -5955,6 +6350,7 @@ internal fun serverDiagnosticsScript( val clientPort = expectedClientPort?.takeIf { it in 1..65535 } ?: 9000 return """ set +e + ${outboundProbeFunctions().replace("\n", "\n ")} WDTT_EXPECTED_DTLS_PORT="$dtlsPort" WDTT_EXPECTED_WG_PORT="$wgPort" WDTT_EXPECTED_CLIENT_PORT="$clientPort" @@ -6037,7 +6433,7 @@ internal fun serverDiagnosticsScript( } wdtt_diag_public_ip() { if wdtt_diag_cmd curl; then - curl -4fsS --connect-timeout 5 --max-time 10 https://api.ipify.org 2>/dev/null + curl -4fsS --connect-timeout 3 --max-time 6 https://api.ipify.org 2>/dev/null fi } wdtt_diag_resolve_host() { @@ -6046,9 +6442,17 @@ internal fun serverDiagnosticsScript( [0-9]*.[0-9]*.[0-9]*.[0-9]*) printf '%s' "${'$'}host"; return 0 ;; esac if wdtt_diag_cmd getent; then - getent ahostsv4 "${'$'}host" 2>/dev/null | awk '{print ${'$'}1; exit}' + if wdtt_diag_cmd timeout; then + timeout 3 getent ahostsv4 "${'$'}host" 2>/dev/null | awk '{print ${'$'}1; exit}' + else + getent ahostsv4 "${'$'}host" 2>/dev/null | awk '{print ${'$'}1; exit}' + fi elif wdtt_diag_cmd nslookup; then - nslookup "${'$'}host" 2>/dev/null | awk '/^Address: / {print ${'$'}2; exit}' + if wdtt_diag_cmd timeout; then + timeout 3 nslookup "${'$'}host" 2>/dev/null | awk '/^Address: / {print ${'$'}2; exit}' + else + nslookup "${'$'}host" 2>/dev/null | awk '/^Address: / {print ${'$'}2; exit}' + fi elif wdtt_diag_cmd ping; then ping -4 -c 1 -W 2 "${'$'}host" >/dev/null 2>&1 && printf 'ping-ok' fi @@ -6060,7 +6464,7 @@ internal fun serverDiagnosticsScript( return 2 fi errfile="/tmp/wdtt-diag-curl-${'$'}${'$'}.err" - code="${'$'}(curl -4sS -o /dev/null -w '%{http_code}' --connect-timeout 6 --max-time 12 "${'$'}url" 2>"${'$'}errfile")" + code="${'$'}(curl -4sS -o /dev/null -w '%{http_code}' --connect-timeout 3 --max-time 6 "${'$'}url" 2>"${'$'}errfile")" exit_code="${'$'}?" err="${'$'}(tr '\n\r|' ' ' <"${'$'}errfile" 2>/dev/null | cut -c1-180)" rm -f "${'$'}errfile" @@ -6095,7 +6499,8 @@ internal fun serverDiagnosticsScript( wdtt_diag_udp_listen_port() { port="${'$'}1" if wdtt_diag_cmd ss; then - ss -H -lunu 2>/dev/null | awk -v needle=":${'$'}port" 'index(${'$'}0, needle) {found=1} END {exit found ? 0 : 1}' + sockets="${'$'}(ss -H -lun 2>/dev/null)" || return 2 + printf '%s\n' "${'$'}sockets" | awk -v needle=":${'$'}port" '${'$'}4 ~ (needle "${'$'}") {found=1} END {exit found ? 0 : 1}' return "${'$'}?" fi return 2 @@ -6136,7 +6541,7 @@ internal fun serverDiagnosticsScript( echo "не выполнена: адрес интерфейса wdtt0 не найден" return 1 fi - trace="${'$'}(curl -4fsS --interface "${'$'}source_ip" --connect-timeout 8 --max-time 15 https://www.cloudflare.com/cdn-cgi/trace 2>/dev/null)" + trace="${'$'}(wdtt_routed_https "${'$'}source_ip" "wg-wdtt-exit" https://www.cloudflare.com/cdn-cgi/trace || true)" if [ -z "${'$'}trace" ]; then echo "не пройдена: HTTPS через маршрут WDTT не отвечает" return 1 @@ -6264,93 +6669,6 @@ internal fun serverDiagnosticsScript( fi wdtt_diag_emit "INFO" "Диск" "${'$'}{DISK_INFO:-не удалось прочитать}" "Для установки нужны место под бинарник сервера, временные файлы, WireGuard/WARP-профили и журналы systemd." "" - PUBLIC_IP="${'$'}(wdtt_diag_public_ip)" - DEFAULT_ROUTE="" - if wdtt_diag_cmd ip; then - DEFAULT_ROUTE="${'$'}(ip -4 route show default 2>/dev/null | head -n 1)" - fi - NET_DETAILS="Публичный IPv4 самого сервера: ${'$'}{PUBLIC_IP:-не удалось определить}. Default route: ${'$'}{DEFAULT_ROUTE:-не определён}." - if [ -n "${'$'}PUBLIC_IP" ]; then - wdtt_diag_emit "OK" "Сеть сервера" "интернет доступен" "${'$'}NET_DETAILS" "" - else - wdtt_diag_emit "WARNING" "Сеть сервера" "публичный IPv4 не проверен" "${'$'}NET_DETAILS" "Проверьте исходящий HTTPS-доступ с сервера; он нужен для wgcf, WARP-проверок и обновлений." - fi - - VK_DETAILS="" - for host in api.vk.me calls.okcdn.ru login.vk.ru api.vk.ru; do - resolved="${'$'}(wdtt_diag_resolve_host "${'$'}host")" - if [ -n "${'$'}resolved" ]; then - VK_DETAILS="${'$'}VK_DETAILS ${'$'}host DNS: ${'$'}resolved;" - else - VK_DETAILS="${'$'}VK_DETAILS ${'$'}host DNS: не разрешается;" - fi - done - VK_API_ME_HTTP="${'$'}(wdtt_diag_http_probe 'https://api.vk.me/method/users.get?v=5.276')" - VK_DETAILS="${'$'}VK_DETAILS основной api.vk.me HTTPS: ${'$'}VK_API_ME_HTTP;" - OK_HTTP="${'$'}(wdtt_diag_http_probe https://calls.okcdn.ru/fb.do)" - VK_DETAILS="${'$'}VK_DETAILS основной calls.okcdn.ru HTTPS: ${'$'}OK_HTTP;" - VK_LOGIN_HTTP="${'$'}(wdtt_diag_http_probe https://login.vk.ru/)" - VK_DETAILS="${'$'}VK_DETAILS legacy login.vk.ru HTTPS: ${'$'}VK_LOGIN_HTTP;" - VK_API_RU_HTTP="${'$'}(wdtt_diag_http_probe 'https://api.vk.ru/method/users.get?v=5.275')" - VK_DETAILS="${'$'}VK_DETAILS legacy api.vk.ru HTTPS: ${'$'}VK_API_RU_HTTP." - wdtt_diag_emit "INFO" "VK/OK с VPS (справочно)" "не влияет на основной VK-вход" "${'$'}VK_DETAILS Получение VK-токенов и решение капчи выполняются на телефоне, а не на VPS. Поэтому недоступность этих HTTPS-адресов именно с сервера не считается ошибкой туннеля; серверу важнее рабочая служба, UDP-порты, маршрутизация и выходной интернет." "Если туннель не стартует, запустите «Проверить устройство»: она проверяет api.vk.me, calls.okcdn.ru, DNS и резервную цепочку из реальной сети телефона." - - TELEGRAM_CONFIGURED=0 - if [ -r /etc/wdtt/access.json ] && grep -Eq '"bot_token"[[:space:]]*:[[:space:]]*"[^"]{10,}"' /etc/wdtt/access.json 2>/dev/null; then - TELEGRAM_CONFIGURED=1 - fi - TG_HTTP="${'$'}(wdtt_diag_http_probe https://api.telegram.org/)"; TG_HTTP_CODE="${'$'}?" - if [ "${'$'}TG_HTTP_CODE" = "0" ]; then - wdtt_diag_emit "INFO" "Telegram API" "доступен" "api.telegram.org: ${'$'}TG_HTTP. Настроен ли бот на сервере: ${'$'}([ "${'$'}TELEGRAM_CONFIGURED" = "1" ] && echo да || echo нет)." "" - elif [ "${'$'}TELEGRAM_CONFIGURED" = "1" ]; then - wdtt_diag_emit "WARNING" "Telegram API" "недоступен" "На сервере найден признак настроенного Telegram-бота, но api.telegram.org не отвечает: ${'$'}TG_HTTP." "Если бот нужен, проверьте DNS/HTTPS-доступ к Telegram API с VPS или ограничения региона/провайдера." - else - wdtt_diag_emit "INFO" "Telegram API" "не проверен как обязательный" "api.telegram.org не отвечает: ${'$'}TG_HTTP. Бот на сервере не выглядит настроенным, поэтому это не мешает основному туннелю." "" - fi - - WARP_WARN=0 - WARP_DETAILS="" - WARP_API_HTTP="${'$'}(wdtt_diag_http_probe https://api.cloudflareclient.com/)"; WARP_API_HTTP_CODE="${'$'}?" - [ "${'$'}WARP_API_HTTP_CODE" = "0" ] || WARP_WARN=1 - WARP_DETAILS="${'$'}WARP_DETAILS регистрация api.cloudflareclient.com: ${'$'}WARP_API_HTTP;" - CF_TRACE="${'$'}(curl -4fsS --connect-timeout 6 --max-time 12 https://www.cloudflare.com/cdn-cgi/trace 2>/dev/null)" - if [ -n "${'$'}CF_TRACE" ]; then - CF_WARP="${'$'}(printf '%s\n' "${'$'}CF_TRACE" | sed -n 's/^warp=//p' | head -n 1)" - CF_COLO="${'$'}(printf '%s\n' "${'$'}CF_TRACE" | sed -n 's/^colo=//p' | head -n 1)" - WARP_DETAILS="${'$'}WARP_DETAILS Cloudflare trace доступен: warp=${'$'}{CF_WARP:-не указано}, colo=${'$'}{CF_COLO:-не указано};" - else - WARP_WARN=1 - WARP_DETAILS="${'$'}WARP_DETAILS Cloudflare trace недоступен;" - fi - WGCF_HTTP="${'$'}(wdtt_diag_http_probe "${'$'}WDTT_WGCF_URL")"; WGCF_HTTP_CODE="${'$'}?" - [ "${'$'}WGCF_HTTP_CODE" = "0" ] || WARP_WARN=1 - WARP_DETAILS="${'$'}WARP_DETAILS wgcf download: ${'$'}WGCF_HTTP;" - WGCF_API_HTTP="${'$'}(wdtt_diag_http_probe "${'$'}WDTT_WGCF_API")"; WGCF_API_HTTP_CODE="${'$'}?" - [ "${'$'}WGCF_API_HTTP_CODE" = "0" ] || WARP_WARN=1 - WARP_DETAILS="${'$'}WARP_DETAILS GitHub API wgcf: ${'$'}WGCF_API_HTTP;" - ENGAGE_IP="${'$'}(wdtt_diag_resolve_host engage.cloudflareclient.com)" - if [ -n "${'$'}ENGAGE_IP" ]; then - WARP_DETAILS="${'$'}WARP_DETAILS engage.cloudflareclient.com DNS: ${'$'}ENGAGE_IP;" - else - WARP_WARN=1 - WARP_DETAILS="${'$'}WARP_DETAILS engage.cloudflareclient.com DNS: не разрешается;" - fi - WARP_UDP_2408="${'$'}(wdtt_diag_udp_probe engage.cloudflareclient.com 2408)"; WARP_UDP_2408_CODE="${'$'}?" - [ "${'$'}WARP_UDP_2408_CODE" = "1" ] && WARP_WARN=1 - WARP_DETAILS="${'$'}WARP_DETAILS UDP 2408: ${'$'}WARP_UDP_2408;" - WARP_UDP_500="${'$'}(wdtt_diag_udp_probe engage.cloudflareclient.com 500)"; WARP_UDP_500_CODE="${'$'}?" - [ "${'$'}WARP_UDP_500_CODE" = "1" ] && WARP_WARN=1 - WARP_DETAILS="${'$'}WARP_DETAILS UDP 500: ${'$'}WARP_UDP_500;" - WARP_STACK="${'$'}(wdtt_diag_wireguard_kernel)" - WARP_STACK_CODE="${'$'}?" - [ "${'$'}WARP_STACK_CODE" = "0" ] || WARP_WARN=1 - WARP_DETAILS="${'$'}WARP_DETAILS ${'$'}WARP_STACK; wg=${'$'}(wdtt_diag_cmd wg && echo есть || echo нет); wg-quick=${'$'}(wdtt_diag_cmd wg-quick && echo есть || echo нет)." - if [ "${'$'}WARP_WARN" = "0" ]; then - wdtt_diag_emit "OK" "Бесплатный WARP" "предпосылки выглядят рабочими" "${'$'}WARP_DETAILS" "Это не гарантирует регистрацию WARP: Cloudflare может временно ограничивать регион/VPS, но базовая сеть и инструменты выглядят пригодными." - else - wdtt_diag_emit "WARNING" "Бесплатный WARP" "есть риск, что не заработает" "${'$'}WARP_DETAILS" "Проверьте исходящий HTTPS к Cloudflare/GitHub, UDP к WARP endpoint, WireGuard-стек ядра и попробуйте другой MTU/endpoint или регион VPS." - fi - OUT_MODE="${'$'}(wdtt_diag_outbound_mode)" WDTT_SERVICE_FOR_ROUTING="${'$'}(wdtt_diag_service_state wdtt.service)" FIREWALL_DETAILS="" @@ -6488,7 +6806,7 @@ internal fun serverDiagnosticsScript( tun_interface) TUN_TEST_SOURCE="${'$'}(ip -4 -o addr show dev wdtt0 scope global 2>/dev/null | awk '{split(${'$'}4, value, "/"); print value[1]; exit}')" TUN_EXIT_IP="" - [ -n "${'$'}TUN_TEST_SOURCE" ] && TUN_EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}TUN_TEST_SOURCE" --max-time 12 https://api.ipify.org 2>/dev/null || true)" + [ -n "${'$'}TUN_TEST_SOURCE" ] && TUN_EXIT_IP="${'$'}(wdtt_routed_public_ip "${'$'}TUN_TEST_SOURCE" "${'$'}TUN_INTERFACE" || true)" FIREWALL_DETAILS="${'$'}FIREWALL_DETAILS TUN-выход ${'$'}{TUN_INTERFACE:-не указан}: интерфейс=${'$'}TUN_INTERFACE_ACTIVE, служба=${'$'}TUN_SERVICE_ACTIVE, правило=${'$'}TUN_POLICY_RULE_ACTIVE, маршрут=${'$'}TUN_DEFAULT_ROUTE_ACTIVE, блокировка=${'$'}TUN_FAIL_CLOSED_ACTIVE, FORWARD=${'$'}TUN_FORWARD_RULES_ACTIVE, ip_forward=${'$'}TUN_IP_FORWARD_ACTIVE, проверочный IP=${'$'}{TUN_EXIT_IP:-нет}." if [ "${'$'}TUN_INTERFACE_ACTIVE" = "1" ] && [ "${'$'}TUN_SERVICE_ACTIVE" = "1" ] && @@ -6607,7 +6925,7 @@ internal fun serverDiagnosticsScript( WDTT_SERVICE="${'$'}(wdtt_diag_service_state wdtt.service)" WDTT_BIN="${'$'}(wdtt_diag_file_state /usr/local/bin/wdtt-server)" WDTT_CONFIG="${'$'}(wdtt_diag_file_state /etc/wdtt)" - WDTT_ACCESS="${'$'}(wdtt_diag_file_state /etc/wdtt/access.json)" + WDTT_ACCESS="${'$'}(wdtt_diag_file_state /etc/wdtt/passwords.json)" if [ -S /run/wdtt/admin.sock ]; then WDTT_ADMIN_SOCKET="/run/wdtt/admin.sock есть" elif [ -S /etc/wdtt/admin.sock ]; then @@ -6615,7 +6933,7 @@ internal fun serverDiagnosticsScript( else WDTT_ADMIN_SOCKET="не найден" fi - WDTT_DETAILS="wdtt.service: ${'$'}WDTT_SERVICE. /usr/local/bin/wdtt-server: ${'$'}WDTT_BIN. /etc/wdtt: ${'$'}WDTT_CONFIG. access.json: ${'$'}WDTT_ACCESS. admin socket: ${'$'}WDTT_ADMIN_SOCKET." + WDTT_DETAILS="wdtt.service: ${'$'}WDTT_SERVICE. /usr/local/bin/wdtt-server: ${'$'}WDTT_BIN. /etc/wdtt: ${'$'}WDTT_CONFIG. passwords.json: ${'$'}WDTT_ACCESS. admin socket: ${'$'}WDTT_ADMIN_SOCKET." case "${'$'}WDTT_SERVICE" in active) if [ "${'$'}WDTT_ADMIN_SOCKET" = "не найден" ]; then @@ -6628,16 +6946,16 @@ internal fun serverDiagnosticsScript( *) wdtt_diag_emit "INFO" "WDTT сервер" "${'$'}WDTT_SERVICE" "${'$'}WDTT_DETAILS" "Если установка ещё не выполнялась — это нормально." ;; esac - PORT_EXPECT_DETAILS="Активный профиль приложения ожидает DTLS UDP ${'$'}WDTT_EXPECTED_DTLS_PORT и серверный WireGuard UDP ${'$'}WDTT_EXPECTED_WG_PORT. Локальный порт Android-клиента ${'$'}WDTT_EXPECTED_CLIENT_PORT проверяется на телефоне, а не на VPS." + PORT_EXPECT_DETAILS="Активный профиль приложения ожидает DTLS UDP ${'$'}WDTT_EXPECTED_DTLS_PORT и серверный WireGuard UDP ${'$'}WDTT_EXPECTED_WG_PORT. Локальный порт Android-клиента ${'$'}WDTT_EXPECTED_CLIENT_PORT проверяется на телефоне, а не на VPS. Режим TCP/TLS на телефоне не отменяет UDP на сервере; доступность портов извне здесь не проверяется." PORT_EXPECT_SEVERITY="INFO" PORT_EXPECT_STATUS="проверено частично" if wdtt_diag_udp_listen_port "${'$'}WDTT_EXPECTED_DTLS_PORT"; then PORT_EXPECT_DETAILS="${'$'}PORT_EXPECT_DETAILS DTLS-порт слушается на сервере." - [ "${'$'}WDTT_SERVICE" = "active" ] && PORT_EXPECT_SEVERITY="OK" && PORT_EXPECT_STATUS="порты совпадают" + [ "${'$'}WDTT_SERVICE" = "active" ] && PORT_EXPECT_SEVERITY="OK" && PORT_EXPECT_STATUS="UDP-порты слушаются" else PORT_LISTEN_CODE="${'$'}?" if [ "${'$'}PORT_LISTEN_CODE" = "2" ]; then - PORT_EXPECT_DETAILS="${'$'}PORT_EXPECT_DETAILS Не удалось проверить UDP listening: ss отсутствует." + PORT_EXPECT_DETAILS="${'$'}PORT_EXPECT_DETAILS Не удалось проверить UDP listening: ss отсутствует или вернул ошибку." else PORT_EXPECT_DETAILS="${'$'}PORT_EXPECT_DETAILS DTLS-порт ${'$'}WDTT_EXPECTED_DTLS_PORT не найден среди UDP listening sockets." [ "${'$'}WDTT_SERVICE" = "active" ] && PORT_EXPECT_SEVERITY="WARNING" && PORT_EXPECT_STATUS="порт не слушается" @@ -6648,13 +6966,13 @@ internal fun serverDiagnosticsScript( else WG_LISTEN_CODE="${'$'}?" if [ "${'$'}WG_LISTEN_CODE" = "2" ]; then - PORT_EXPECT_DETAILS="${'$'}PORT_EXPECT_DETAILS Не удалось проверить WireGuard UDP listening: ss отсутствует." + PORT_EXPECT_DETAILS="${'$'}PORT_EXPECT_DETAILS Не удалось проверить WireGuard UDP listening: ss отсутствует или вернул ошибку." else PORT_EXPECT_DETAILS="${'$'}PORT_EXPECT_DETAILS WireGuard-порт ${'$'}WDTT_EXPECTED_WG_PORT не найден среди UDP listening sockets." [ "${'$'}WDTT_SERVICE" = "active" ] && PORT_EXPECT_SEVERITY="WARNING" && PORT_EXPECT_STATUS="часть портов не слушается" fi fi - wdtt_diag_emit "${'$'}PORT_EXPECT_SEVERITY" "Порты активного профиля" "${'$'}PORT_EXPECT_STATUS" "${'$'}PORT_EXPECT_DETAILS" "Если порты не совпадают, выполните установку/обновление с сохранением данных или проверьте ручные порты в «Секретах»." + wdtt_diag_emit "${'$'}PORT_EXPECT_SEVERITY" "Порты активного профиля" "${'$'}PORT_EXPECT_STATUS" "${'$'}PORT_EXPECT_DETAILS" "Если порты не совпадают, выполните установку/обновление с сохранением данных или проверьте ручные порты в параметрах сервера." LISTEN_INFO="" if wdtt_diag_cmd ss; then @@ -6696,6 +7014,94 @@ internal fun serverDiagnosticsScript( VIRT_INFO="${'$'}(systemd-detect-virt 2>/dev/null || echo physical/unknown)" fi wdtt_diag_emit "INFO" "Виртуализация" "${'$'}{VIRT_INFO:-не определена}" "Некоторые VPS-провайдеры или регионы могут ограничивать WARP/UDP; этот пункт помогает сопоставлять отчёты." "" + PUBLIC_IP="${'$'}(wdtt_diag_public_ip)" + DEFAULT_ROUTE="" + if wdtt_diag_cmd ip; then + DEFAULT_ROUTE="${'$'}(ip -4 route show default 2>/dev/null | head -n 1)" + fi + NET_DETAILS="Публичный IPv4 самого сервера: ${'$'}{PUBLIC_IP:-не удалось определить}. Default route: ${'$'}{DEFAULT_ROUTE:-не определён}." + if [ -n "${'$'}PUBLIC_IP" ]; then + wdtt_diag_emit "OK" "Сеть сервера" "интернет доступен" "${'$'}NET_DETAILS" "" + else + wdtt_diag_emit "WARNING" "Сеть сервера" "публичный IPv4 не проверен" "${'$'}NET_DETAILS" "Проверьте исходящий HTTPS-доступ с сервера; он нужен для wgcf, WARP-проверок и обновлений." + fi + + VK_DETAILS="" + for host in api.vk.me calls.okcdn.ru login.vk.ru api.vk.ru; do + resolved="${'$'}(wdtt_diag_resolve_host "${'$'}host")" + if [ -n "${'$'}resolved" ]; then + VK_DETAILS="${'$'}VK_DETAILS ${'$'}host DNS: ${'$'}resolved;" + else + VK_DETAILS="${'$'}VK_DETAILS ${'$'}host DNS: не разрешается;" + fi + done + VK_API_ME_HTTP="${'$'}(wdtt_diag_http_probe 'https://api.vk.me/method/users.get?v=5.276')" + VK_DETAILS="${'$'}VK_DETAILS основной api.vk.me HTTPS: ${'$'}VK_API_ME_HTTP;" + OK_HTTP="${'$'}(wdtt_diag_http_probe https://calls.okcdn.ru/fb.do)" + VK_DETAILS="${'$'}VK_DETAILS основной calls.okcdn.ru HTTPS: ${'$'}OK_HTTP;" + VK_LOGIN_HTTP="${'$'}(wdtt_diag_http_probe https://login.vk.ru/)" + VK_DETAILS="${'$'}VK_DETAILS legacy login.vk.ru HTTPS: ${'$'}VK_LOGIN_HTTP;" + VK_API_RU_HTTP="${'$'}(wdtt_diag_http_probe 'https://api.vk.ru/method/users.get?v=5.275')" + VK_DETAILS="${'$'}VK_DETAILS legacy api.vk.ru HTTPS: ${'$'}VK_API_RU_HTTP." + wdtt_diag_emit "INFO" "VK/OK с VPS (справочно)" "не влияет на основной VK-вход" "${'$'}VK_DETAILS Получение VK-токенов и решение капчи выполняются на телефоне, а не на VPS. Поэтому недоступность этих HTTPS-адресов именно с сервера не считается ошибкой туннеля; серверу важнее рабочая служба, UDP-порты, маршрутизация и выходной интернет." "Если туннель не стартует, запустите «Проверить устройство»: она проверяет api.vk.me, calls.okcdn.ru, DNS и резервную цепочку из реальной сети телефона." + + TELEGRAM_CONFIGURED=0 + if [ -r /etc/wdtt/passwords.json ] && grep -Eq '"bot_token"[[:space:]]*:[[:space:]]*"[^"]{10,}"' /etc/wdtt/passwords.json 2>/dev/null; then + TELEGRAM_CONFIGURED=1 + fi + TG_HTTP="${'$'}(wdtt_diag_http_probe https://api.telegram.org/)"; TG_HTTP_CODE="${'$'}?" + if [ "${'$'}TG_HTTP_CODE" = "0" ]; then + wdtt_diag_emit "INFO" "Telegram API" "доступен" "api.telegram.org: ${'$'}TG_HTTP. Настроен ли бот на сервере: ${'$'}([ "${'$'}TELEGRAM_CONFIGURED" = "1" ] && echo да || echo нет)." "" + elif [ "${'$'}TELEGRAM_CONFIGURED" = "1" ]; then + wdtt_diag_emit "WARNING" "Telegram API" "недоступен" "На сервере найден признак настроенного Telegram-бота, но api.telegram.org не отвечает: ${'$'}TG_HTTP." "Если бот нужен, проверьте DNS/HTTPS-доступ к Telegram API с VPS или ограничения региона/провайдера." + else + wdtt_diag_emit "INFO" "Telegram API" "не проверен как обязательный" "api.telegram.org не отвечает: ${'$'}TG_HTTP. Бот на сервере не выглядит настроенным, поэтому это не мешает основному туннелю." "" + fi + + WARP_WARN=0 + WARP_DETAILS="" + WARP_API_HTTP="${'$'}(wdtt_diag_http_probe https://api.cloudflareclient.com/)"; WARP_API_HTTP_CODE="${'$'}?" + [ "${'$'}WARP_API_HTTP_CODE" = "0" ] || WARP_WARN=1 + WARP_DETAILS="${'$'}WARP_DETAILS регистрация api.cloudflareclient.com: ${'$'}WARP_API_HTTP;" + CF_TRACE="${'$'}(curl -4fsS --connect-timeout 3 --max-time 6 https://www.cloudflare.com/cdn-cgi/trace 2>/dev/null)" + if [ -n "${'$'}CF_TRACE" ]; then + CF_WARP="${'$'}(printf '%s\n' "${'$'}CF_TRACE" | sed -n 's/^warp=//p' | head -n 1)" + CF_COLO="${'$'}(printf '%s\n' "${'$'}CF_TRACE" | sed -n 's/^colo=//p' | head -n 1)" + WARP_DETAILS="${'$'}WARP_DETAILS Cloudflare trace доступен: warp=${'$'}{CF_WARP:-не указано}, colo=${'$'}{CF_COLO:-не указано};" + else + WARP_WARN=1 + WARP_DETAILS="${'$'}WARP_DETAILS Cloudflare trace недоступен;" + fi + WGCF_HTTP="${'$'}(wdtt_diag_http_probe "${'$'}WDTT_WGCF_URL")"; WGCF_HTTP_CODE="${'$'}?" + [ "${'$'}WGCF_HTTP_CODE" = "0" ] || WARP_WARN=1 + WARP_DETAILS="${'$'}WARP_DETAILS wgcf download: ${'$'}WGCF_HTTP;" + WGCF_API_HTTP="${'$'}(wdtt_diag_http_probe "${'$'}WDTT_WGCF_API")"; WGCF_API_HTTP_CODE="${'$'}?" + [ "${'$'}WGCF_API_HTTP_CODE" = "0" ] || WARP_WARN=1 + WARP_DETAILS="${'$'}WARP_DETAILS GitHub API wgcf: ${'$'}WGCF_API_HTTP;" + ENGAGE_IP="${'$'}(wdtt_diag_resolve_host engage.cloudflareclient.com)" + if [ -n "${'$'}ENGAGE_IP" ]; then + WARP_DETAILS="${'$'}WARP_DETAILS engage.cloudflareclient.com DNS: ${'$'}ENGAGE_IP;" + else + WARP_WARN=1 + WARP_DETAILS="${'$'}WARP_DETAILS engage.cloudflareclient.com DNS: не разрешается;" + fi + WARP_UDP_2408="${'$'}(wdtt_diag_udp_probe engage.cloudflareclient.com 2408)"; WARP_UDP_2408_CODE="${'$'}?" + [ "${'$'}WARP_UDP_2408_CODE" = "1" ] && WARP_WARN=1 + WARP_DETAILS="${'$'}WARP_DETAILS UDP 2408: ${'$'}WARP_UDP_2408;" + WARP_UDP_500="${'$'}(wdtt_diag_udp_probe engage.cloudflareclient.com 500)"; WARP_UDP_500_CODE="${'$'}?" + [ "${'$'}WARP_UDP_500_CODE" = "1" ] && WARP_WARN=1 + WARP_DETAILS="${'$'}WARP_DETAILS UDP 500: ${'$'}WARP_UDP_500;" + WARP_STACK="${'$'}(wdtt_diag_wireguard_kernel)" + WARP_STACK_CODE="${'$'}?" + [ "${'$'}WARP_STACK_CODE" = "0" ] || WARP_WARN=1 + WARP_DETAILS="${'$'}WARP_DETAILS ${'$'}WARP_STACK; wg=${'$'}(wdtt_diag_cmd wg && echo есть || echo нет); wg-quick=${'$'}(wdtt_diag_cmd wg-quick && echo есть || echo нет)." + if [ "${'$'}WARP_WARN" = "0" ]; then + wdtt_diag_emit "OK" "Бесплатный WARP" "предпосылки выглядят рабочими" "${'$'}WARP_DETAILS" "Это не гарантирует регистрацию WARP: Cloudflare может временно ограничивать регион/VPS, но базовая сеть и инструменты выглядят пригодными." + else + wdtt_diag_emit "WARNING" "Бесплатный WARP" "есть риск, что не заработает" "${'$'}WARP_DETAILS" "Проверьте исходящий HTTPS к Cloudflare/GitHub, UDP к WARP endpoint, WireGuard-стек ядра и попробуйте другой MTU/endpoint или регион VPS." + fi + + printf '%s\n' 'WDTT_SERVER_DIAG_COMPLETE=1' """.trimIndent() } @@ -6722,6 +7128,61 @@ private fun parseServerDiagnosticsItems(output: String): List = } .toList() +internal fun serverDiagnosticsOutputIssue(output: String): String? { + val lower = output.lowercase(Locale.ROOT) + return when { + "ssh channel closed before exit status" in lower || + "ssh channel interrupted" in lower || + "remote command exited with code -1" in lower || + "session is down" in lower -> + "SSH-канал закрылся без подтверждения завершения команды. Ответ сервера может быть неполным." + "error: timeout" in lower -> + "Превышено время ожидания ответа VPS. Проверка остановлена; ответ может быть неполным." + Regex("(?m)^error: remote command exited with code [1-9]").containsMatchIn(lower) -> + "Команда проверки завершилась с ошибкой на VPS. Полученные пункты могут быть неполными." + output.lineSequence().any { it.trimStart().startsWith("error:", ignoreCase = true) } -> + "SSH-команда не завершилась. Ответ сервера может быть неполным." + else -> null + } +} + +internal fun serverDiagnosticsSshInterrupted(output: String): Boolean { + val lower = output.lowercase(Locale.ROOT) + return "ssh channel closed before exit status" in lower || + "ssh channel interrupted" in lower || + "remote command exited with code -1" in lower || + "session is down" in lower || + "error: timeout" in lower +} + +internal fun serverDiagnosticsCompletionItem(output: String, directInspection: Boolean): DeviceCheckItem? { + val issue = serverDiagnosticsOutputIssue(output) + return when { + issue != null -> DeviceCheckItem( + title = "Полнота диагностики", + status = "ответ прерван", + details = issue, + recommendation = "Повторите проверку при стабильном соединении. Полученные выше пункты сохраняются для анализа.", + severity = DeviceCheckSeverity.Warning, + ) + markerValue(output, "WDTT_SERVER_DIAG_COMPLETE") == "1" -> null + !directInspection -> DeviceCheckItem( + title = "Объём диагностики", + status = "сокращённая проверка", + details = "Получены только доступные сведения сервера. Расширенные проверки ОС и сети не выполнялись.", + recommendation = "Для полной проверки откройте «Деплой» при доступном прямом SSH-подключении.", + severity = DeviceCheckSeverity.Info, + ) + else -> DeviceCheckItem( + title = "Полнота диагностики", + status = "ответ не завершён", + details = "Полученные пункты сохранены, но сервер не подтвердил завершение полной проверки.", + recommendation = "Повторите проверку при стабильном SSH-соединении.", + severity = DeviceCheckSeverity.Warning, + ) + } +} + private fun serverDiagnosticsErrorReport( title: String, status: String, @@ -6784,9 +7245,9 @@ private suspend fun collectServerDiagnostics( profileIndex: Int, expectedDtlsPort: Int, expectedWgPort: Int, - expectedClientPort: Int + expectedClientPort: Int, + connectionProfile: com.wdtt.plus.TunnelProfileSnapshot?, ): DeviceCompatibilityReport = withContext(Dispatchers.IO) { - val checkedAt = System.currentTimeMillis() val authLabel = if (selectedAuthMode == "key") "SSH-ключ" else "логин/пароль" val localItems = mutableListOf( serverProfileDiagnosticItem(profileName, profileIndex), @@ -6798,6 +7259,18 @@ private suspend fun collectServerDiagnostics( severity = DeviceCheckSeverity.Ok ) ) + connectionProfile?.let { + localItems += com.wdtt.plus.connectionModeDiagnostic(it.rtNetwork) + } + localItems += DeviceCheckItem( + title = "Границы проверки", + status = "проверяется сервер, а не сеть оператора", + details = "Режимы «UDP» и «TCP/TLS» относятся к внешнему пути телефона. Оба проверяют ответ сервера и восстанавливают потерянные каналы. На WDTT-сервере UDP-порты по-прежнему нужны. Прослушивание порта не доказывает его доступность извне или работу пути через TURN/MASQUE.", + recommendation = "Для проверки пути запустите подключение и откройте «Логи». «Проверить устройство» проверяет сеть телефона. Эта диагностика не определяет блокировку SIM.", + severity = DeviceCheckSeverity.Info, + ) + var directInspection = false + val inspectionStartedAt = System.nanoTime() val output = runSafeInspection( target = target, relayOperation = listOf( @@ -6806,8 +7279,9 @@ private suspend fun collectServerDiagnostics( expectedWgPort.toString(), expectedClientPort.toString(), ), - timeout = 150000L, + timeout = 80_000L, ) { ssh -> + directInspection = true ssh.exec( rootShCommand( serverDiagnosticsScript( @@ -6816,23 +7290,57 @@ private suspend fun collectServerDiagnostics( expectedClientPort = expectedClientPort ) ), - timeout = 150000L + // Leave time to return the partial report before the outer deadline. + timeout = (85_000L - (System.nanoTime() - inspectionStartedAt) / 1_000_000L).coerceAtLeast(1_000L), + preservePartialOnFailure = true, ) }.trim() val remoteItems = parseServerDiagnosticsItems(output) + val outputIssue = serverDiagnosticsOutputIssue(output) + if (!directInspection) { + localItems[1] = DeviceCheckItem( + title = "Доступ к серверу", + status = "через работающий WDTT", + details = "Прямое SSH-подключение не ответило. Сведения получены через безопасную проверку серверной части WDTT.", + recommendation = "Для расширенной диагностики нужен прямой SSH-доступ к выбранному VPS.", + severity = DeviceCheckSeverity.Info, + ) + } else if (serverDiagnosticsSshInterrupted(output)) { + localItems[1] = localItems[1].copy( + status = "проверка прервана", + details = "SSH-подключение к ${target.host}:${target.port} было установлено. ${outputIssue.orEmpty()}", + recommendation = "Проверьте устойчивость сети телефона и повторите диагностику. Состояние VPS нельзя оценить по неполному ответу.", + severity = DeviceCheckSeverity.Warning, + ) + } if (remoteItems.isNotEmpty()) { - DeviceCompatibilityReport(checkedAt = checkedAt, items = localItems + remoteItems) + val completionItem = serverDiagnosticsCompletionItem(output, directInspection) + DeviceCompatibilityReport( + checkedAt = System.currentTimeMillis(), + items = localItems + remoteItems + listOfNotNull(completionItem), + ) } else { + val sudoFailure = friendlyAdminSudoError(output) + val commandTooLong = output.contains("Argument list too long", ignoreCase = true) localItems += DeviceCheckItem( - title = "Root/sudo диагностика", + title = if (sudoFailure != null) "Root/sudo диагностика" else "Серверная диагностика", status = "не выполнена", - details = compactRemoteTail(output).ifBlank { - "Сервер не вернул диагностические строки. Вероятно, не сработали root-права, sudo, bash или безопасный канал управления." + details = when { + sudoFailure != null -> sudoFailure + commandTooLong -> "Команда проверки превысила лимит аргументов оболочки сервера." + outputIssue != null -> outputIssue + else -> compactRemoteTail(output).ifBlank { + "Сервер не вернул диагностические строки." + } + }, + recommendation = when { + sudoFailure != null -> "Проверьте права выбранного SSH-пользователя и повторите проверку." + commandTooLong -> "Обновите приложение и запустите проверку снова." + else -> "Повторите проверку. Если ошибка сохраняется, проверьте SSH-соединение и откройте «Логи»." }, - recommendation = "Для полной диагностики и установки нужны root-права или рабочий sudo для выбранного SSH-пользователя. Серверы без bash/systemd могут потребовать ручной настройки.", severity = DeviceCheckSeverity.Warning ) - DeviceCompatibilityReport(checkedAt = checkedAt, items = localItems) + DeviceCompatibilityReport(checkedAt = System.currentTimeMillis(), items = localItems) } } @@ -6900,7 +7408,7 @@ private suspend fun runSafeInspection( if (session != null) { // Команда выполняется только после успешного подключения. После её // отправки второй путь не запускается, чтобы ничего не дублировать. - return@withContext direct(SSHClient(session, target.pass)).trim() + return@withContext runInterruptible { direct(SSHClient(session, target.pass)).trim() } } } finally { runCatching { session?.disconnect() } @@ -6909,7 +7417,7 @@ private suspend fun runSafeInspection( if (!relayReady) { throw IllegalStateException( relayAvailability?.unavailableMessage() - ?: "Откройте «Секреты» и укажите главный пароль администратора.", + ?: "Откройте параметры сервера и укажите главный пароль администратора.", directFailure, ) } @@ -6934,7 +7442,7 @@ private suspend fun runSafeInspection( var legacySession: Session? = null try { legacySession = createSafeReadOnlySshSession(target) - return@withContext direct(SSHClient(legacySession, target.pass)).trim() + return@withContext runInterruptible { direct(SSHClient(legacySession, target.pass)).trim() } } finally { runCatching { legacySession?.disconnect() } } @@ -6963,23 +7471,44 @@ private fun createCriticalSshSession( routePolicy = SshRoutePolicy.SERVER_MUTATION_DIRECT_ONLY, ) +private fun recordRemoteCommandEvent(event: RemoteLogEvent) { + val safeMessage = remoteCommandOutputCapture.get()?.sanitize(event.message) ?: redactRemoteDiagnostics(event.message) + val userText = remoteEventUserText(event.copy(message = safeMessage)) + when (event.category) { + RemoteLogCategory.Error -> { + DeployManager.writeError(userText) + TunnelManager.addDeployErrorLog(userText) + } + RemoteLogCategory.Warning -> TunnelManager.addDeployMessageLog(userText, warning = true) + RemoteLogCategory.Info -> if (event.message.startsWith("systemd:")) TunnelManager.addDeployMessageLog(userText) + RemoteLogCategory.Technical -> Unit // Preserved in command output for the caller. + } +} + private class SSHClient(private val session: Session, private val pass: String) { - fun exec(command: String, timeout: Long = CMD_TIMEOUT): String { + fun exec( + command: String, + timeout: Long = CMD_TIMEOUT, + preservePartialOnFailure: Boolean = false, + ): String { if (!session.isConnected) { - DeployManager.writeError("SSH exec: сессия разорвана перед командой: ${command.take(80)}") + DeployManager.writeError("SSH: соединение с сервером потеряно перед выполнением команды.") return "error: session is down" } var channel: ChannelExec? = null val result = StringBuilder() + val stderrLines = ArrayDeque() + val startedAt = System.nanoTime() return try { + val plan = buildSshExecStdinPlan(command, pass) channel = session.openChannel("exec") as ChannelExec // Root-команды сами явно выбирают sudo -S. Нельзя переписывать // произвольный текст: строка `command -v sudo` — это проверка // наличия программы, а не её запуск. - val cmd = command + val cmd = plan?.command ?: command channel.setCommand(cmd) val outStream = channel.outputStream @@ -6987,20 +7516,24 @@ private class SSHClient(private val session: Session, private val pass: String) val err = channel.errStream channel.connect(15000) - if (cmd.contains("sudo -S")) { - outStream.write("$pass\n".toByteArray()) + if (plan != null) { + outStream.write(plan.stdinPayload.toByteArray(Charsets.UTF_8)) outStream.flush() + outStream.close() } val reader = input.bufferedReader() val errReader = err.bufferedReader() - val startTime = System.currentTimeMillis() val progressRegex = Regex("^WDTT_PROGRESS\\|(\\d+\\.?\\d*)\\|(.+)$") while (!channel.isClosed || reader.ready() || errReader.ready()) { - if (System.currentTimeMillis() - startTime > timeout) { - DeployManager.writeError("SSH timeout (${timeout/1000}s): ${command.take(80)}") + if ((System.nanoTime() - startedAt) / 1_000_000L > timeout) { + DeployManager.writeError("SSH: сервер не завершил команду за ${timeout/1000} с.") try { channel.disconnect() } catch (_: Exception) {} + if (preservePartialOnFailure) { + result.appendLine("error: timeout") + return result.toString() + } return "error: timeout" } @@ -7014,9 +7547,9 @@ private class SSHClient(private val session: Session, private val pass: String) } else if (!line.contains("WDTT_PROGRESS")) { val clean = line.replace(Regex("\u001B\\[[;\\d]*m"), "") result.appendLine(clean) - remoteErrorMessageForUserLog(clean)?.let { message -> - DeployManager.writeError(message) - TunnelManager.addDeployErrorLog(message) + val event = classifyRemoteCommandLine(clean) + if (event.category == RemoteLogCategory.Error || event.category == RemoteLogCategory.Warning) { + recordRemoteCommandEvent(event) } } } @@ -7026,22 +7559,39 @@ private class SSHClient(private val session: Session, private val pass: String) if (line != null && !line.contains("password for")) { val clean = line.replace(Regex("\u001B\\[[;\\d]*m"), "") result.appendLine(clean) - if (clean.isNotBlank() && !clean.startsWith("Warning:")) { - val message = "Ошибка на сервере: $clean" - DeployManager.writeError(message) - TunnelManager.addDeployErrorLog(message) - } + // Defer unknown stderr severity until SSH reports the exit status. + if (stderrLines.size == 200) stderrLines.removeFirst() + stderrLines.addLast(clean) } } if (!reader.ready() && !errReader.ready()) Thread.sleep(100) } + stderrLines.forEach { line -> + recordRemoteCommandEvent(classifyRemoteCommandLine(line, channel.exitStatus, stderr = true)) + } + if (channel.exitStatus < 0) { + if (!preservePartialOnFailure) return "error: SSH channel closed before exit status" + result.appendLine("error: SSH channel closed before exit status") + } else if (channel.exitStatus != 0) { + result.appendLine("error: remote command exited with code ${channel.exitStatus}") + } result.toString() + } catch (e: InterruptedException) { + throw e + } catch (e: java.io.InterruptedIOException) { + throw e } catch (e: Exception) { - DeployManager.writeError("SSH exec error: ${e.message} | cmd: ${command.take(80)}") - TunnelManager.addDeployErrorLog("SSH exec error: ${e.message}") + remoteCommandOutputCapture.get()?.append("SSH: ${e.message}") + DeployManager.writeError("SSH: не удалось выполнить команду на сервере.") + TunnelManager.addDeployErrorLog("Не удалось выполнить команду по SSH. Подробности — в результате действия.") + if (preservePartialOnFailure && result.isNotEmpty()) { + result.appendLine("error: SSH channel interrupted") + return result.toString() + } "error: ${e.message}" } finally { + remoteCommandOutputCapture.get()?.append(result.toString()) try { channel?.disconnect() } catch (_: Exception) {} } } @@ -7123,7 +7673,8 @@ private suspend fun runRootScript( directFile.delete() } }.also { output -> - markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(output.take(1200)) } + remoteCommandOutputCapture.get()?.append(output) + markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(rootScriptErrorExcerpt(output)) } if (output.startsWith("error:", true) || output.contains("\nerror:", true)) { throw IllegalStateException(output.take(500)) } @@ -7145,7 +7696,7 @@ private suspend fun runRootScript( rootCommand("chmod 700 $remotePath; bash $remotePath; code=\$?; rm -f $remotePath; exit \$code"), timeout = timeout ) - markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(output.trim().take(1200)) } + markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(rootScriptErrorExcerpt(output)) } if (output.startsWith("error:", ignoreCase = true) || output.contains("\nerror:", ignoreCase = true)) { throw IllegalStateException(output.trim().take(500)) } @@ -7167,9 +7718,9 @@ private suspend fun runCheckedRootScript( val output = runSafeInspection(target, relayOperation, timeout) { ssh -> ssh.exec(rootCommand(script), timeout = timeout) }.trim() - markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(output.take(1200)) } + markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(rootScriptErrorExcerpt(output)) } if (output.startsWith("error:", true) || output.contains("\nerror:", true)) { - throw IllegalStateException(output.take(1200)) + throw IllegalStateException(rootScriptErrorExcerpt(output)) } return@withContext output } @@ -7184,12 +7735,12 @@ private suspend fun runCheckedRootScript( .exec(rootCommand(script), timeout = timeout) .trim() markerValue(output, "WDTT_ERROR")?.let { - throw IllegalStateException(output.take(1200)) + throw IllegalStateException(rootScriptErrorExcerpt(output)) } if (output.startsWith("error:", ignoreCase = true) || output.contains("\nerror:", ignoreCase = true) ) { - throw IllegalStateException(output.take(1200)) + throw IllegalStateException(rootScriptErrorExcerpt(output)) } output } finally { @@ -7273,6 +7824,7 @@ internal fun outboundShellPrelude(): String = """ wdtt_clear_proxy_out() { if command -v iptables >/dev/null 2>&1; then while iptables -t nat -D PREROUTING -i "${'$'}WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null; do :; done + while iptables -D INPUT -i "${'$'}WDTT_IFACE" -s "${'$'}WDTT_SUBNET" -p tcp --dport 12345 -m comment --comment WDTT_PROXY_OUT -j ACCEPT 2>/dev/null; do :; done iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true fi @@ -7284,6 +7836,8 @@ internal fun outboundShellPrelude(): String = """ systemctl disable --now wdtt-warp-watchdog.timer 2>/dev/null || true systemctl disable --now wdtt-wg-exit.service 2>/dev/null || true if command -v iptables >/dev/null 2>&1; then + while iptables -D FORWARD -i "${'$'}WDTT_IFACE" -o "${'$'}WDTT_WG_IFACE" -s "${'$'}WDTT_SUBNET" -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT 2>/dev/null; do :; done + while iptables -D FORWARD -i "${'$'}WDTT_WG_IFACE" -o "${'$'}WDTT_IFACE" -d "${'$'}WDTT_SUBNET" -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT 2>/dev/null; do :; done while iptables -t nat -D POSTROUTING -s "${'$'}WDTT_SUBNET" -o "${'$'}WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null; do :; done fi while ip rule del from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TABLE" priority 100 2>/dev/null; do :; done @@ -7365,9 +7919,11 @@ internal fun outboundShellPrelude(): String = """ chain="${'$'}1" proxy_ip="${'$'}2" for net in 0.0.0.0/8 10.0.0.0/8 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 224.0.0.0/4 240.0.0.0/4; do - iptables -t nat -A "${'$'}chain" -d "${'$'}net" -j RETURN + iptables -t nat -A "${'$'}chain" -d "${'$'}net" -j RETURN || return 1 done - [ -n "${'$'}proxy_ip" ] && iptables -t nat -A "${'$'}chain" -d "${'$'}proxy_ip" -j RETURN 2>/dev/null || true + if [ -n "${'$'}proxy_ip" ]; then + iptables -t nat -A "${'$'}chain" -d "${'$'}proxy_ip" -j RETURN || return 1 + fi } wdtt_cleanup_proxy_test() { cleanup_test_source="${'$'}{WDTT_PROXY_TEST_SOURCE:-}" @@ -7376,31 +7932,13 @@ internal fun outboundShellPrelude(): String = """ iptables -t nat -D OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST 2>/dev/null || true iptables -t nat -F WDTT_PROXY_TEST 2>/dev/null || true iptables -t nat -X WDTT_PROXY_TEST 2>/dev/null || true + if [ -n "${'$'}cleanup_test_source" ]; then + iptables -D INPUT -i lo -s "${'$'}cleanup_test_source" -d 127.0.0.1 -p tcp --dport 12345 -m comment --comment WDTT_PROXY_TEST -j ACCEPT 2>/dev/null || true + fi WDTT_PROXY_TEST_SOURCE="" } - wdtt_test_redsocks_path() { - proxy_ip="${'$'}1" - systemctl is-active --quiet wdtt-redsocks || { echo WDTT_ERROR=external_proxy_service_inactive; return 1; } - command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; return 1; } - test_source="${'$'}(wdtt_test_source)" - [ -n "${'$'}test_source" ] || { echo WDTT_ERROR=wdtt_iface_not_found; return 1; } - wdtt_cleanup_proxy_test - WDTT_PROXY_TEST_SOURCE="${'$'}test_source" - iptables -t nat -N WDTT_PROXY_TEST 2>/dev/null || true - iptables -t nat -F WDTT_PROXY_TEST - wdtt_proxy_reserved_returns WDTT_PROXY_TEST "${'$'}proxy_ip" - iptables -t nat -A WDTT_PROXY_TEST -p tcp -j REDIRECT --to-ports 12345 - if ! iptables -t nat -I OUTPUT -s "${'$'}test_source" -p tcp -j WDTT_PROXY_TEST 2>/dev/null; then - wdtt_cleanup_proxy_test - echo WDTT_ERROR=external_proxy_test_rule_failed - return 1 - fi - test_ip="${'$'}(curl --interface "${'$'}test_source" -4fsS --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/tmp/wdtt-redsocks-test.err || true)" - wdtt_cleanup_proxy_test - [ -n "${'$'}test_ip" ] || { echo WDTT_ERROR=external_proxy_apply_failed; tail -n 20 /var/log/wdtt-redsocks.log 2>/dev/null || true; cat /tmp/wdtt-redsocks-test.err 2>/dev/null || true; return 1; } - echo "Проверка пути через внешний TCP-прокси успешна. IP через прокси: ${'$'}test_ip" - return 0 - } + ${outboundProbeFunctions().replace("\n", "\n ")} + ${externalProxyProbeFunctions().replace("\n", "\n ")} wdtt_write_mode() { mode="${'$'}1" detail="${'$'}2" @@ -7459,8 +7997,10 @@ internal fun outboundStatusScript(): String = shellScript( ;; warp_free|imported_wg|wireguard_vps|tun_interface) TEST_SOURCE="${'$'}(wdtt_test_source)" + STATUS_EXIT_IFACE=wg-wdtt-exit + [ "${'$'}MODE" != tun_interface ] || STATUS_EXIT_IFACE="${'$'}(cat "${'$'}WDTT_TUN_CONFIG_FILE" 2>/dev/null | head -n 1)" WDTT_EXIT_IP="" - [ -n "${'$'}TEST_SOURCE" ] && WDTT_EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}TEST_SOURCE" --max-time 12 https://api.ipify.org 2>/dev/null || true)" + [ -n "${'$'}TEST_SOURCE" ] && WDTT_EXIT_IP="${'$'}(wdtt_routed_public_ip "${'$'}TEST_SOURCE" "${'$'}STATUS_EXIT_IFACE" || true)" if [ -n "${'$'}WDTT_EXIT_IP" ]; then echo "Проверочный выход WDTT: ${'$'}WDTT_EXIT_IP" else @@ -7473,7 +8013,7 @@ internal fun outboundStatusScript(): String = shellScript( fi if [ "${'$'}MODE" = "warp_free" ]; then WARP_TRACE="" - [ -n "${'$'}TEST_SOURCE" ] && WARP_TRACE="${'$'}(curl -4fsS --interface "${'$'}TEST_SOURCE" --max-time 15 https://www.cloudflare.com/cdn-cgi/trace 2>/dev/null || true)" + [ -n "${'$'}TEST_SOURCE" ] && WARP_TRACE="${'$'}(wdtt_routed_https "${'$'}TEST_SOURCE" "wg-wdtt-exit" https://www.cloudflare.com/cdn-cgi/trace || true)" WARP_STATE="${'$'}(printf '%s\n' "${'$'}WARP_TRACE" | sed -n 's/^warp=//p' | head -n 1)" echo "Cloudflare WARP: ${'$'}{WARP_STATE:-проверка не пройдена}" echo "Автопроверка WARP: ${'$'}(systemctl is-active wdtt-warp-watchdog.timer 2>/dev/null || echo не запущена)" @@ -8249,9 +8789,9 @@ private suspend fun checkWireGuardExit( echo "WireGuard ${'$'}WDTT_WG_IFACE запущен." TEST_SOURCE="${'$'}(wdtt_test_source)" [ -n "${'$'}TEST_SOURCE" ] || { echo WDTT_ERROR=wdtt_test_source_missing; exit 3; } - EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}TEST_SOURCE" --max-time 12 https://api.ipify.org 2>/dev/null || true)" + EXIT_IP="${'$'}(wdtt_routed_public_ip "${'$'}TEST_SOURCE" "wg-wdtt-exit" || true)" if [ -n "${'$'}EXIT_IP" ]; then - echo "Проверка успешна: WDTT-пользователи выходят через WireGuard. Проверочный IP: ${'$'}EXIT_IP" + echo "Проверка маршрута сервера через WireGuard успешна. Проверочный IP: ${'$'}EXIT_IP" else echo WDTT_ERROR=wireguard_exit_check_failed exit 3 @@ -8483,9 +9023,9 @@ internal fun buildTunInterfaceExitScript(interfaceName: String): String { } block() { blocked_status && return 0 - ip route replace unreachable default table "${'$'}WDTT_TUN_TABLE" + ip route replace unreachable default table "${'$'}WDTT_TUN_TABLE" || exit 1 policy_rule_present || - ip rule add from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TUN_TABLE" priority "${'$'}WDTT_TUN_PRIORITY" + ip rule add from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TUN_TABLE" priority "${'$'}WDTT_TUN_PRIORITY" || exit 1 blocked_status } case "${'$'}{1:-}" in @@ -8496,7 +9036,7 @@ internal fun buildTunInterfaceExitScript(interfaceName: String): String { cleanup ;; status) - status + status || exit 1 ;; up) if [ "${'$'}(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null)" != "1" ]; then @@ -8510,15 +9050,15 @@ internal fun buildTunInterfaceExitScript(interfaceName: String): String { [ -n "${'$'}EXT_IFACE" ] && [ "${'$'}TUN_IFACE" != "${'$'}EXT_IFACE" ] || exit 1 # Сначала удерживаем подсеть на unreachable-маршруте. Рабочий # default через TUN ставим только после полной подготовки правил. - ip route replace unreachable default table "${'$'}WDTT_TUN_TABLE" + ip route replace unreachable default table "${'$'}WDTT_TUN_TABLE" || exit 1 policy_rule_present || - ip rule add from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TUN_TABLE" priority "${'$'}WDTT_TUN_PRIORITY" + ip rule add from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TUN_TABLE" priority "${'$'}WDTT_TUN_PRIORITY" || exit 1 trap 'code=${'$'}?; trap - 0; [ "${'$'}code" -eq 0 ] || block; exit "${'$'}code"' 0 clear_forward_rules - iptables -A FORWARD -i "${'$'}WDTT_IFACE" -o "${'$'}TUN_IFACE" -m comment --comment WDTT_TUN_EXIT -j ACCEPT - iptables -A FORWARD -i "${'$'}TUN_IFACE" -o "${'$'}WDTT_IFACE" -m comment --comment WDTT_TUN_EXIT -j ACCEPT - ip route replace default dev "${'$'}TUN_IFACE" table "${'$'}WDTT_TUN_TABLE" - status + iptables -I FORWARD -i "${'$'}WDTT_IFACE" -o "${'$'}TUN_IFACE" -m comment --comment WDTT_TUN_EXIT -j ACCEPT || exit 1 + iptables -I FORWARD -i "${'$'}TUN_IFACE" -o "${'$'}WDTT_IFACE" -m comment --comment WDTT_TUN_EXIT -j ACCEPT || exit 1 + ip route replace default dev "${'$'}TUN_IFACE" table "${'$'}WDTT_TUN_TABLE" || exit 1 + status || exit 1 trap - 0 ;; *) exit 2;; @@ -8617,16 +9157,13 @@ internal fun buildTunInterfaceExitScript(interfaceName: String): String { echo WDTT_ERROR=wdtt_test_source_missing exit 3 } - EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}TEST_SOURCE" --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/tmp/wdtt-tun-exit-test.err || true)" + EXIT_IP="${'$'}(wdtt_routed_public_ip "${'$'}TEST_SOURCE" "${'$'}TUN_IFACE" || true)" if [ -z "${'$'}EXIT_IP" ]; then - tail -n 10 /tmp/wdtt-tun-exit-test.err 2>/dev/null || true - rm -f /tmp/wdtt-tun-exit-test.err wdtt_clear_tun_out wdtt_write_mode "direct" "rollback after TUN traffic test error" echo WDTT_ERROR=tun_exit_check_failed exit 3 fi - rm -f /tmp/wdtt-tun-exit-test.err echo "WDTT_PROGRESS|0.94|Сохраняю режим выхода через TUN-интерфейс..." wdtt_write_mode "tun_interface" "${'$'}TUN_IFACE" TUN_COMMITTED=1 @@ -8660,9 +9197,9 @@ internal fun checkTunInterfaceExitScript(interfaceName: String): String { /usr/local/lib/wdtt/tun-exit-route status >/dev/null 2>&1 || { echo WDTT_ERROR=tun_exit_route_inactive; exit 3; } TEST_SOURCE="${'$'}(wdtt_test_source)" [ -n "${'$'}TEST_SOURCE" ] || { echo WDTT_ERROR=wdtt_test_source_missing; exit 3; } - EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}TEST_SOURCE" --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/dev/null || true)" + EXIT_IP="${'$'}(wdtt_routed_public_ip "${'$'}TEST_SOURCE" "${'$'}TUN_IFACE" || true)" [ -n "${'$'}EXIT_IP" ] || { echo WDTT_ERROR=tun_exit_check_failed; exit 3; } - echo "Проверка успешна: WDTT-пользователи выходят через TUN-интерфейс ${'$'}TUN_IFACE. Проверочный IP: ${'$'}EXIT_IP" + echo "Проверка маршрута сервера через TUN-интерфейс ${'$'}TUN_IFACE. Проверочный IP: ${'$'}EXIT_IP" """ ) } @@ -8921,8 +9458,9 @@ internal fun buildLocalProxyInstallScript( /usr/local/lib/wdtt/local-proxy-firewall up || { echo WDTT_ERROR=local_proxy_firewall_failed; systemctl disable --now wdtt-3proxy 2>/dev/null || true; exit 3; } wdtt_progress 0.96 "Проверяю подключение через установленный SOCKS5..." - TEST_IP="${'$'}(curl --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" --socks5-hostname "127.0.0.1:${'$'}PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" - [ -n "${'$'}TEST_IP" ] || + ${outboundProbeFunctions().replace("\n", "\n ")} + TEST_IP="${'$'}(curl -q --noproxy '' --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" --socks5-hostname "127.0.0.1:${'$'}PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null)" || TEST_IP="" + wdtt_probe_ipv4 "${'$'}TEST_IP" || { systemctl disable --now wdtt-3proxy 2>/dev/null || true; echo WDTT_ERROR=local_proxy_check_failed; exit 3; } SERVER_IP="${'$'}(curl -4fsS --max-time 8 https://api.ipify.org 2>/dev/null || hostname -I | awk '{print ${'$'}1}')" cat >/etc/wdtt/local-proxy.json </dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; exit 2; } echo "WDTT_PROGRESS|0.70|Подключаюсь через SOCKS5 127.0.0.1:${'$'}PROXY_PORT..." - IP="${'$'}(curl --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" --socks5-hostname "127.0.0.1:${'$'}PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" - [ -n "${'$'}IP" ] || { echo WDTT_ERROR=local_proxy_check_failed; exit 3; } + ${outboundProbeFunctions().replace("\n", "\n ")} + IP="${'$'}(curl -q --noproxy '' --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" --socks5-hostname "127.0.0.1:${'$'}PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null)" || IP="" + wdtt_probe_ipv4 "${'$'}IP" || { echo WDTT_ERROR=local_proxy_check_failed; exit 3; } echo "WDTT_PROGRESS|1.0|Прокси отвечает." echo "Проверка успешна: SOCKS5 на 127.0.0.1:${'$'}PROXY_PORT отвечает с указанными логином и паролем. Выходной IP: ${'$'}IP" """.trimIndent() @@ -9074,22 +9613,25 @@ private suspend fun checkExternalProxy( } val scheme = if (kind == ProxyKind.Socks5) "socks5h" else "http" val proxyUri = "$scheme://$host:$port" - val script = """ + val script = shellScript(externalProxyProbeFunctions(), """ echo "WDTT_PROGRESS|0.25|Проверяю curl на сервере..." command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; exit 2; } echo "WDTT_PROGRESS|0.55|Пробую выйти в интернет через указанный ${kind.label}..." PROXY_URI=${shellQuote(proxyUri)} PROXY_LOGIN=${shellQuote(login)} PROXY_PASSWORD=${shellQuote(proxyPassword)} + CHECK_EXIT=0 if [ -n "${'$'}PROXY_LOGIN" ]; then - IP="${'$'}(curl --proxy "${'$'}PROXY_URI" --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)" + ${outboundProbeFunctions().replace("\n", "\n ")} + IP="${'$'}(curl -q --noproxy '' --proxy "${'$'}PROXY_URI" --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null)" || CHECK_EXIT=${'$'}? else - IP="${'$'}(curl --proxy "${'$'}PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)" + ${outboundProbeFunctions().replace("\n", "\n ")} + IP="${'$'}(curl -q --noproxy '' --proxy "${'$'}PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null)" || CHECK_EXIT=${'$'}? fi - [ -n "${'$'}IP" ] || { echo WDTT_ERROR=external_proxy_check_failed; exit 3; } + [ "${'$'}CHECK_EXIT" = 0 ] && wdtt_valid_proxy_test_ip "${'$'}IP" || { echo WDTT_ERROR=external_proxy_check_failed; exit 3; } echo "WDTT_PROGRESS|1.0|Внешний TCP-прокси отвечает." echo "Проверка успешна: ${kind.label} отвечает, сервер смог открыть проверочный сайт через него. IP через прокси: ${'$'}IP" - """.trimIndent() + """.trimIndent()) return runRootScript( context, target, @@ -9113,7 +9655,10 @@ internal fun externalProxyRoutesScript(): String = """ action="${'$'}{1:-}" PROXY_IP="${'$'}{2:-}" WDTT_IFACE=wdtt0 + WDTT_SUBNET="${'$'}(ip -4 route show dev "${'$'}WDTT_IFACE" scope link | awk '{print ${'$'}1; exit}')" + [ -n "${'$'}WDTT_SUBNET" ] || WDTT_SUBNET=10.66.66.0/24 cleanup() { + while iptables -D INPUT -i "${'$'}WDTT_IFACE" -s "${'$'}WDTT_SUBNET" -p tcp --dport 12345 -m comment --comment WDTT_PROXY_OUT -j ACCEPT 2>/dev/null; do :; done while iptables -t nat -D PREROUTING -i "${'$'}WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null; do :; done iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true @@ -9131,6 +9676,7 @@ internal fun externalProxyRoutesScript(): String = """ done iptables -t nat -A WDTT_PROXY_OUT -d "${'$'}PROXY_IP" -j RETURN iptables -t nat -A WDTT_PROXY_OUT -p tcp -j REDIRECT --to-ports 12345 + iptables -I INPUT -i "${'$'}WDTT_IFACE" -s "${'$'}WDTT_SUBNET" -p tcp --dport 12345 -m comment --comment WDTT_PROXY_OUT -j ACCEPT iptables -t nat -A PREROUTING -i "${'$'}WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT """.trimIndent() + "\n" @@ -9393,7 +9939,7 @@ internal fun sanitizeWireGuardConfigForWdttExit(config: String): String { return out.joinToString("\n").trim() + "\n" } -private fun wireGuardPolicyScript(mode: String, detail: String): String = shellScript( +internal fun wireGuardPolicyScript(mode: String, detail: String): String = shellScript( outboundShellPrelude(), """ [ -d /sys/class/net/"${'$'}WDTT_IFACE" ] || { echo WDTT_ERROR=wdtt_iface_not_found; exit 2; } @@ -9421,6 +9967,8 @@ private fun wireGuardPolicyScript(mode: String, detail: String): String = shellS trap - 0 if [ "${'$'}status" -ne 0 ]; then set +e + while iptables -D FORWARD -i "${'$'}WDTT_IFACE" -o "${'$'}WDTT_WG_IFACE" -s "${'$'}WDTT_SUBNET" -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT 2>/dev/null; do :; done + while iptables -D FORWARD -i "${'$'}WDTT_WG_IFACE" -o "${'$'}WDTT_IFACE" -d "${'$'}WDTT_SUBNET" -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT 2>/dev/null; do :; done iptables -t nat -D POSTROUTING -s "${'$'}WDTT_SUBNET" -o "${'$'}WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null while ip rule del from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TABLE" priority 100 2>/dev/null; do :; done ip route flush table "${'$'}WDTT_TABLE" 2>/dev/null @@ -9436,6 +9984,10 @@ private fun wireGuardPolicyScript(mode: String, detail: String): String = shellS ip route replace default dev "${'$'}WDTT_WG_IFACE" table "${'$'}WDTT_TABLE" iptables -t nat -C POSTROUTING -s "${'$'}WDTT_SUBNET" -o "${'$'}WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null || \ iptables -t nat -A POSTROUTING -s "${'$'}WDTT_SUBNET" -o "${'$'}WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE + while iptables -D FORWARD -i "${'$'}WDTT_IFACE" -o "${'$'}WDTT_WG_IFACE" -s "${'$'}WDTT_SUBNET" -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT 2>/dev/null; do :; done + while iptables -D FORWARD -i "${'$'}WDTT_WG_IFACE" -o "${'$'}WDTT_IFACE" -d "${'$'}WDTT_SUBNET" -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT 2>/dev/null; do :; done + iptables -I FORWARD -i "${'$'}WDTT_IFACE" -o "${'$'}WDTT_WG_IFACE" -s "${'$'}WDTT_SUBNET" -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT + iptables -I FORWARD -i "${'$'}WDTT_WG_IFACE" -o "${'$'}WDTT_IFACE" -d "${'$'}WDTT_SUBNET" -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT trap - 0 WDTT_WG_UP cat >/usr/local/lib/wdtt/wg-exit-down <<'WDTT_WG_DOWN' @@ -9445,6 +9997,8 @@ private fun wireGuardPolicyScript(mode: String, detail: String): String = shellS WDTT_TABLE=100 WDTT_SUBNET="${'$'}(ip -4 route show dev "${'$'}WDTT_IFACE" scope link 2>/dev/null | awk '{print ${'$'}1; exit}')" [ -n "${'$'}WDTT_SUBNET" ] || WDTT_SUBNET=10.66.66.0/24 + while iptables -D FORWARD -i "${'$'}WDTT_IFACE" -o "${'$'}WDTT_WG_IFACE" -s "${'$'}WDTT_SUBNET" -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT 2>/dev/null; do :; done + while iptables -D FORWARD -i "${'$'}WDTT_WG_IFACE" -o "${'$'}WDTT_IFACE" -d "${'$'}WDTT_SUBNET" -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment WDTT_EXIT_FORWARD -j ACCEPT 2>/dev/null; do :; done iptables -t nat -D POSTROUTING -s "${'$'}WDTT_SUBNET" -o "${'$'}WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null || true ip rule del from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TABLE" priority 100 2>/dev/null || true ip route flush table "${'$'}WDTT_TABLE" 2>/dev/null || true @@ -9483,6 +10037,15 @@ private fun wireGuardPolicyScript(mode: String, detail: String): String = shellS exit 3 fi rm -f /tmp/wdtt-wg-exit-start.log + if [ ${shellQuote(mode)} != warp_free ]; then + TEST_SOURCE="${'$'}(wdtt_test_source)" + if ! wdtt_routed_public_ip "${'$'}TEST_SOURCE" "${'$'}WDTT_WG_IFACE" >/dev/null; then + wdtt_clear_wireguard_out + wdtt_write_mode direct "rollback after WireGuard route check error" + echo WDTT_ERROR=wireguard_exit_check_failed + exit 3 + fi + fi echo "WDTT_PROGRESS|0.95|Сохраняю новый режим выхода WDTT..." wdtt_write_mode ${shellQuote(mode)} ${shellQuote(detail)} sleep 1 @@ -9623,6 +10186,7 @@ private fun freeWarpWatchdogInstallScript(): String = """ cat >/usr/local/lib/wdtt/warp-watchdog <<'WDTT_WARP_WATCHDOG' #!/bin/sh set -u + ${outboundProbeFunctions().replace("\n", "\n ")} MODE="${'$'}(sed -n 's/.*"outboundMode"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' /etc/wdtt/outbound.json 2>/dev/null | head -n 1)" [ "${'$'}MODE" = warp_free ] || exit 0 STATE_DIR=/etc/wdtt-plus/warp @@ -9630,7 +10194,7 @@ private fun freeWarpWatchdogInstallScript(): String = """ TEST_SOURCE="${'$'}(ip -4 -o addr show dev wdtt0 scope global 2>/dev/null | awk '{split(${'$'}4, value, "/"); print value[1]; exit}')" check_warp() { [ -n "${'$'}TEST_SOURCE" ] || return 1 - trace="${'$'}(curl -4fsS --interface "${'$'}TEST_SOURCE" --connect-timeout 8 --max-time 20 https://www.cloudflare.com/cdn-cgi/trace 2>/dev/null || true)" + trace="${'$'}(wdtt_routed_https "${'$'}TEST_SOURCE" "wg-wdtt-exit" https://www.cloudflare.com/cdn-cgi/trace || true)" printf '%s\n' "${'$'}trace" | grep -Eq '^warp=(on|plus)${'$'}' } write_state() { @@ -9822,7 +10386,7 @@ private fun freeWarpAutoTuneScript(): String = """ local source="${'$'}1" local trace [ -n "${'$'}source" ] || { WARP_LAST_REASON="wdtt_test_source_missing"; return 1; } - trace="${'$'}(curl -4fsS --interface "${'$'}source" --connect-timeout 6 --max-time 12 https://www.cloudflare.com/cdn-cgi/trace 2>/dev/null || true)" + trace="${'$'}(wdtt_routed_https "${'$'}source" "wg-wdtt-exit" https://www.cloudflare.com/cdn-cgi/trace || true)" WARP_LAST_STATE="${'$'}(wdtt_warp_trace_state "${'$'}trace")" WARP_LAST_HANDSHAKE="${'$'}(wdtt_warp_latest_handshake || true)" case "${'$'}WARP_LAST_STATE" in @@ -9867,7 +10431,7 @@ private fun freeWarpAutoTuneScript(): String = """ if wdtt_warp_check_current "${'$'}source"; then WARP_SELECTED_MTU="${'$'}mtu" WARP_SELECTED_ENDPOINT="${'$'}endpoint" - WARP_LAST_EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}source" --connect-timeout 6 --max-time 12 https://api.ipify.org 2>/dev/null || true)" + WARP_LAST_EXIT_IP="${'$'}(wdtt_routed_public_ip "${'$'}source" "wg-wdtt-exit" || true)" wdtt_warp_save_selected return 0 fi @@ -10081,7 +10645,7 @@ private suspend fun checkFreeWarp( echo WDTT_ERROR=warp_trace_check_failed exit 3 fi - WARP_LAST_EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}TEST_SOURCE" --connect-timeout 8 --max-time 20 https://api.ipify.org 2>/dev/null || true)" + WARP_LAST_EXIT_IP="${'$'}(wdtt_routed_public_ip "${'$'}TEST_SOURCE" "wg-wdtt-exit" || true)" fi WARP_KIND="${'$'}WARP_LAST_STATE" VERSION="${'$'}(cat "${'$'}WARP_DIR/wgcf-version" 2>/dev/null || echo неизвестна)" @@ -10099,7 +10663,7 @@ private suspend fun checkFreeWarp( """ ) val output = ssh.exec(rootCommand(script), timeout = 45000L).trim() - markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(output.take(1200)) } + markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(rootScriptErrorExcerpt(output)) } output } finally { try { session?.disconnect() } catch (_: Exception) {} @@ -10169,7 +10733,7 @@ private suspend fun resetFreeWarpRegistration(target: OutboundSshTarget): String """ ) val output = ssh.exec(rootCommand(script), timeout = 60000L).trim() - markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(output.take(1200)) } + markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(rootScriptErrorExcerpt(output)) } output } finally { try { session?.disconnect() } catch (_: Exception) {} @@ -10245,7 +10809,7 @@ private suspend fun deleteFreeWarp(target: OutboundSshTarget): String = withCont """ ) val output = ssh.exec(rootCommand(script), timeout = 60000L).trim() - markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(output.take(1200)) } + markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(rootScriptErrorExcerpt(output)) } output } finally { try { session?.disconnect() } catch (_: Exception) {} @@ -10437,6 +11001,7 @@ internal fun deleteWireGuardVpsForeignScript(): String = """ fi if command -v iptables >/dev/null 2>&1 && { iptables -S INPUT 2>/dev/null | grep -q WDTT_EXIT_FOREIGN || + iptables -S FORWARD 2>/dev/null | grep -q WDTT_EXIT_FOREIGN || iptables -t nat -S POSTROUTING 2>/dev/null | grep -q WDTT_EXIT_FOREIGN; }; then OWNED=1 fi @@ -10450,6 +11015,8 @@ internal fun deleteWireGuardVpsForeignScript(): String = """ if command -v iptables >/dev/null 2>&1; then iptables -S INPUT 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done + iptables -S FORWARD 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -D /' | + while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done iptables -t nat -S POSTROUTING 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -t nat -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done fi @@ -10470,6 +11037,7 @@ internal fun deleteWireGuardVpsForeignScript(): String = """ [ -e /etc/wdtt-plus/wg-exit/public.key ] && FOREIGN_REMOVE_LEFT=1 if command -v iptables >/dev/null 2>&1 && { iptables -S INPUT 2>/dev/null | grep -q WDTT_EXIT_FOREIGN || + iptables -S FORWARD 2>/dev/null | grep -q WDTT_EXIT_FOREIGN || iptables -t nat -S POSTROUTING 2>/dev/null | grep -q WDTT_EXIT_FOREIGN; }; then FOREIGN_REMOVE_LEFT=1 fi @@ -10501,7 +11069,7 @@ private suspend fun deleteWireGuardExitVps( val currentOutput = SSHClient(currentSession, current.pass) .exec(rootCommand(deleteWireGuardVpsCurrentScript()), timeout = 30000L) markerValue(currentOutput, "WDTT_ERROR")?.let { - throw IllegalStateException(currentOutput.take(1200)) + throw IllegalStateException(rootScriptErrorExcerpt(currentOutput)) } require(markerValue(currentOutput, "WDTT_CURRENT_WG_REMOVED") == "1") { "текущий VPS не подтвердил удаление WireGuard-выхода" @@ -10509,7 +11077,7 @@ private suspend fun deleteWireGuardExitVps( val foreignOutput = SSHClient(foreignSession, foreignCredentials.password) .exec(rootCommand(deleteWireGuardVpsForeignScript()), timeout = 30000L) markerValue(foreignOutput, "WDTT_ERROR")?.let { - throw IllegalStateException(foreignOutput.take(1200)) + throw IllegalStateException(rootScriptErrorExcerpt(foreignOutput)) } require(markerValue(foreignOutput, "WDTT_FOREIGN_WG_REMOVED") == "1") { "дополнительный VPS не подтвердил удаление WireGuard" @@ -10576,7 +11144,7 @@ private suspend fun installWireGuardExitVps( throw IllegalStateException("WDTT_ERROR=wireguard_vps_previous_server_requires_removal") } - val prepareKeys = """ + val prepareKeys = shellScript(outboundShellPrelude(), """ echo "WDTT_PROGRESS|0.26|Готовлю WireGuard-инструменты и ключи..." wdtt_install_wireguard_tools || true command -v wg >/dev/null 2>&1 || { echo WDTT_ERROR=wireguard_tools_required; exit 2; } @@ -10585,7 +11153,7 @@ private suspend fun installWireGuardExitVps( [ -f /etc/wdtt-plus/wg-exit/private.key ] || wg genkey >/etc/wdtt-plus/wg-exit/private.key wg pubkey /etc/wdtt-plus/wg-exit/public.key printf 'WDTT_WG_PUB='; cat /etc/wdtt-plus/wg-exit/public.key; printf '\n' - """.trimIndent() + """) DeployManager.updateProgress(0.28f, "Готовлю WireGuard-ключи на текущем сервере...") val currentPub = markerValue(currentSsh.exec(rootCommand(prepareKeys), timeout = CMD_TIMEOUT), "WDTT_WG_PUB") ?: throw IllegalStateException("текущий сервер не отдал публичный ключ WireGuard") @@ -10618,11 +11186,14 @@ private suspend fun installWireGuardExitVps( systemctl is-active --quiet wg-quick@wg-wdtt-exit 2>/dev/null && touch "${'$'}BACKUP_DIR/was_active" || true systemctl is-enabled --quiet wg-quick@wg-wdtt-exit 2>/dev/null && touch "${'$'}BACKUP_DIR/was_enabled" || true iptables -S INPUT 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' >"${'$'}BACKUP_DIR/input.rules" || true + iptables -S FORWARD 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' >"${'$'}BACKUP_DIR/forward.rules" || true iptables -t nat -S POSTROUTING 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' >"${'$'}BACKUP_DIR/nat.rules" || true chmod 600 "${'$'}BACKUP_DIR"/* systemctl stop wg-quick@wg-wdtt-exit 2>/dev/null || true iptables -S INPUT 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done + iptables -S FORWARD 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -D /' | + while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done iptables -t nat -S POSTROUTING 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -t nat -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done echo "WDTT_PROGRESS|0.56|Включаю пересылку трафика на другом сервере..." @@ -10639,6 +11210,10 @@ private suspend fun installWireGuardExitVps( PrivateKey = ${'$'}PRIV PostUp = iptables -C INPUT -p udp --dport ${'$'}WG_PORT -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${'$'}WG_PORT -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT PostUp = iptables -t nat -C POSTROUTING -s 10.77.77.0/30 -o ${'$'}EXT_IFACE -m comment --comment WDTT_EXIT_FOREIGN -j MASQUERADE 2>/dev/null || iptables -t nat -A POSTROUTING -s 10.77.77.0/30 -o ${'$'}EXT_IFACE -m comment --comment WDTT_EXIT_FOREIGN -j MASQUERADE + PostUp = iptables -I FORWARD -i wg-wdtt-exit -o ${'$'}EXT_IFACE -s 10.77.77.0/30 -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT + PostDown = iptables -D FORWARD -i wg-wdtt-exit -o ${'$'}EXT_IFACE -s 10.77.77.0/30 -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT 2>/dev/null || true + PostUp = iptables -I FORWARD -i ${'$'}EXT_IFACE -o wg-wdtt-exit -d 10.77.77.0/30 -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT + PostDown = iptables -D FORWARD -i ${'$'}EXT_IFACE -o wg-wdtt-exit -d 10.77.77.0/30 -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT 2>/dev/null || true PostDown = iptables -D INPUT -p udp --dport ${'$'}WG_PORT -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT 2>/dev/null || true PostDown = iptables -t nat -D POSTROUTING -s 10.77.77.0/30 -o ${'$'}EXT_IFACE -m comment --comment WDTT_EXIT_FOREIGN -j MASQUERADE 2>/dev/null || true @@ -10655,6 +11230,8 @@ private suspend fun installWireGuardExitVps( systemctl is-active --quiet wg-quick@wg-wdtt-exit || { echo WDTT_ERROR=foreign_wireguard_start_failed; exit 3; } iptables -C INPUT -p udp --dport "${'$'}WG_PORT" -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT 2>/dev/null && + iptables -C FORWARD -i wg-wdtt-exit -o ${'$'}EXT_IFACE -s 10.77.77.0/30 -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT 2>/dev/null && + iptables -C FORWARD -i ${'$'}EXT_IFACE -o wg-wdtt-exit -d 10.77.77.0/30 -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment WDTT_EXIT_FOREIGN -j ACCEPT 2>/dev/null && iptables -t nat -C POSTROUTING -s 10.77.77.0/30 -o "${'$'}EXT_IFACE" -m comment --comment WDTT_EXIT_FOREIGN -j MASQUERADE 2>/dev/null || { echo WDTT_ERROR=foreign_firewall_failed; exit 3; } echo WDTT_FOREIGN_READY=1 @@ -10664,7 +11241,7 @@ private suspend fun installWireGuardExitVps( DeployManager.updateProgress(0.48f, "Настраиваю WireGuard на другом сервере...") foreignTouched = true val foreignOutput = foreignSsh.exec(rootCommand(foreignConfigScript), timeout = CMD_TIMEOUT) - markerValue(foreignOutput, "WDTT_ERROR")?.let { throw IllegalStateException(foreignOutput.trim().take(1200)) } + markerValue(foreignOutput, "WDTT_ERROR")?.let { throw IllegalStateException(rootScriptErrorExcerpt(foreignOutput)) } require(markerValue(foreignOutput, "WDTT_FOREIGN_READY") == "1") { "другой сервер не подтвердил запуск WireGuard" } @@ -10725,7 +11302,7 @@ private suspend fun installWireGuardExitVps( DeployManager.updateProgress(0.72f, "Применяю WireGuard-выход на текущем сервере...") currentTouched = true val output = currentSsh.exec(rootCommand(currentConfigScript), timeout = CMD_TIMEOUT) - if (output.contains("WDTT_ERROR=")) throw IllegalStateException(output.trim().take(400)) + if (output.contains("WDTT_ERROR=") || output.lineSequence().any { it.startsWith("error:") }) throw IllegalStateException(rootScriptErrorExcerpt(output)) currentSsh.exec(rootCommand("rm -rf ${shellQuote("/etc/wdtt-plus/wg-exit/transactions/$transactionId")}"), timeout = 15000L) foreignSsh.exec(rootCommand("rm -rf ${shellQuote("/etc/wdtt-plus/wg-exit/transactions/$transactionId")}"), timeout = 15000L) currentTouched = false @@ -10743,6 +11320,8 @@ private suspend fun installWireGuardExitVps( if command -v iptables >/dev/null 2>&1; then iptables -S INPUT 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done + iptables -S FORWARD 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -D /' | + while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done iptables -t nat -S POSTROUTING 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -t nat -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done fi @@ -10771,9 +11350,17 @@ private suspend fun installWireGuardExitVps( if command -v iptables >/dev/null 2>&1; then iptables -S INPUT 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done + iptables -S FORWARD 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -D /' | + while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done iptables -t nat -S POSTROUTING 2>/dev/null | grep 'WDTT_EXIT_FOREIGN' | sed 's/^-A /iptables -t nat -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done while IFS= read -r rule; do [ -z "${'$'}rule" ] || iptables ${'$'}rule 2>/dev/null || true; done <"${'$'}BACKUP_DIR/input.rules" + while IFS= read -r rule; do + [ -z "${'$'}rule" ] && continue + # Owned ACCEPT rules must precede a pre-existing terminal DROP. + rule="${'$'}(printf '%s\n' "${'$'}rule" | sed 's/^-A /-I /')" + iptables ${'$'}rule 2>/dev/null || exit 3 + done <"${'$'}BACKUP_DIR/forward.rules" while IFS= read -r rule; do [ -z "${'$'}rule" ] || iptables -t nat ${'$'}rule 2>/dev/null || true; done <"${'$'}BACKUP_DIR/nat.rules" fi if [ -f "${'$'}BACKUP_DIR/was_active" ] && @@ -10949,13 +11536,14 @@ private suspend fun checkExistingInstall( verifyRootAccess(ssh) ssh.exec( rootCommand( - "printf 'SERVICE=%s\\n' \"$([ -f /etc/systemd/system/wdtt.service ] && echo 1 || echo 0)\"; " + - "printf 'BINARY=%s\\n' \"$([ -f /usr/local/bin/wdtt-server ] && echo 1 || echo 0)\"; " + - "printf 'CONFIG_DIR=%s\\n' \"$([ -d /etc/wdtt ] && echo 1 || echo 0)\"; " + - "printf 'ACCESS_DB=%s\\n' \"$([ -f /etc/wdtt/passwords.json ] && echo 1 || echo 0)\"; " + - "printf 'WG_KEYS=%s\\n' \"$([ -f /etc/wdtt/wg-keys.dat ] && echo 1 || echo 0)\"; " + + "printf 'SERVICE=%s\\n' \"$([ -e /etc/systemd/system/wdtt.service ] || [ -L /etc/systemd/system/wdtt.service ] || [ -e /lib/systemd/system/wdtt.service ] || [ -e /run/systemd/system/wdtt.service ] && echo 1 || echo 0)\"; " + + "printf 'BINARY=%s\\n' \"$([ -e /usr/local/bin/wdtt-server ] || [ -L /usr/local/bin/wdtt-server ] && echo 1 || echo 0)\"; " + + "printf 'CONFIG_DIR=%s\\n' \"$([ -e /etc/wdtt ] || [ -L /etc/wdtt ] || [ -e /var/lib/wdtt-server-installer ] || [ -L /var/lib/wdtt-server-installer ] || [ -e /sys/class/net/wdtt0 ] && echo 1 || echo 0)\"; " + + "printf 'ACCESS_DB=%s\\n' \"$([ -e /etc/wdtt/passwords.json ] || [ -L /etc/wdtt/passwords.json ] && echo 1 || echo 0)\"; " + + "printf 'WG_KEYS=%s\\n' \"$([ -e /etc/wdtt/wg-keys.dat ] || [ -L /etc/wdtt/wg-keys.dat ] && echo 1 || echo 0)\"; " + "printf 'ACTIVE=%s\\n' \"$(systemctl is-active wdtt 2>/dev/null || true)\"; " + - standaloneInstallerOwnershipProbeScript() + standaloneInstallerOwnershipProbeScript() + "\n" + + serverUpdateRollbackProbeScript() ), timeout = 15000L ) @@ -10963,6 +11551,7 @@ private suspend fun checkExistingInstall( if (output.startsWith("error:", ignoreCase = true) || output.contains("\nerror:", ignoreCase = true)) { throw IllegalStateException(output.trim().take(300)) } + validateExistingInstallProbe(output) fun flag(name: String): Boolean = Regex("^$name=1$", RegexOption.MULTILINE).containsMatchIn(output) ExistingInstallInfo( serviceExists = flag("SERVICE"), @@ -10978,10 +11567,23 @@ private suspend fun checkExistingInstall( incompleteAndroidDeployCandidate = markerValue( output, "WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE" - ) == "1" + ) == "1", + updateRollbackState = parseServerUpdateRollbackState(output), ) } +internal fun validateExistingInstallProbe(output: String) { + val flags = 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") + require(flags.all { name -> + val matches = Regex("^$name=([01])$", RegexOption.MULTILINE).findAll(output).toList() + matches.size == 1 + } && markerValue(output, "ACTIVE") != null && markerValue(output, "WDTT_UPDATE_BACKUP_STATUS") != null) { + "Проверка VPS вернула неполные сведения. Установка не запущена; повторите проверку." + } +} + private fun markerValue(output: String, name: String): String? = Regex("^$name=(.*)$", setOf(RegexOption.MULTILINE)).find(output)?.groupValues?.getOrNull(1)?.trim() @@ -11128,8 +11730,20 @@ private fun deploymentOwnership(ssh: SSHClient): DeploymentOwnership { private fun verifyRootAccess(ssh: SSHClient) { val output = ssh.exec(rootCommand("printf 'WDTT_ROOT_ACCESS=ok\\n'"), timeout = 20_000L) - require(markerValue(output, "WDTT_ROOT_ACCESS") == "ok") { - "SSH-подключение установлено, но root-права не получены. Проверьте пароль sudo и права выбранного пользователя." + validateRootAccessOutput(output) +} + +internal fun validateRootAccessOutput(output: String) { + // A missing marker does not prove a permission denial: the SSH command may + // have timed out or lost its channel before returning a complete answer. + friendlyAdminSudoError(output)?.let { throw IllegalStateException(it) } + val commandErrors = output.lineSequence() + .map(String::trim) + .filter { it.startsWith("error:", ignoreCase = true) } + .joinToString("\n") + check(commandErrors.isBlank()) { commandErrors.take(2000) } + check(markerValue(output, "WDTT_ROOT_ACCESS") == "ok") { + "Сервер не подтвердил проверку прав администратора. Установка не запущена; проверьте соединение и повторите проверку." } } @@ -11213,25 +11827,6 @@ private fun assertAndroidDeployMayManageServer(ssh: SSHClient, operation: String } } -private val remoteMachineMarkerRegex = Regex("^[A-Z][A-Z0-9_]*=.*$") - -internal fun shouldWriteRemoteErrorToUserLog(line: String): Boolean { - val clean = line.trim() - if (clean.isBlank() || remoteMachineMarkerRegex.matches(clean)) return false - return clean.contains("[✗]") || - clean.contains("FAIL") || - (clean.contains("error", true) && !clean.contains("2>/dev/null")) -} - -internal fun remoteErrorMessageForUserLog(line: String): String? { - if (!shouldWriteRemoteErrorToUserLog(line)) return null - val detail = line.trim() - .removePrefix("FAIL:") - .removePrefix("[✗]") - .trim() - return "Ошибка на сервере: ${detail.ifBlank { "операция не выполнена" }}" -} - private fun compactRemoteTail(raw: String): String { val lines = raw.lineSequence() .map { it.trim() } @@ -11240,7 +11835,7 @@ private fun compactRemoteTail(raw: String): String { return lines.takeLast(4).joinToString(" ").take(260) } -private fun friendlyDeployError(error: Throwable, operation: String): String { +internal fun friendlyDeployError(error: Throwable, operation: String): String { val rawFull = listOfNotNull(error.message, error.cause?.message) .joinToString(" ") .ifBlank { error.toString() } @@ -11318,7 +11913,11 @@ private fun friendlyDeployError(error: Throwable, operation: String): String { "external_proxy_route_install_failed" in lower -> "служба внешнего прокси запустилась, но сервер не применил постоянное правило маршрутизации WDTT. Режим отключён и прямой выход сохранён." "external_proxy_apply_failed" in lower -> - withTail("внешний TCP-прокси отвечает напрямую, но путь WDTT через redsocks не заработал. Приложение откатило правила и вернуло прямой выход, чтобы VPN-интернет не пропал.") + externalProxyFailureMessage(rawFull) + "external_proxy_test_not_redirected" in lower -> + "проверочный запрос не прошёл через правило перенаправления redsocks. Внешний прокси отключён, восстановлен прямой выход WDTT." + "external_proxy_test_temp_failed" in lower -> + "не удалось создать временный файл проверки прокси. Внешний выход отключён; проверьте свободное место и права в /tmp на сервере." "external_proxy_test_rule_failed" in lower -> "сервер не разрешил создать временное правило для проверки пути WDTT через внешний прокси. Режим не считается проверенным и был отключён." "external_proxy_remove_failed" in lower -> @@ -11459,7 +12058,11 @@ private fun friendlyDeployError(error: Throwable, operation: String): String { "network is unreachable" in lower || "no route to host" in lower -> "Сервер недоступен из текущей сети. Проверьте интернет, IP и правила межсетевого экрана." - "session is down" in lower -> + "session is down" in lower || "ssh-сессия разорвана" in lower || + "ssh channel closed before exit status" in lower || + "connection reset" in lower || "socket closed" in lower || + "pipe closed" in lower || "broken pipe" in lower || + "channel is not opened" in lower -> "SSH-сессия оборвалась во время операции. Повторите действие после проверки соединения." "no_passwords_json" in lower || "passwords.json" in lower && ("не найден" in lower || "не отдал" in lower) -> @@ -11514,7 +12117,7 @@ private fun String.isValidPortsSpec(): Boolean { return parts.size == 3 && parts.all { it.toIntOrNull()?.let { port -> port in 1..65535 } == true } } -private fun String.isValidPublicHost(): Boolean { +internal fun String.isValidPublicHost(): Boolean { val value = trim() if (value.isBlank() || value.length > 253 || value.any { it == '/' || it == '\\' || it == ':' || it == '@' }) return false val ipv4 = Regex("^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$") @@ -11739,7 +12342,7 @@ internal fun validatePasswordsDbForPreserving( return false } require(replacementMainPassword.isNotBlank()) { - "main_password пустой; укажите главный пароль в «Секретах»" + "main_password пустой; укажите главный пароль в параметрах сервера" } val validatedCopy = JSONObject(db.toString()) .put("main_password", replacementMainPassword) @@ -12428,10 +13031,10 @@ private fun ownerProfileDiffLines(server: ServerAdminProfileInfo, local: ServerA val localComparable = local.comparableOwnerProfile() val lines = mutableListOf() if (serverComparable.vkHashes != localComparable.vkHashes) { - lines += "VK-хеши: сервер — ${secretPresenceLabel(serverComparable.vkHashes)}, приложение — ${secretPresenceLabel(localComparable.vkHashes)}" + lines += "ВК-хеши: сервер — ${secretPresenceLabel(serverComparable.vkHashes)}, приложение — ${secretPresenceLabel(localComparable.vkHashes)}" } if (serverComparable.secondaryVkHash != localComparable.secondaryVkHash) { - lines += "Резервный VK-хеш: сервер — ${secretPresenceLabel(serverComparable.secondaryVkHash)}, приложение — ${secretPresenceLabel(localComparable.secondaryVkHash)}" + lines += "Резервный ВК-хеш: сервер — ${secretPresenceLabel(serverComparable.secondaryVkHash)}, приложение — ${secretPresenceLabel(localComparable.secondaryVkHash)}" } if (serverComparable.profileName.isNotBlank() && serverComparable.profileName != localComparable.profileName) { lines += "Название профиля: сервер — ${serverComparable.profileName.ifBlank { "стандартное" }}, приложение — ${localComparable.profileName.ifBlank { "стандартное" }}" @@ -12474,10 +13077,10 @@ private fun ownerProfileInstallDiffLines( val localComparable = local.comparableOwnerProfile() return buildList { if (localComparable.vkHashes.isNotBlank() && serverComparable.vkHashes != localComparable.vkHashes) { - add("VK-хеши: сервер — ${secretPresenceLabel(serverComparable.vkHashes)}, приложение — ${secretPresenceLabel(localComparable.vkHashes)}") + add("ВК-хеши: сервер — ${secretPresenceLabel(serverComparable.vkHashes)}, приложение — ${secretPresenceLabel(localComparable.vkHashes)}") } if (localComparable.secondaryVkHash.isNotBlank() && serverComparable.secondaryVkHash != localComparable.secondaryVkHash) { - add("Резервный VK-хеш: сервер — ${secretPresenceLabel(serverComparable.secondaryVkHash)}, приложение — ${secretPresenceLabel(localComparable.secondaryVkHash)}") + add("Резервный ВК-хеш: сервер — ${secretPresenceLabel(serverComparable.secondaryVkHash)}, приложение — ${secretPresenceLabel(localComparable.secondaryVkHash)}") } if (localComparable.profileName.isNotBlank() && serverComparable.profileName != localComparable.profileName) { add("Название профиля: сервер — ${serverComparable.profileName.ifBlank { "стандартное" }}, приложение — ${localComparable.profileName}") @@ -12664,10 +13267,10 @@ private suspend fun compareDeployWithServer( overwriteLines += "Главный пароль владельца" } if (request.adminId.isNotBlank() && db.optString("admin_id") != request.adminId) { - overwriteLines += "Telegram Admin ID" + overwriteLines += "Telegram ID администратора: сервер — ${db.optString("admin_id").ifBlank { "не задан" }}, будет — ${request.adminId}" } if (request.botToken.isNotBlank() && db.optString("bot_token") != request.botToken) { - overwriteLines += "Telegram Bot Token" + overwriteLines += "Токен Telegram-бота: будет ${if (db.optString("bot_token").isBlank()) "добавлен" else "заменён"}" } val serverDns = normalizeDnsValues(db.optString("dns")) val localDns = normalizeDnsValues( @@ -12681,8 +13284,13 @@ private suspend fun compareDeployWithServer( } val defaultPorts = db.optString("default_ports").ifBlank { "56000,56001,9000" } + val requestedPorts = Triple(request.dtlsPort, request.wgPort, request.localPort).asPortsSpec() + if (defaultPorts != requestedPorts) { + overwriteLines += "Порты подключения: сервер — $defaultPorts, будет — $requestedPorts" + } val serverProfile = parseOwnerProfileFromDb(db.optJSONObject("admin_profile"), defaultPorts) val ownerInstallDiff = ownerProfileInstallDiffLines(serverProfile, localOwnerProfile) + .filterNot { it.startsWith("Порты ссылки:") || it.startsWith("Локальный порт:") } if (serverProfile.hasSavedFields && ownerInstallDiff.isNotEmpty()) { overwriteLines += ownerProfileOverwriteLines(ownerInstallDiff) } else if (!serverProfile.hasSavedFields && hasMeaningfulAdminProfileFields(localOwnerProfile)) { @@ -13200,6 +13808,74 @@ private suspend fun performServerImportNow( private const val SERVER_UPDATE_BACKUP_DIR = "/var/tmp/wdtt-plus-update-backup" +internal fun serverUpdateRollbackProbeScript( + backupDir: String = SERVER_UPDATE_BACKUP_DIR, +): String = """ + BACKUP=${shellQuote(backupDir)} + wdtt_backup_result() { + printf 'WDTT_UPDATE_BACKUP_STATUS=%s\n' "${'$'}1" + printf 'WDTT_UPDATE_BACKUP_DIAGNOSTIC=%s\n' "${'$'}2" + exit 0 + } + if [ ! -e "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ]; then + wdtt_backup_result none absent + fi + if [ -L "${'$'}BACKUP" ] || [ ! -d "${'$'}BACKUP" ]; then + wdtt_backup_result prepared_corrupted unsafe_backup_path + fi + if [ ! -f "${'$'}BACKUP/state" ] || [ -L "${'$'}BACKUP/state" ]; then + wdtt_backup_result prepared_corrupted missing_or_unsafe_state + fi + backup_state=${'$'}(cat "${'$'}BACKUP/state" 2>/dev/null || true) + if [ "${'$'}backup_state" != prepared ]; then + wdtt_backup_result unknown_state state_not_prepared + fi + for marker in had_config had_binary had_service was_active was_enabled; do + marker_path="${'$'}BACKUP/${'$'}marker" + if [ -e "${'$'}marker_path" ] || [ -L "${'$'}marker_path" ]; then + [ -f "${'$'}marker_path" ] && [ ! -L "${'$'}marker_path" ] || + wdtt_backup_result prepared_corrupted unsafe_marker + fi + done + if [ -f "${'$'}BACKUP/had_config" ]; then + [ -d "${'$'}BACKUP/config" ] && [ ! -L "${'$'}BACKUP/config" ] || + wdtt_backup_result prepared_corrupted missing_config + unsafe=${'$'}(find "${'$'}BACKUP/config" -mindepth 1 \( -type l -o ! \( -type f -o -type d \) \) -print -quit 2>/dev/null || true) + [ -z "${'$'}unsafe" ] || wdtt_backup_result prepared_corrupted unsafe_config_tree + elif [ -e "${'$'}BACKUP/config" ] || [ -L "${'$'}BACKUP/config" ]; then + wdtt_backup_result prepared_corrupted unexpected_config + fi + if [ -f "${'$'}BACKUP/had_binary" ]; then + [ -f "${'$'}BACKUP/wdtt-server" ] && [ ! -L "${'$'}BACKUP/wdtt-server" ] || + wdtt_backup_result prepared_corrupted missing_binary + elif [ -e "${'$'}BACKUP/wdtt-server" ] || [ -L "${'$'}BACKUP/wdtt-server" ]; then + wdtt_backup_result prepared_corrupted unexpected_binary + fi + if [ -f "${'$'}BACKUP/had_service" ]; then + [ -f "${'$'}BACKUP/wdtt.service" ] && [ ! -L "${'$'}BACKUP/wdtt.service" ] || + wdtt_backup_result prepared_corrupted missing_service + elif [ -e "${'$'}BACKUP/wdtt.service" ] || [ -L "${'$'}BACKUP/wdtt.service" ]; then + wdtt_backup_result prepared_corrupted unexpected_service + fi + if { [ -f "${'$'}BACKUP/was_active" ] || [ -f "${'$'}BACKUP/was_enabled" ]; } && + [ ! -f "${'$'}BACKUP/had_service" ]; then + wdtt_backup_result prepared_corrupted service_state_without_service + fi + unknown=${'$'}(find "${'$'}BACKUP" -mindepth 1 -maxdepth 1 \ + ! -name state ! -name had_config ! -name config \ + ! -name had_binary ! -name wdtt-server \ + ! -name had_service ! -name wdtt.service \ + ! -name was_active ! -name was_enabled -print -quit 2>/dev/null || true) + [ -z "${'$'}unknown" ] || wdtt_backup_result prepared_corrupted unknown_backup_entry + printf 'WDTT_UPDATE_BACKUP_STATUS=prepared_valid\n' + printf 'WDTT_UPDATE_BACKUP_DIAGNOSTIC=prepared\n' + printf 'WDTT_UPDATE_BACKUP_HAD_CONFIG=%s\n' "$([ -f "${'$'}BACKUP/had_config" ] && echo 1 || echo 0)" + printf 'WDTT_UPDATE_BACKUP_HAD_BINARY=%s\n' "$([ -f "${'$'}BACKUP/had_binary" ] && echo 1 || echo 0)" + printf 'WDTT_UPDATE_BACKUP_HAD_SERVICE=%s\n' "$([ -f "${'$'}BACKUP/had_service" ] && echo 1 || echo 0)" + printf 'WDTT_UPDATE_BACKUP_WAS_ACTIVE=%s\n' "$([ -f "${'$'}BACKUP/was_active" ] && echo 1 || echo 0)" + printf 'WDTT_UPDATE_BACKUP_WAS_ENABLED=%s\n' "$([ -f "${'$'}BACKUP/was_enabled" ] && echo 1 || echo 0)" +""".trimIndent() + private fun sha256File(file: File): String { val digest = MessageDigest.getInstance("SHA-256") file.inputStream().use { input -> @@ -13264,11 +13940,23 @@ private fun prepareServerUpdateRollback(ssh: SSHClient) { } } +private fun inspectServerUpdateRollback(ssh: SSHClient): ServerUpdateRollbackState { + val output = ssh.exec( + rootCommand(serverUpdateRollbackProbeScript()), + timeout = 15_000L, + ) + return parseServerUpdateRollbackState(output) +} + private fun cleanupServerUpdateRollback(ssh: SSHClient) { + require(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.PreparedValid) { + "страховочная копия изменилась или повреждена; автоматическое удаление запрещено" + } val command = """ set -e BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)} - [ -f "${'$'}BACKUP/state" ] && [ "${'$'}(cat "${'$'}BACKUP/state")" = prepared ] || exit 2 + [ -d "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ] || exit 2 + [ -f "${'$'}BACKUP/state" ] && [ ! -L "${'$'}BACKUP/state" ] && [ "${'$'}(cat "${'$'}BACKUP/state")" = prepared ] || exit 2 printf 'committed\n' > "${'$'}BACKUP/state" rm -rf "${'$'}BACKUP" """.trimIndent() @@ -13276,14 +13964,17 @@ private fun cleanupServerUpdateRollback(ssh: SSHClient) { } private fun rollbackServerUpdate(ssh: SSHClient) { + require(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.PreparedValid) { + "страховочная копия не прошла повторную проверку; восстановление остановлено" + } val command = """ set -e BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)} - [ -d "${'$'}BACKUP" ] || { echo WDTT_ROLLBACK=missing; exit 2; } - [ -f "${'$'}BACKUP/state" ] && [ "${'$'}(cat "${'$'}BACKUP/state")" = prepared ] || { echo WDTT_ROLLBACK=unsafe_state; exit 2; } - [ ! -e "${'$'}BACKUP/had_config" ] || [ -d "${'$'}BACKUP/config" ] || { echo WDTT_ROLLBACK=incomplete_config; exit 2; } - [ ! -e "${'$'}BACKUP/had_binary" ] || [ -f "${'$'}BACKUP/wdtt-server" ] || { echo WDTT_ROLLBACK=incomplete_binary; exit 2; } - [ ! -e "${'$'}BACKUP/had_service" ] || [ -f "${'$'}BACKUP/wdtt.service" ] || { echo WDTT_ROLLBACK=incomplete_service; exit 2; } + [ -d "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ] || { echo WDTT_ROLLBACK=missing; exit 2; } + [ -f "${'$'}BACKUP/state" ] && [ ! -L "${'$'}BACKUP/state" ] && [ "${'$'}(cat "${'$'}BACKUP/state")" = prepared ] || { echo WDTT_ROLLBACK=unsafe_state; exit 2; } + [ ! -e "${'$'}BACKUP/had_config" ] || { [ -d "${'$'}BACKUP/config" ] && [ ! -L "${'$'}BACKUP/config" ]; } || { echo WDTT_ROLLBACK=incomplete_config; exit 2; } + [ ! -e "${'$'}BACKUP/had_binary" ] || { [ -f "${'$'}BACKUP/wdtt-server" ] && [ ! -L "${'$'}BACKUP/wdtt-server" ]; } || { echo WDTT_ROLLBACK=incomplete_binary; exit 2; } + [ ! -e "${'$'}BACKUP/had_service" ] || { [ -f "${'$'}BACKUP/wdtt.service" ] && [ ! -L "${'$'}BACKUP/wdtt.service" ]; } || { echo WDTT_ROLLBACK=incomplete_service; exit 2; } systemctl stop wdtt 2>/dev/null || true if [ -f "${'$'}BACKUP/had_binary" ]; then install -m 755 "${'$'}BACKUP/wdtt-server" /usr/local/bin/wdtt-server; else rm -f /usr/local/bin/wdtt-server; fi if [ -f "${'$'}BACKUP/had_service" ]; then install -m 644 "${'$'}BACKUP/wdtt.service" /etc/systemd/system/wdtt.service; else rm -f /etc/systemd/system/wdtt.service; fi @@ -13291,6 +13982,26 @@ private fun rollbackServerUpdate(ssh: SSHClient) { systemctl daemon-reload if [ -f "${'$'}BACKUP/was_enabled" ]; then systemctl enable wdtt >/dev/null 2>&1; else systemctl disable wdtt >/dev/null 2>&1 || true; fi if [ -f "${'$'}BACKUP/was_active" ]; then systemctl restart wdtt; sleep 2; systemctl is-active --quiet wdtt; fi + if [ -f "${'$'}BACKUP/had_binary" ]; then + [ -f /usr/local/bin/wdtt-server ] && [ ! -L /usr/local/bin/wdtt-server ] && [ -x /usr/local/bin/wdtt-server ] || { echo WDTT_ROLLBACK=verify_binary; exit 3; } + else + [ ! -e /usr/local/bin/wdtt-server ] && [ ! -L /usr/local/bin/wdtt-server ] || { echo WDTT_ROLLBACK=verify_binary_absent; exit 3; } + fi + if [ -f "${'$'}BACKUP/had_service" ]; then + [ -f /etc/systemd/system/wdtt.service ] && [ ! -L /etc/systemd/system/wdtt.service ] || { echo WDTT_ROLLBACK=verify_service; exit 3; } + else + [ ! -e /etc/systemd/system/wdtt.service ] && [ ! -L /etc/systemd/system/wdtt.service ] || { echo WDTT_ROLLBACK=verify_service_absent; exit 3; } + fi + if [ -f "${'$'}BACKUP/had_config" ]; then + [ -d /etc/wdtt ] && [ ! -L /etc/wdtt ] || { echo WDTT_ROLLBACK=verify_config; exit 3; } + else + [ ! -e /etc/wdtt ] && [ ! -L /etc/wdtt ] || { echo WDTT_ROLLBACK=verify_config_absent; exit 3; } + fi + if [ -f "${'$'}BACKUP/was_active" ]; then + systemctl is-active --quiet wdtt || { echo WDTT_ROLLBACK=verify_active; exit 3; } + else + ! systemctl is-active --quiet wdtt || { echo WDTT_ROLLBACK=verify_inactive; exit 3; } + fi rm -rf "${'$'}BACKUP" echo WDTT_ROLLBACK=ok """.trimIndent() @@ -13300,6 +14011,85 @@ private fun rollbackServerUpdate(ssh: SSHClient) { } } +private fun cleanupAbandonedServerUpdateRollback(ssh: SSHClient) { + require(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.PreparedValid) { + "страховочная копия не прошла повторную проверку; удаление запрещено" + } + val output = ssh.exec( + rootCommand( + """ + set -e + BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)} + [ -d "${'$'}BACKUP" ] && [ ! -L "${'$'}BACKUP" ] || { echo WDTT_BACKUP_CLEANUP=unsafe_backup; exit 2; } + [ -f /usr/local/bin/wdtt-server ] && [ ! -L /usr/local/bin/wdtt-server ] && [ -x /usr/local/bin/wdtt-server ] || { echo WDTT_BACKUP_CLEANUP=missing_binary; exit 3; } + [ -f /etc/systemd/system/wdtt.service ] && [ ! -L /etc/systemd/system/wdtt.service ] || { echo WDTT_BACKUP_CLEANUP=missing_service; exit 3; } + [ -f /etc/wdtt/passwords.json ] && [ ! -L /etc/wdtt/passwords.json ] && [ -s /etc/wdtt/passwords.json ] || { echo WDTT_BACKUP_CLEANUP=missing_config; exit 3; } + systemctl is-active --quiet wdtt || { echo WDTT_BACKUP_CLEANUP=service_inactive; exit 3; } + rm -rf "${'$'}BACKUP" + echo WDTT_BACKUP_CLEANUP=ok + """.trimIndent(), + ), + timeout = 30_000L, + ) + require(markerValue(output, "WDTT_BACKUP_CLEANUP") == "ok") { + "текущее состояние WDTT не прошло проверку; страховочная копия сохранена" + } +} + +internal enum class ServerUpdateRollbackAction { + RestorePrevious, + KeepCurrentAndDeleteBackup, +} + +private suspend fun resolveServerUpdateRollback( + request: DeployRequest, + action: ServerUpdateRollbackAction, +): String = withContext(Dispatchers.IO) { + val actionName = when (action) { + ServerUpdateRollbackAction.RestorePrevious -> "restore_previous" + ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup -> "keep_current_delete_backup" + } + DeployManager.writeError("Server update rollback action selected: $actionName") + var session: Session? = null + try { + session = createCriticalSshSession( + request.host, + request.user, + SshCredentials( + password = request.pass, + privateKey = request.privateKey, + privateKeyPassphrase = request.keyPassphrase, + allowPasswordAuthentication = request.allowPasswordAuthentication, + ), + request.sshPort, + ) + val ssh = SSHClient(session, request.pass) + verifyRootAccess(ssh) + when (action) { + ServerUpdateRollbackAction.RestorePrevious -> rollbackServerUpdate(ssh) + ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup -> + cleanupAbandonedServerUpdateRollback(ssh) + } + check(inspectServerUpdateRollback(ssh) is ServerUpdateRollbackState.None) { + "операция завершилась, но каталог страховочной копии всё ещё найден" + } + DeployManager.writeError("Server update rollback action result: $actionName=success") + when (action) { + ServerUpdateRollbackAction.RestorePrevious -> + "Прежнее состояние WDTT Plus восстановлено и проверено. Страховочная копия удалена." + ServerUpdateRollbackAction.KeepCurrentAndDeleteBackup -> + "Текущее состояние WDTT Plus проверено. Удалена только страховочная копия." + } + } catch (error: Exception) { + DeployManager.writeError( + "Server update rollback action result: $actionName=failed; ${error.message}", + ) + throw error + } finally { + try { session?.disconnect() } catch (_: Exception) {} + } +} + private data class PreservedTrafficCounter( val downBytes: Long, val upBytes: Long @@ -14178,7 +14968,7 @@ private fun ServerBackupExportPasswordDialog( else -> null } - AlertDialog( + BoundedAlertDialog( onDismissRequest = { if (!busy) onDismiss() }, title = { DialogTitleWithClose( @@ -14259,7 +15049,7 @@ private fun ServerBackupImportPasswordDialog( var busy by remember { mutableStateOf(false) } var error by remember { mutableStateOf(null) } - AlertDialog( + BoundedAlertDialog( onDismissRequest = { if (!busy) onDismiss() }, title = { DialogTitleWithClose( @@ -14565,7 +15355,7 @@ private fun ServerImportConfirmDialog( else -> "не трогать WG-ключи текущего сервера" } - androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) { + BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = onDismiss) { BoxWithConstraints( modifier = Modifier.fillMaxSize().padding(8.dp), contentAlignment = Alignment.Center @@ -14699,7 +15489,7 @@ private fun SshAuthenticationHelpDialog( ) { val television = isTelevisionDevice() val scrollState = rememberScrollState() - androidx.compose.ui.window.Dialog( + BoundedAppDialog( onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = !television), ) { @@ -14757,7 +15547,7 @@ private fun SshAuthenticationHelpDialog( ) if (!additionalServer) { Text( - "«Пароль туннеля» требуется отдельно: SSH открывает доступ к системе, а пароль туннеля подтверждает владельца WDTT.", + "Главный пароль администратора требуется отдельно: SSH открывает доступ к системе, а главный пароль подтверждает владельца WDTT.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) @@ -14809,7 +15599,7 @@ private fun SshPrivateKeyDialog( } } - androidx.compose.ui.window.Dialog(onDismissRequest = { if (!checking) onDismiss() }) { + BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = { if (!checking) onDismiss() }) { Surface( modifier = Modifier .fillMaxWidth() @@ -15024,29 +15814,27 @@ private suspend fun readSshPrivateKeyFromUri(context: Context, uri: Uri): String @Composable fun DeploySecretsDialog( settingsStore: SettingsStore, + profileIndex: Int, initialMainPass: String, initialAdminId: String, initialBotToken: String, - initialSshPort: String, initialDns1: String, initialDns2: String, initialManualPortsEnabled: Boolean, initialServerDtlsPort: String, initialServerWgPort: String, - deployIp: String, - deployLogin: String, - deployPassword: String, onSaved: (String, String) -> Unit, - onDismiss: () -> Unit + onDismiss: () -> Unit, + connectionOnly: Boolean = false, ) { val scope = rememberCoroutineScope() + var savingParameters by remember { mutableStateOf(false) } var passInput by rememberSaveable { mutableStateOf(initialMainPass) } var adminIdInput by rememberSaveable { mutableStateOf(initialAdminId) } var botTokenInput by rememberSaveable { mutableStateOf(initialBotToken) } var showTelegramBotHelp by rememberSaveable { mutableStateOf(false) } var passInputFocused by remember { mutableStateOf(false) } var botTokenFocused by remember { mutableStateOf(false) } - var sshPortInput by rememberSaveable { mutableStateOf(if (initialSshPort.isBlank()) "22" else initialSshPort) } var dns1Input by rememberSaveable { mutableStateOf(initialDns1.ifBlank { "1.1.1.1" }) } var dns2Input by rememberSaveable { mutableStateOf(initialDns2.ifBlank { "1.0.0.1" }) } var manualDnsInput by rememberSaveable { @@ -15055,7 +15843,6 @@ fun DeploySecretsDialog( initialDns2.isNotBlank() && initialDns2 != "1.0.0.1" ) } - var manualSshInput by rememberSaveable { mutableStateOf(initialSshPort.isNotBlank() && initialSshPort != "22") } var manualPortsInput by rememberSaveable { mutableStateOf( initialManualPortsEnabled && @@ -15070,7 +15857,7 @@ fun DeploySecretsDialog( return value.toIntOrNull()?.takeIf { it in 1..65535 }?.toString() ?: fallback } - androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) { + BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = onDismiss) { BoxWithConstraints( modifier = Modifier.fillMaxSize().padding(8.dp), contentAlignment = Alignment.Center @@ -15088,7 +15875,7 @@ fun DeploySecretsDialog( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { - Text("Секреты Деплоя", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + Text(if (connectionOnly) "Пароль администратора" else "Параметры установки", modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) IconButton( onClick = onDismiss, modifier = Modifier.remoteIconButtonFocus(), @@ -15099,8 +15886,11 @@ fun DeploySecretsDialog( Spacer(Modifier.height(16.dp)) + val portsInputValid = connectionOnly || !manualPortsInput || + ((dtlsPortInput.toIntOrNull() ?: 0) in 1..65535 && (wgPortInput.toIntOrNull() ?: 0) in 1..65535 && + dtlsPortInput.toIntOrNull() != wgPortInput.toIntOrNull()) val isPasswordValid = passInput.isNotEmpty() && passInput.matches(Regex("^[a-zA-Z0-9_.!?:#/-]+$")) - val dnsInputIssue = if (manualDnsInput) { + val dnsInputIssue = if (!connectionOnly && manualDnsInput) { runCatching { normalizedDeployDns(dns1Input, dns2Input) } .exceptionOrNull()?.message } else { @@ -15110,8 +15900,8 @@ fun DeploySecretsDialog( OutlinedTextField( value = passInput, onValueChange = { passInput = it.filter { c -> !c.isWhitespace() } }, - label = { Text("Задайте пароль туннеля (любой)") }, - placeholder = { Text("Придумайте надежный пароль") }, + label = { Text("Главный пароль администратора") }, + placeholder = { Text(if (connectionOnly) "Пароль работающего сервера" else "Придумайте надёжный пароль") }, singleLine = true, visualTransformation = if (passInputFocused) VisualTransformation.None else PasswordVisualTransformation(), modifier = Modifier @@ -15124,7 +15914,8 @@ fun DeploySecretsDialog( if (passInput.isNotEmpty() && !isPasswordValid) { "Разрешены только буквы, цифры и симв: _ . ! ? : # - /" } else { - "Это первый пароль для подключения к VPN, обычно пароль администратора сервера." + if (connectionOnly) "Введите главный пароль работающего WDTT-сервера. Это отдельный пароль, а не пароль SSH." + else "Для новой установки задайте пароль администратора; для обновления используйте текущий пароль сервера." }, style = MaterialTheme.typography.bodySmall, color = if (passInput.isNotEmpty() && !isPasswordValid) { @@ -15135,244 +15926,207 @@ fun DeploySecretsDialog( modifier = Modifier.padding(top = 4.dp) ) - Spacer(Modifier.height(16.dp)) - HorizontalDivider() - Spacer(Modifier.height(8.dp)) - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp) - ) { - Text( - "Telegram-бот для управления", - color = MaterialTheme.colorScheme.primary, - fontWeight = FontWeight.SemiBold, - style = MaterialTheme.typography.titleSmall, - modifier = Modifier.weight(1f) - ) - IconButton( - onClick = { showTelegramBotHelp = true }, - modifier = Modifier.size(36.dp).remoteHelpFocus() - ) { - Icon( - Icons.AutoMirrored.Filled.HelpOutline, - contentDescription = "Как создать и подключить Telegram-бота", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(20.dp) - ) - } - } - Text( - "Можно оставить пустым, если бот не нужен. При подключении без установки приложение проверяет SSH-доступ и главный пароль, а Telegram-поля читает с сервера и подставляет автоматически.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Spacer(Modifier.height(8.dp)) - - OutlinedTextField( - value = adminIdInput, - onValueChange = { adminIdInput = it }, - label = { Text("ID Админа (опционально)") }, - placeholder = { Text("ID из @userinfobot") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( - keyboardType = androidx.compose.ui.text.input.KeyboardType.Number - ) - ) - - Spacer(Modifier.height(8.dp)) - - OutlinedTextField( - value = botTokenInput, - onValueChange = { botTokenInput = it }, - label = { Text("Токен Бота (опционально)") }, - placeholder = { Text("Токен от BotFather") }, - singleLine = true, - visualTransformation = if (botTokenFocused) VisualTransformation.None else PasswordVisualTransformation(), - modifier = Modifier - .fillMaxWidth() - .onFocusChanged { botTokenFocused = it.isFocused }, - shape = RoundedCornerShape(16.dp) - ) - - Spacer(Modifier.height(16.dp)) - HorizontalDivider() - Spacer(Modifier.height(8.dp)) - Row( - modifier = Modifier - .fillMaxWidth() - .remoteToggleableRow(value = manualDnsInput) { manualDnsInput = it } - .padding(horizontal = 8.dp, vertical = 6.dp), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column(modifier = Modifier.weight(1f)) { - Text("DNS сервера", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold) - Text( - "Оставьте выключенным, если подходят стандартные DNS 1.1.1.1 и 1.0.0.1.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - Switch( - checked = manualDnsInput, - onCheckedChange = null, - ) - } - - if (manualDnsInput) { + if (!connectionOnly) { + Spacer(Modifier.height(16.dp)) + HorizontalDivider() Spacer(Modifier.height(8.dp)) Row( modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(12.dp) + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) ) { + Text( + "Telegram-бот для управления", + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.SemiBold, + style = MaterialTheme.typography.titleSmall, + modifier = Modifier.weight(1f, fill = false) + ) + HintIconButton(hint = "Как создать и подключить Telegram-бота", + onClick = { showTelegramBotHelp = true }, + modifier = Modifier.size(36.dp).remoteHelpFocus() + ) { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Как создать и подключить Telegram-бота", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + } + } + Text( + "Можно оставить пустым, если бот не нужен. При подключении без установки приложение проверяет SSH-доступ и главный пароль, а Telegram-поля читает с сервера и подставляет автоматически.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(8.dp)) + + OutlinedTextField( + value = adminIdInput, + onValueChange = { adminIdInput = it }, + label = { Text("ID Админа (опционально)") }, + placeholder = { Text("ID из @userinfobot") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( + keyboardType = androidx.compose.ui.text.input.KeyboardType.Number + ) + ) + + Spacer(Modifier.height(8.dp)) + + OutlinedTextField( + value = botTokenInput, + onValueChange = { botTokenInput = it }, + label = { Text("Токен Бота (опционально)") }, + placeholder = { Text("Токен от BotFather") }, + singleLine = true, + visualTransformation = if (botTokenFocused) VisualTransformation.None else PasswordVisualTransformation(), + modifier = Modifier + .fillMaxWidth() + .onFocusChanged { botTokenFocused = it.isFocused }, + shape = RoundedCornerShape(16.dp) + ) + + Spacer(Modifier.height(16.dp)) + HorizontalDivider() + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier + .fillMaxWidth() + .remoteToggleableRow(value = manualDnsInput) { manualDnsInput = it } + .padding(horizontal = 8.dp, vertical = 6.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text("DNS сервера", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold) + Text( + "Оставьте выключенным, если подходят стандартные DNS 1.1.1.1 и 1.0.0.1.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = manualDnsInput, + onCheckedChange = null, + ) + } + + if (manualDnsInput) { + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + OutlinedTextField( + value = dns1Input, + onValueChange = { dns1Input = it.filter { c -> !c.isWhitespace() } }, + label = { Text("Основной DNS") }, + placeholder = { Text("1.1.1.1") }, + singleLine = true, + modifier = Modifier.weight(1f), + shape = RoundedCornerShape(16.dp) + ) + OutlinedTextField( + value = dns2Input, + onValueChange = { dns2Input = it.filter { c -> !c.isWhitespace() } }, + label = { Text("Резервный DNS") }, + placeholder = { Text("1.0.0.1") }, + singleLine = true, + modifier = Modifier.weight(1f), + shape = RoundedCornerShape(16.dp) + ) + } + if (dnsInputIssue != null) { + Text( + text = dnsInputIssue, + modifier = Modifier.padding(top = 4.dp), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } + } + + Spacer(Modifier.height(16.dp)) + HorizontalDivider() + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier + .fillMaxWidth() + .remoteToggleableRow(value = manualPortsInput) { manualPortsInput = it } + .padding(horizontal = 8.dp, vertical = 6.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text("Порты сервера", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold) + Text( + "Оставьте выключенным, если подходят стандартные порты: DTLS 56000 и WireGuard 56001.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = manualPortsInput, + onCheckedChange = null, + ) + } + + if (manualPortsInput) { + if (!portsInputValid) Text("Укажите два разных порта от 1 до 65535.", color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) OutlinedTextField( - value = dns1Input, - onValueChange = { dns1Input = it.filter { c -> !c.isWhitespace() } }, - label = { Text("Основной DNS") }, - placeholder = { Text("1.1.1.1") }, + value = dtlsPortInput, + onValueChange = { dtlsPortInput = it.filter(Char::isDigit).take(5) }, + label = { Text("Порт DTLS сервера") }, + placeholder = { Text("56000") }, singleLine = true, - modifier = Modifier.weight(1f), - shape = RoundedCornerShape(16.dp) + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( + keyboardType = androidx.compose.ui.text.input.KeyboardType.Number + ) ) + Spacer(Modifier.height(8.dp)) OutlinedTextField( - value = dns2Input, - onValueChange = { dns2Input = it.filter { c -> !c.isWhitespace() } }, - label = { Text("Резервный DNS") }, - placeholder = { Text("1.0.0.1") }, + value = wgPortInput, + onValueChange = { wgPortInput = it.filter(Char::isDigit).take(5) }, + label = { Text("Порт WireGuard сервера") }, + placeholder = { Text("56001") }, singleLine = true, - modifier = Modifier.weight(1f), - shape = RoundedCornerShape(16.dp) + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( + keyboardType = androidx.compose.ui.text.input.KeyboardType.Number + ) ) } - if (dnsInputIssue != null) { - Text( - text = dnsInputIssue, - modifier = Modifier.padding(top = 4.dp), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - } - Spacer(Modifier.height(16.dp)) - HorizontalDivider() - Spacer(Modifier.height(8.dp)) - Row( - modifier = Modifier - .fillMaxWidth() - .remoteToggleableRow(value = manualSshInput) { manualSshInput = it } - .padding(horizontal = 8.dp, vertical = 6.dp), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column(modifier = Modifier.weight(1f)) { - Text("SSH-порт", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold) - Text( - "Оставьте выключенным, если SSH работает на стандартном порту 22.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - Switch( - checked = manualSshInput, - onCheckedChange = null, - ) - } - - if (manualSshInput) { - Spacer(Modifier.height(8.dp)) - OutlinedTextField( - value = sshPortInput, - onValueChange = { sshPortInput = it.filter(Char::isDigit).take(5) }, - label = { Text("Порт для деплоя SSH") }, - placeholder = { Text("22") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( - keyboardType = androidx.compose.ui.text.input.KeyboardType.Number - ) - ) - } - - Spacer(Modifier.height(16.dp)) - HorizontalDivider() - Spacer(Modifier.height(8.dp)) - Row( - modifier = Modifier - .fillMaxWidth() - .remoteToggleableRow(value = manualPortsInput) { manualPortsInput = it } - .padding(horizontal = 8.dp, vertical = 6.dp), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column(modifier = Modifier.weight(1f)) { - Text("Порты сервера", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold) - Text( - "Оставьте выключенным, если подходят стандартные порты: DTLS 56000 и WireGuard 56001.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - Switch( - checked = manualPortsInput, - onCheckedChange = null, - ) - } - - if (manualPortsInput) { - Spacer(Modifier.height(8.dp)) - OutlinedTextField( - value = dtlsPortInput, - onValueChange = { dtlsPortInput = it.filter(Char::isDigit).take(5) }, - label = { Text("Порт DTLS сервера") }, - placeholder = { Text("56000") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( - keyboardType = androidx.compose.ui.text.input.KeyboardType.Number - ) - ) - Spacer(Modifier.height(8.dp)) - OutlinedTextField( - value = wgPortInput, - onValueChange = { wgPortInput = it.filter(Char::isDigit).take(5) }, - label = { Text("Порт WireGuard сервера") }, - placeholder = { Text("56001") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( - keyboardType = androidx.compose.ui.text.input.KeyboardType.Number - ) - ) } Spacer(Modifier.height(24.dp)) Button( onClick = { - val finalPort = if (manualSshInput) normalizePort(sshPortInput, "22") else "22" val finalDtls = if (manualPortsInput) normalizePort(dtlsPortInput, "56000") else "56000" val finalWg = if (manualPortsInput) normalizePort(wgPortInput, "56001") else "56001" val finalDns1 = if (manualDnsInput) dns1Input.trim().ifBlank { "1.1.1.1" } else "1.1.1.1" val finalDns2 = if (manualDnsInput) dns2Input.trim().ifBlank { "1.0.0.1" } else "1.0.0.1" - val effectiveManualPorts = manualPortsInput && (finalDtls != "56000" || finalWg != "56001") + savingParameters = true scope.launch { - settingsStore.saveDeploySecrets(passInput, adminIdInput, botTokenInput, finalPort) - settingsStore.saveDeploy(deployIp, deployLogin, deployPassword, finalPort, finalDns1, finalDns2) - settingsStore.saveManualPortsEnabled(effectiveManualPorts) - settingsStore.savePorts(finalDtls.toInt(), finalWg.toInt(), settingsStore.listenPort.first()) - onSaved(finalDtls, finalWg) + settingsStore.saveServerParameters(profileIndex, passInput, adminIdInput, botTokenInput, + dns1 = finalDns1.takeUnless { connectionOnly }, dns2 = finalDns2.takeUnless { connectionOnly }, + dtlsPort = finalDtls.toInt().takeUnless { connectionOnly }, + wgPort = finalWg.toInt().takeUnless { connectionOnly }) + if (!connectionOnly) onSaved(finalDtls, finalWg) onDismiss() } }, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), shape = RoundedCornerShape(16.dp), - enabled = isPasswordValid && dnsInputIssue == null, + enabled = isPasswordValid && dnsInputIssue == null && portsInputValid && !savingParameters, colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary) ) { Text("Сохранить", fontWeight = FontWeight.SemiBold) } Spacer(Modifier.height(4.dp)) @@ -15389,7 +16143,6 @@ fun DeploySecretsDialog( @Composable private fun TelegramBotHelpDialog(onDismiss: () -> Unit) { val context = LocalContext.current - val television = isTelevisionDevice() fun openTelegramBot(username: String, miniApp: Boolean = false) { val tgUri = if (miniApp) { @@ -15422,94 +16175,43 @@ private fun TelegramBotHelpDialog(onDismiss: () -> Unit) { Toast.makeText(context, "$handle скопирован", Toast.LENGTH_SHORT).show() } - androidx.compose.ui.window.Dialog( - onDismissRequest = onDismiss, - properties = DialogProperties(usePlatformDefaultWidth = !television), + SettingsDialogLayout( + title = "Подключение Telegram-бота", + onDismiss = onDismiss, ) { - BoxWithConstraints( - modifier = Modifier.fillMaxSize().padding(8.dp), - contentAlignment = Alignment.Center - ) { - Surface( - modifier = Modifier - .televisionDialogWidth(television) - .heightIn(max = maxHeight * 0.92f), - shape = RoundedCornerShape(24.dp), - color = MaterialTheme.colorScheme.surface, - contentColor = MaterialTheme.colorScheme.onSurface, - tonalElevation = 8.dp - ) { - Column( - modifier = Modifier - .padding(22.dp) - .fillMaxWidth() - .verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(12.dp) - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - "Подключение Telegram-бота", - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary, - modifier = Modifier.weight(1f) - ) - IconButton( - onClick = onDismiss, - modifier = Modifier.remoteIconButtonFocus(), - ) { - Icon(Icons.Default.Close, contentDescription = "Закрыть") - } - } + Text( + "1. Откройте мини-приложение BotFather и создайте бота без ручной отправки команд. Если мини-приложение недоступно в вашей версии Telegram, откройте обычный чат @BotFather, нажмите «Запустить» и отправьте /newbot. Задайте имя и username, который заканчивается на bot, затем скопируйте выданный токен.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + TelegramBotFatherRows( + onOpenMiniApp = { openTelegramBot("BotFather", miniApp = true) }, + onOpenChat = { openTelegramBot("BotFather") }, + onCopy = { copyTelegramHandle("@BotFather") } + ) - Text( - "1. Откройте мини-приложение BotFather и создайте бота без ручной отправки команд. Если мини-приложение недоступно в вашей версии Telegram, откройте обычный чат @BotFather, нажмите «Запустить» и отправьте /newbot. Задайте имя и username, который заканчивается на bot, затем скопируйте выданный токен.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - TelegramBotFatherRows( - onOpenMiniApp = { openTelegramBot("BotFather", miniApp = true) }, - onOpenChat = { openTelegramBot("BotFather") }, - onCopy = { copyTelegramHandle("@BotFather") } - ) + Text( + "2. Откройте @userinfobot, нажмите «Запустить» и скопируйте свой числовой Telegram ID.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + TelegramBotActionRow( + buttonText = "Открыть @userinfobot", + handle = "@userinfobot", + onOpen = { openTelegramBot("userinfobot") }, + onCopy = { copyTelegramHandle("@userinfobot") } + ) - Text( - "2. Откройте @userinfobot, нажмите «Запустить» и скопируйте свой числовой Telegram ID.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - TelegramBotActionRow( - buttonText = "Открыть @userinfobot", - handle = "@userinfobot", - onOpen = { openTelegramBot("userinfobot") }, - onCopy = { copyTelegramHandle("@userinfobot") } - ) - - Text( - "3. Вставьте ID в поле администратора, токен — в поле бота и нажмите «Сохранить». Чтобы передать эти данные серверу, выполните установку во вкладке «Деплой» — при обновлении сервера можно выбрать установку с сохранением данных.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - "Токен даёт доступ к управлению ботом. Не отправляйте его другим людям и не публикуйте; при утечке перевыпустите токен через @BotFather.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - - Button( - onClick = onDismiss, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp) - ) { - Text("Понятно", fontWeight = FontWeight.Bold) - } - } - } - } + Text( + "3. В «Деплой» выберите «Установить» и откройте «Параметры». Вставьте ID в поле администратора, токен — в поле бота и нажмите «Сохранить». Чтобы передать эти данные серверу, выполните установку во вкладке «Деплой» — при обновлении сервера можно выбрать установку с сохранением данных.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + "Токен даёт доступ к управлению ботом. Не отправляйте его другим людям и не публикуйте; при утечке перевыпустите токен через @BotFather.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) } } @@ -15547,7 +16249,7 @@ private fun TelegramBotFatherRows( Text("Обычный чат @BotFather", textAlign = TextAlign.Center) } } - FilledTonalIconButton( + HintFilledTonalIconButton(hint = "Скопировать @BotFather", onClick = onCopy, modifier = Modifier.size(48.dp) ) { @@ -15581,7 +16283,7 @@ private fun TelegramBotActionRow( ) { Text(buttonText, textAlign = TextAlign.Center) } - FilledTonalIconButton( + HintFilledTonalIconButton(hint = "Скопировать $handle", onClick = onCopy, modifier = Modifier.size(48.dp) ) { @@ -15601,7 +16303,7 @@ private fun ServerBackupDeleteConfirmDialog( onDismiss: () -> Unit, onConfirm: () -> Unit ) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = onDismiss, title = { DialogTitleWithClose( @@ -16196,6 +16898,127 @@ private fun SelectedBackupApplyCard( } } +@Composable +private fun ServerUpdateRollbackDialog( + state: ServerUpdateRollbackState, + busy: Boolean, + statusMessage: String, + onDismiss: () -> Unit, + onRestore: () -> Unit, + onKeepCurrent: () -> Unit, +) { + val television = isTelevisionDevice() + val scrollState = rememberScrollState() + BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = { if (!busy) onDismiss() }) { + BoxWithConstraints( + modifier = Modifier.fillMaxSize().padding(8.dp), + contentAlignment = Alignment.Center, + ) { + Surface( + modifier = Modifier.heightIn(max = maxHeight * 0.92f), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 8.dp, + ) { + Column( + modifier = Modifier + .padding(24.dp) + .fillMaxWidth() + .verticalScroll(scrollState) + .tvDpadScrollable(scrollState, television), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + DialogTitleWithClose( + title = "Незавершённое обновление", + onDismiss = onDismiss, + enabled = !busy, + color = MaterialTheme.colorScheme.error, + ) + Text( + "Обнаружено незавершённое обновление WDTT Plus. На сервере сохранена страховочная копия предыдущего состояния.", + style = MaterialTheme.typography.bodyMedium, + ) + when (state) { + is ServerUpdateRollbackState.PreparedValid -> { + Surface( + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.45f), + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.primary.copy(alpha = 0.25f), + ), + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(12.dp), + verticalArrangement = Arrangement.spacedBy(5.dp), + ) { + Text("Копия проверена и готова к восстановлению.", fontWeight = FontWeight.SemiBold) + InstallTraceLine("Конфигурация", state.markers.hadConfig) + InstallTraceLine("Бинарник", state.markers.hadBinary) + InstallTraceLine("Служба systemd", state.markers.hadService) + InstallTraceLine("Служба была активна", state.markers.wasActive) + } + } + Button( + onClick = onRestore, + enabled = !busy, + modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp), + shape = RoundedCornerShape(16.dp), + ) { + Text("Восстановить прежнее состояние", fontWeight = FontWeight.Bold) + } + Text( + "Если текущая установка уже полностью работает, можно удалить только эту копию. " + + "Приложение сначала проверит бинарник, конфигурацию, unit и активную службу; рабочая установка не удаляется.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + DangerousServerHoldButton( + actionLabel = "Текущее состояние работает — удалить копию", + enabled = !busy, + guardKey = "server-update-backup-cleanup", + buttonWidthFraction = 1f, + actionLabelMaxLines = 2, + onConfirmed = onKeepCurrent, + modifier = Modifier.fillMaxWidth(), + ) + } + is ServerUpdateRollbackState.PreparedCorrupted -> { + Text( + "Страховочная копия повреждена: ${state.diagnostic}. Автоматическое восстановление, удаление и обычный деплой заблокированы. Нужна ручная проверка сервера по SSH.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + is ServerUpdateRollbackState.UnknownState -> { + Text( + "Состояние страховочной копии не распознано: ${state.diagnostic}. Ничего не удалено; обычный деплой заблокирован до ручной проверки по SSH.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + ServerUpdateRollbackState.None -> Unit + } + if (busy) { + LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + } + if (statusMessage.isNotBlank()) { + Text( + statusMessage, + style = MaterialTheme.typography.bodySmall, + color = if (busy) { + MaterialTheme.colorScheme.onSurfaceVariant + } else { + MaterialTheme.colorScheme.error + }, + ) + } + } + } + } + } +} + @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ExistingInstallDialog( @@ -16218,16 +17041,16 @@ private fun ExistingInstallDialog( ) val preservingUpdateAllowed = existingInstallAllowsPreservingUpdate( ownership = ownership, - checkSucceeded = checkError == null + checkSucceeded = checkError == null && info.comparison?.checkError == null ) val resetAllowed = existingInstallAllowsReset( ownership = ownership, - checkSucceeded = checkError == null + checkSucceeded = checkError == null && info.comparison?.checkError == null ) LaunchedEffect(resetAllowed) { if (!resetAllowed) showResetConfirmation = false } - androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) { + BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = onDismiss) { BoxWithConstraints( modifier = Modifier.fillMaxSize().padding(8.dp), contentAlignment = Alignment.Center @@ -16349,7 +17172,7 @@ private fun ExistingInstallDialog( border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.35f)) ) { Text( - "Не удалось сравнить сохранённые поля сервера с приложением. При продолжении они могут быть заменены локальными значениями: ${comparison.checkError.take(180)}", + "Не удалось сравнить сохранённые поля сервера с приложением. Повторите проверку перед обновлением: ${comparison.checkError.take(180)}", modifier = Modifier.fillMaxWidth().padding(12.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onErrorContainer @@ -16367,7 +17190,7 @@ private fun ExistingInstallDialog( Text("Будут заменены серверные значения:", fontWeight = FontWeight.SemiBold) comparison.overwriteLines.forEach { Text("• $it", style = MaterialTheme.typography.bodySmall) } Text( - "Если нужны значения сервера, отмените установку и сначала выполните «Подключиться (без установки)». Для выходного IP используйте «Загрузить настройки».", + "Если нужны значения сервера, отмените установку и сначала выполните режим «Подключить». Для выходного IP используйте «Загрузить настройки».", style = MaterialTheme.typography.bodySmall ) } @@ -16469,7 +17292,7 @@ private fun ServerResetConfirmDialog( onDismiss: () -> Unit, onConfirm: () -> Unit ) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = onDismiss, title = { DialogTitleWithClose( @@ -16545,7 +17368,7 @@ private fun UninstallConfirmDialog( ) { val television = isTelevisionDevice() val scrollState = rememberScrollState() - androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) { + BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = onDismiss) { BoxWithConstraints( modifier = Modifier.fillMaxSize().padding(8.dp), contentAlignment = Alignment.Center diff --git a/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt b/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt index 43345d6..c29ec17 100644 --- a/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt @@ -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) + } } } diff --git a/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt b/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt index 9e56679..6feaab7 100644 --- a/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt @@ -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 diff --git a/app/src/main/java/com/wdtt/plus/ui/ExternalProxyDiagnostics.kt b/app/src/main/java/com/wdtt/plus/ui/ExternalProxyDiagnostics.kt new file mode 100644 index 0000000..177142d --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/ExternalProxyDiagnostics.kt @@ -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() diff --git a/app/src/main/java/com/wdtt/plus/ui/FirstServerSetupDialog.kt b/app/src/main/java/com/wdtt/plus/ui/FirstServerSetupDialog.kt new file mode 100644 index 0000000..7ecdac3 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/FirstServerSetupDialog.kt @@ -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 = emptyList(), + val notes: List = 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(null) } + var review by remember { mutableStateOf(null) } + var reviewedDraft by remember { mutableStateOf(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, 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 и прокси». Диагностика сервера доступна по лупе; удаление — по значку корзины и только после отдельного подтверждения.") + } +} diff --git a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt index fae4065..749b43f 100644 --- a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt +++ b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt @@ -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(null) } var resettingProfile by remember { mutableStateOf(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( diff --git a/app/src/main/java/com/wdtt/plus/ui/IconHints.kt b/app/src/main/java/com/wdtt/plus/ui/IconHints.kt new file mode 100644 index 0000000..facf767 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/IconHints.kt @@ -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(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) +} diff --git a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt index 4f36c90..5d162a6 100644 --- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt @@ -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(null) } var questionActionLoading by remember { mutableStateOf(false) } + var questionActionProfile by remember { mutableStateOf(null) } + var questionActionRetry by remember { mutableIntStateOf(0) } + var questionActionGeneration by remember { mutableIntStateOf(0) } var isCheckingDevice by remember { mutableStateOf(false) } var deviceCheckReport by remember { mutableStateOf(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 ?: "недоступно"}") diff --git a/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt b/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt index e5d902b..a319010 100644 --- a/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt @@ -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) } } diff --git a/app/src/main/java/com/wdtt/plus/ui/OutboundActionFeedback.kt b/app/src/main/java/com/wdtt/plus/ui/OutboundActionFeedback.kt new file mode 100644 index 0000000..793b860 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/OutboundActionFeedback.kt @@ -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, + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/ui/OutboundProbe.kt b/app/src/main/java/com/wdtt/plus/ui/OutboundProbe.kt new file mode 100644 index 0000000..5b7d00f --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/OutboundProbe.kt @@ -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/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() diff --git a/app/src/main/java/com/wdtt/plus/ui/RemoteCommandLog.kt b/app/src/main/java/com/wdtt/plus/ui/RemoteCommandLog.kt new file mode 100644 index 0000000..b83e3ba --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/RemoteCommandLog.kt @@ -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() + +internal class RemoteCommandCapture(private val secrets: List = 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 -> "Служебное сообщение сервера сохранено в подробностях действия." + } +} diff --git a/app/src/main/java/com/wdtt/plus/ui/RtNetworkSettingsDialog.kt b/app/src/main/java/com/wdtt/plus/ui/RtNetworkSettingsDialog.kt index e66f4fe..aa7e381 100644 --- a/app/src/main/java/com/wdtt/plus/ui/RtNetworkSettingsDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/RtNetworkSettingsDialog.kt @@ -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) + } } } diff --git a/app/src/main/java/com/wdtt/plus/ui/ScreenOffModeDialog.kt b/app/src/main/java/com/wdtt/plus/ui/ScreenOffModeDialog.kt index b48a9c9..097ca31 100644 --- a/app/src/main/java/com/wdtt/plus/ui/ScreenOffModeDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/ScreenOffModeDialog.kt @@ -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( diff --git a/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt index 0944a7b..a344126 100644 --- a/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt +++ b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt @@ -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 diff --git a/app/src/main/java/com/wdtt/plus/ui/ServerInstallCompletionNavigation.kt b/app/src/main/java/com/wdtt/plus/ui/ServerInstallCompletionNavigation.kt new file mode 100644 index 0000000..9b3fefb --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/ServerInstallCompletionNavigation.kt @@ -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, + val successCountdown: MutableIntState, + val successProfile: MutableState, + val firstInstallTunnelProfile: MutableState, + val firstInstallationProfile: MutableState, + val firstInstallationNavigationRevision: MutableState, + val firstInstallationNavigationCancelled: MutableState, + val navigationRevision: State, +) + +@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(null) } + val firstInstallTunnelProfile = rememberSaveable { mutableStateOf(null) } + val firstInstallationProfile = rememberSaveable { mutableStateOf(null) } + val firstInstallationNavigationRevision = rememberSaveable { mutableStateOf(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 + } + }) + } +} diff --git a/app/src/main/java/com/wdtt/plus/ui/ServerSetupIcon.kt b/app/src/main/java/com/wdtt/plus/ui/ServerSetupIcon.kt new file mode 100644 index 0000000..790597e --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/ServerSetupIcon.kt @@ -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) + } +} diff --git a/app/src/main/java/com/wdtt/plus/ui/SettingsDialogLayout.kt b/app/src/main/java/com/wdtt/plus/ui/SettingsDialogLayout.kt new file mode 100644 index 0000000..38989cc --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/SettingsDialogLayout.kt @@ -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() + } + } + } + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt index fac243b..9519d6a 100644 --- a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt @@ -44,6 +44,7 @@ import androidx.compose.material.icons.automirrored.filled.HelpOutline import androidx.compose.material.icons.automirrored.filled.OpenInNew import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.ContentPaste import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Cloud @@ -68,12 +69,15 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.rotate @@ -100,6 +104,7 @@ import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.withLink +import androidx.compose.ui.viewinterop.AndroidView import androidx.compose.ui.semantics.ProgressBarRangeInfo import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription @@ -116,7 +121,6 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Density 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 androidx.lifecycle.Lifecycle @@ -138,14 +142,18 @@ import com.wdtt.plus.DEFAULT_HTTP_CONNECT_PORT import com.wdtt.plus.SOCKS5_LOOPBACK_HOST import com.wdtt.plus.ManlCaptchaWebViewManager import com.wdtt.plus.MainActivity +import com.wdtt.plus.LocalContinuationCancelledException +import com.wdtt.plus.LocalContinuationExtensions import com.wdtt.plus.NativeClientStartupSecrets import com.wdtt.plus.RemoteContinuation import com.wdtt.plus.RemoteContinuationLauncher +import com.wdtt.plus.RemoteAccessCapability import com.wdtt.plus.RemoteActionCatalogGateway import com.wdtt.plus.RemoteDocumentGateway import com.wdtt.plus.RemoteLaunchTarget import com.wdtt.plus.RemoteUiAction import com.wdtt.plus.RemoteUiActionLauncher +import com.wdtt.plus.R import com.wdtt.plus.RT_MASQUE_CONFIG_FILE_NAME import com.wdtt.plus.SettingsStore import com.wdtt.plus.TunnelManager @@ -207,6 +215,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import kotlinx.coroutines.CancellationException +import java.util.concurrent.atomic.AtomicBoolean import android.content.Intent import android.net.Uri import android.net.VpnService @@ -222,15 +231,20 @@ internal fun proxySettingsButtonShowsLabel(availableWidthDp: Int): Boolean = ava private const val WORKERS_PER_GROUP = 9 private const val REMOTE_ACTION_REFRESH_MS = 10 * 60 * 1000L -private fun launchRemoteTarget(context: Context, target: RemoteLaunchTarget) { +private fun mainActivityFrom(context: Context): MainActivity? { var current: Context? = context while (current != null) { - if (current is MainActivity) { - current.launchRemoteContinuation(target) - return - } + if (current is MainActivity) return current current = (current as? ContextWrapper)?.baseContext } + return null +} + +private fun launchRemoteTarget(context: Context, target: RemoteLaunchTarget) { + mainActivityFrom(context)?.let { activity -> + activity.launchRemoteContinuation(target) + return + } RemoteContinuationLauncher.launch(context, target) } @@ -443,6 +457,8 @@ fun SettingsTab( scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }, onVkHashesSaved: (Int, List) -> Unit = { _, _ -> }, onOpenProjectSupport: () -> Unit = {}, + onProfileHeaderBounds: (Rect) -> Unit = {}, + onProfileHeaderBoundary: (Float) -> Unit = {}, ) { val context = LocalContext.current val scope = rememberCoroutineScope() @@ -458,6 +474,8 @@ fun SettingsTab( scrollPosition = scrollPosition, onVkHashesSaved = onVkHashesSaved, onOpenProjectSupport = onOpenProjectSupport, + onProfileHeaderBounds = onProfileHeaderBounds, + onProfileHeaderBoundary = onProfileHeaderBoundary, ) } } @@ -471,6 +489,8 @@ fun SettingsTabContent( scrollPosition: MutableIntState, onVkHashesSaved: (Int, List) -> Unit, onOpenProjectSupport: () -> Unit, + onProfileHeaderBounds: (Rect) -> Unit, + onProfileHeaderBoundary: (Float) -> Unit, ) { val profileSnapshotState by settingsStore.activeTunnelProfileContentUiSnapshot.collectAsStateWithLifecycle() @@ -538,6 +558,7 @@ fun SettingsTabContent( val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle() val activeWorkers by TunnelManager.activeWorkers.collectAsStateWithLifecycle() + val connectionPath by TunnelManager.connectionPath.collectAsStateWithLifecycle() val wakeRecoveryInProgress by TunnelManager.wakeRecoveryInProgress.collectAsStateWithLifecycle() val wakeRecoveryReadyWorkers by TunnelManager.wakeRecoveryReadyWorkers.collectAsStateWithLifecycle() val wakeRecoveryTargetWorkers by TunnelManager.wakeRecoveryTargetWorkers.collectAsStateWithLifecycle() @@ -796,7 +817,7 @@ fun SettingsTabContent( val linkConnectionPresent = remember(wdttLink) { WdttDeepLink.parse(wdttLink, allowMissingHashes = true) != null } - val rtSniValid = !rtNetwork || normalizeRtTurnSni(rtTurnSniInput) != null + val rtSniValid = normalizeRtTurnSni(rtTurnSniInput) != null val socksSettingsValid = proxySettingsAreValid( mode = tunnelMode, port = socksPortInput.toIntOrNull() ?: 0, @@ -850,7 +871,7 @@ fun SettingsTabContent( if (intent == null) { TunnelManager.reportConnectionIssue( "Профиль заполнен не полностью", - "Проверьте адрес, пароль подключения и VK-хеши." + "Проверьте адрес, пароль подключения и ВК-хеши." ) TunnelManager.clearTransition() Toast.makeText(context, "Проверьте настройки профиля", Toast.LENGTH_LONG).show() @@ -1306,18 +1327,6 @@ fun SettingsTabContent( scope.launch { settingsStore.saveCaptchaPreference(enabled) } }, onRtNetworkSettings = { showRtNetworkSettings = true }, - onRtNetworkHelp = { showRtNetworkHelp = true }, - onRtNetworkChange = { enabled -> - saveJob?.cancel() - val nextSni = if (enabled) { - normalizeRtTurnSni(rtTurnSniInput) ?: DEFAULT_RT_TURN_SNI - } else { - rtTurnSniInput.trim() - } - rtTurnSniInput = nextSni - scope.launch { settingsStore.saveRtNetwork(enabled, nextSni) } - if (enabled) showRtNetworkSettings = true - }, onDismiss = { showLaunchParameters = false }, ) } @@ -1455,6 +1464,9 @@ fun SettingsTabContent( Text( "Настройки соединения (${vpnProfileDisplayName(activeProfile, profileNames)})", + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp) + .wrapContentHeight(Alignment.CenterVertically) + .onGloballyPositioned { onProfileHeaderBounds(it.boundsInWindow()) }, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), color = MaterialTheme.colorScheme.onSurface, ) @@ -1468,6 +1480,7 @@ fun SettingsTabContent( if (!remoteManagedProfile) { CompactTunnelProfileCard( + modifier = Modifier.onGloballyPositioned { onProfileHeaderBoundary(it.boundsInWindow().top) }, hasConnection = hasConnectionSource, connectionMethod = userConnectionMethod, savedConnectionMethod = savedConnectionInputMethod, @@ -1483,6 +1496,7 @@ fun SettingsTabContent( ) } AppSectionCard( + modifier = if (remoteManagedProfile) Modifier.onGloballyPositioned { onProfileHeaderBoundary(it.boundsInWindow().top) } else Modifier, containerColor = if (proxySettingsNeedAttention) { MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.24f) } else null, @@ -1556,7 +1570,7 @@ fun SettingsTabContent( fontWeight = FontWeight.SemiBold, ) Spacer(Modifier.width(3.dp)) - IconButton( + HintIconButton(hint = "Инструкция по режимам работы", onClick = { showSocksHelp = true }, modifier = Modifier.size(34.dp).remoteHelpFocus(), ) { @@ -1577,6 +1591,7 @@ fun SettingsTabContent( enabled = !tunnelRunning, modifier = Modifier .height(34.dp) + .iconHoldHint("Настройки ${tunnelModeStatusLabel(tunnelMode)}") .remoteCompactFocus( shape = settingsButtonShape, enabled = !tunnelRunning, @@ -1744,7 +1759,7 @@ fun SettingsTabContent( ) } if (copyAvailable) { - IconButton( + HintIconButton(hint = "Выбрать параметры прокси для копирования", onClick = { showProxyCopyDialog = true }, modifier = Modifier .align(Alignment.BottomEnd) @@ -1814,7 +1829,7 @@ fun SettingsTabContent( ) { Icon(Icons.Default.Tag, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - FlexibleButtonText("Настройка VK Хешей ($filledHashCount/4)", fontWeight = FontWeight.SemiBold) + FlexibleButtonText("Настройка ВК-хешей ($filledHashCount/4)", fontWeight = FontWeight.SemiBold) } val errorTexts = hashErrors.filter { !it.contains("короткий") } @@ -2085,6 +2100,10 @@ fun SettingsTabContent( if (showRtNetworkSettings) { RtNetworkSettingsDialog( rtNetwork = rtNetwork, + connectionPath = connectionPath.takeIf { tunnelRunning && activeWorkers > 0 }.orEmpty(), + onConnectionModeChange = { stream -> + scope.launch { settingsStore.saveConnectionMode(stream) } + }, turnSni = rtTurnSniInput, turnSniValid = normalizeRtTurnSni(rtTurnSniInput) != null, rtMasque = rtMasque, @@ -2097,7 +2116,7 @@ fun SettingsTabContent( saveJob?.cancel() saveJob = scope.launch { delay(300) - settingsStore.saveRtNetwork(enabled = true, turnSni = nextSni) + settingsStore.saveConnectionSni(nextSni, activeProfile) } }, onRtMasqueChange = { enabled -> @@ -2127,11 +2146,11 @@ fun SettingsTabContent( } if (showVkCallsHelp) { SettingsHelpDialog( - title = "Быстрый VKCalls", + title = "Быстрые ВК Звонки", paragraphs = listOf( - "Первым приложение пробует современный анонимный путь VKCalls через системный VK Connect. Ему не нужны ваш Client ID, Client secret или VK Smart Captcha — обычно это самый быстрый и стабильный вариант.", - "Если VKCalls временно недоступен, приложение автоматически пробует собственные legacy-реквизиты (если они включены), затем выбранные встроенные legacy Client ID. В legacy-ветке полностью сохраняется авторешение капчи.", - "Переключатель отключает только первый быстрый провайдер. Для обычной работы рекомендуется оставить VKCalls включённым." + "Первым приложение пробует современный анонимный путь ВК Звонков через системный ВК Connect. Ему не нужны ваш Client ID, Client secret или ВК Smart Captcha — обычно это самый быстрый и стабильный вариант.", + "Если ВК Звонки временно недоступны, приложение автоматически пробует собственные legacy-реквизиты (если они включены), затем выбранные встроенные legacy Client ID. В legacy-ветке полностью сохраняется авторешение капчи.", + "Переключатель отключает только первый быстрый провайдер. Для обычной работы рекомендуется оставить ВК Звонки включёнными." ), onDismiss = { showVkCallsHelp = false } ) @@ -2140,8 +2159,8 @@ fun SettingsTabContent( SettingsHelpDialog( title = "Режим капчи", paragraphs = listOf( - "Эта настройка применяется только к резервным legacy-провайдерам: основной быстрый VKCalls обычно получает TURN-данные без капчи.", - "Авто капча: каждый свежий challenge сначала решается через Auto WebView. Go v2 и ручной WebView используются как запасные этапы, если автоматический WebView не дал рабочий токен или VK потребовал более строгую проверку.", + "Эта настройка применяется только к резервным legacy-провайдерам: основные быстрые ВК Звонки обычно получают TURN-данные без капчи.", + "Авто капча: каждый свежий challenge сначала решается через Auto WebView. Go v2 и ручной WebView используются как запасные этапы, если автоматический WebView не дал рабочий токен или ВК потребовал более строгую проверку.", "Всегда вручную: если legacy-провайдер получил капчу, приложение сразу открывает WebView для самостоятельного прохождения проверки." ), onDismiss = { showAutoCaptchaHelp = false } @@ -2149,31 +2168,30 @@ fun SettingsTabContent( } if (showRtNetworkHelp) { SettingsHelpDialog( - title = "Сеть РТ", + title = "Подключение", paragraphs = listOf( - "Режим предназначен для мобильной сети Ростелекома с белыми списками: разрешённые сайты открываются, но обычный WDTT Plus не подключается. В сети РТ без таких ограничений, у других операторов и по обычному Wi‑Fi он, как правило, не нужен.", - "При включении порядок меняется только для этого профиля: TURN/TLS с указанным SNI → TURN/TCP ко всем адресам, полученным от VK, с разделением первого STUN-запроса → MASQUE HTTP/2 и HTTP/3, если он включён → TURN/UDP как последний резерв. При выключенном режиме сохраняется обычный порядок с приоритетом UDP.", - "SNI по умолчанию — ya.ru; его можно заменить доступным доменом из белого списка. Это только имя во внешнем TLS-рукопожатии TURN/TLS и MASQUE: трафик не становится трафиком этого сайта, а TURN/TCP и TURN/UDP вообще не содержат SNI.", - "Для TURN/TLS приложение продолжает проверять публичную цепочку сертификата, но при подмене SNI не сопоставляет имя сертификата с доменом белого списка. MASQUE проверяет конечную точку по публичному ключу из регистрации WARP. Пароль подключения и шифрование WRAP не меняются.", - "Оператор может одновременно учитывать SNI, IP, порт и протокол, поэтому один SNI не гарантирует результат. TURN/TLS/TCP и MASQUE используют разные адреса и механизмы: рабочий вариант определяется только проверкой в конкретном регионе и тарифе.", - "TLS и TCP обычно дают большую задержку и хуже переносят потери, а MASQUE дополнительно расходует батарею и трафик. Если обычный режим работает, оставьте «Сеть РТ» выключенной.", - "После заблокированной UDP-попытки сеть иногда несколько минут плохо пропускает DNS или другой трафик. Перед повторной проверкой остановите VPN, дождитесь восстановления сайтов или переподключите мобильную сеть, затем запускайте режим заново." + "UDP\nВыбран по умолчанию. Сначала проверяет UDP; если он недоступен, подключается через TCP/TLS. Отказ одного канала не отключает остальные рабочие UDP-каналы. Когда рабочих UDP-каналов нет, новые проверки внешнего UDP откладываются на 5 минут. Рабочее резервное соединение сохраняется до следующего подключения или смены сети.", + "TCP/TLS\nПодключается через TLS и TCP, не использует внешний UDP и HTTP/3. Подходит для сетей, в которых UDP недоступен или вызывает проблемы. Приложения внутри VPN по-прежнему могут использовать UDP.", + "Проверка и восстановление\nВ обоих режимах приложение проверяет ответ вашего сервера и восстанавливает потерянные каналы, сохраняя рабочие. После серии неудач приостанавливает попытки до смены сети или нового подключения. Настройка сохраняется отдельно для каждого профиля.", + "Внешний SNI\nИмя домена для внешнего TLS-соединения. Применяется к TURN/TLS и MASQUE; в TURN/TCP и UDP не используется. Меняйте его, только если знаете подходящее значение для своей сети.", + "MASQUE\nДополнительный способ подключения через Cloudflare, если основные способы недоступны. Доступен в обоих режимах после отдельного включения и согласия с условиями Cloudflare. Может увеличить задержку и время подключения.", + "Регистрация по SSH\nНужна только тогда, когда первая регистрация WARP для MASQUE не проходит напрямую. Использует сервер, указанный в «Деплой» по значку ключа; весь VPN-трафик через этот SSH-канал не направляется. Если регистрация уже сохранена, SSH не нужен.", + "Если интернет пропал полностью\nНастройки подключения не восстанавливают услугу мобильного оператора. Если не открываются даже разрешённые сайты, проверьте мобильный интернет без VPN.", ), - highlightedParagraphIndices = setOf(6), onDismiss = { showRtNetworkHelp = false } ) } if (showRtMasqueHelp) { SettingsHelpDialog( - title = "MASQUE в сети РТ", + title = "MASQUE", paragraphs = listOf( - "Экспериментальный резерв только внутри «Сети РТ». После прямых TURN/TLS и TURN/TCP приложение пробует WARP CONNECT-IP с SNI из поля настроек; TURN/UDP остаётся последним аварийным путём.", - "Сначала проверяется HTTP/2 по TCP/443, затем HTTP/3 по QUIC/443. Успешный вариант совместно используется воркерами до остановки VPN; при новом запуске проверка выполняется заново, потому что доступность путей могла измениться.", - "Для первого запуска приложение регистрирует отдельное устройство Cloudflare WARP. Корректная регистрация хранится только в приватном каталоге WDTT Plus и повторно используется после перезапуска приложения и выключения рубильников — заново создавать её при каждом подключении не требуется.", - "Регистрация сначала выполняется через системную сеть и DNS Android с проверкой сертификата Cloudflare. Если прямой TLS не проходит до отправки данных и включён «Через сервер», последняя попытка регистрации идёт по SSH через сервер активного профиля. Обычный MASQUE-трафик через этот сервер не направляется.", - "Cloudflare обрабатывает внешний туннель и может видеть служебные метаданные и адреса назначения. Конечная точка MASQUE проверяется по публичному ключу сохранённой регистрации WARP, а шифрование WRAP между приложением и вашим WDTT-сервером сохраняется.", - "Режим может увеличить первый запуск, задержку, расход батареи и трафика и не гарантирует обход блокировки IP, TCP/443 или QUIC/443. Он активен только при одновременно включённых «Сеть РТ» и MASQUE; остальные режимы не меняются.", - "Сбрасывайте регистрацию WARP только при сообщении о повреждённых или отклонённых данных. Сброс удаляет локальные ключи, и следующему запуску снова понадобится регистрация; обычную сетевую блокировку это не исправляет." + "Когда использовать\nВключите MASQUE, если обычные способы подключения недоступны. Это дополнительное соединение через Cloudflare для обоих режимов.", + "Как подключается\nСначала используется HTTP/2. HTTP/3 доступен только в режиме UDP и не проверяется во время паузы после отказа внешнего UDP. Режим TCP/TLS использует только HTTP/2. При новом подключении доступность проверяется снова.", + "Регистрация WARP\nПри первом использовании MASQUE приложение регистрирует устройство в Cloudflare WARP. Регистрация начинается только при переходе к этому резервному способу. Данные сохраняются в защищённом хранилище приложения и используются повторно.", + "Если регистрация не проходит\nПриложение сначала обращается к Cloudflare напрямую. Настройка «Регистрация по SSH» позволяет выполнить регистрацию через сервер из «Деплой» по значку ключа, если прямое соединение не установилось. Само подключение MASQUE через SSH не идёт.", + "Конфиденциальность\nCloudflare обрабатывает внешнее соединение и может видеть служебные сведения и адреса назначения. Шифрование между приложением и вашим WDTT-сервером сохраняется. Для включения нужно согласиться с условиями Cloudflare.", + "Ограничения\nMASQUE может увеличить время подключения, задержку, расход батареи и трафика. Он не гарантирует доступ, если сеть блокирует необходимые адреса или соединения с Cloudflare.", + "Сброс регистрации\nИспользуйте сброс только при сообщении о повреждённых или отклонённых данных WARP. Он удаляет сохранённые ключи: при следующем использовании MASQUE потребуется новая регистрация. Обычную сетевую блокировку сброс не исправляет.", ), onDismiss = { showRtMasqueHelp = false }, secondaryActionLabel = "Сбросить регистрацию WARP", @@ -2193,15 +2211,15 @@ fun SettingsTabContent( } if (showRtMasqueServerBootstrapHelp) { SettingsHelpDialog( - title = "Регистрация через сервер", + title = "Регистрация по SSH", paragraphs = listOf( - "Помогает выполнить первоначальную регистрацию WARP, если Android не может напрямую установить TLS-соединение с API Cloudflare. Режим работает лишь вместе с «Сеть РТ» и MASQUE; обычный трафик WDTT, TURN и последующие соединения MASQUE через сервер не проходят.", - "Рубильник доступен, если в активном профиле раздела «Деплой» указан адрес сервера и выбран рабочий вход по SSH: пароль либо корректный приватный ключ. Если данных не хватает, рядом с выключенным рубильником указана точная причина.", - "Вероятнее всего, нужен иностранный сервер за пределами РФ — российский сервер может встретить те же ограничения доступа к Cloudflare.", - "SSH-сервер должен быть доступен из текущей сети и разрешать TCP-переадресацию.", - "На сервер ничего не устанавливается. WDTT Plus временно использует стандартную SSH-переадресацию только для HTTPS-запросов регистрации; сертификат Cloudflare проверяется сквозным TLS. Cloudflare видит IP сервера, а владелец сервера — факт соединения и объём, но не содержимое HTTPS.", - "Сначала приложение всё равно пробует прямые безопасные HTTPS-пути. К SSH оно переходит только при сбое до отправки регистрационных данных, поэтому запрос не дублируется небезопасным образом. Ошибка SSH записывается в журнал, а незавершённая регистрация не сохраняется.", - "После успешной регистрации SSH-выход закрывается, а данные WARP сохраняются в приватном хранилище. Пока сохранённая регистрация корректна, приложение не создаёт новую и рубильник фактически не используется — даже после перезапуска или временного выключения «Сети РТ» и MASQUE." + "Когда использовать\nПомогает выполнить первоначальную регистрацию WARP, если Android не может напрямую установить TLS-соединение с API Cloudflare. Настройка работает в обоих режимах с включённым MASQUE; обычный трафик WDTT, TURN и последующие соединения MASQUE через сервер не проходят.", + "Настройка сервера\nНастройка доступна, если в активном профиле «Деплой» по значку ключа указан адрес сервера и выбран рабочий вход по SSH: пароль либо корректный приватный ключ. Если данных не хватает, рядом с переключателем указана точная причина.", + "Расположение сервера\nВероятнее всего, нужен иностранный сервер за пределами РФ — российский сервер может встретить те же ограничения доступа к Cloudflare.", + "Доступность SSH\nSSH-сервер должен быть доступен из текущей сети и разрешать TCP-переадресацию.", + "Как это работает\nНа сервер ничего не устанавливается. WDTT Plus временно использует стандартную SSH-переадресацию только для HTTPS-запросов регистрации; сертификат Cloudflare проверяется сквозным TLS. Cloudflare видит IP сервера, а владелец сервера — факт соединения и объём, но не содержимое HTTPS.", + "Порядок попыток\nСначала приложение всё равно пробует прямые безопасные HTTPS-пути. К SSH оно переходит только при сбое до отправки регистрационных данных, поэтому запрос не дублируется небезопасным образом. Ошибка SSH записывается в журнал, а незавершённая регистрация не сохраняется.", + "После регистрации\nПосле успешной регистрации SSH-выход закрывается, а данные WARP сохраняются в приватном хранилище. Пока сохранённая регистрация корректна, приложение не создаёт новую и регистрация по SSH не требуется — даже после перезапуска или временного выключения MASQUE." ), highlightedParagraphIndices = setOf(2), onDismiss = { showRtMasqueServerBootstrapHelp = false }, @@ -2210,7 +2228,7 @@ fun SettingsTabContent( if (showRtMasqueConsent) { val linkColor = MaterialTheme.colorScheme.primary val cloudflareTerms = buildAnnotatedString { - append("Включая механизм, вы соглашаетесь с ") + append("Включая MASQUE, вы соглашаетесь с ") withLink( LinkAnnotation.Url( url = "https://www.cloudflare.com/application/terms/", @@ -2227,12 +2245,12 @@ fun SettingsTabContent( } append(" и разрешаете WDTT Plus зарегистрировать отдельное устройство WARP.") } - AlertDialog( + BoundedAlertDialog( onDismissRequest = { showRtMasqueConsent = false }, title = { Text("Включить MASQUE?") }, text = { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - Text("Это внешний экспериментальный транспорт. Cloudflare будет обрабатывать туннель и сможет видеть метаданные подключений. При первом запуске VPN приложение в фоне зарегистрирует отдельное устройство WARP; для этого может потребоваться обычный интернет.") + Text("Это дополнительное соединение через Cloudflare. Сервис будет обрабатывать внешний туннель и сможет видеть служебные сведения о подключениях. При первом использовании MASQUE приложение зарегистрирует устройство WARP; для регистрации может потребоваться сеть без ограничений.") Text(cloudflareTerms) } }, @@ -2252,7 +2270,7 @@ fun SettingsTabContent( ) } if (showRtMasqueResetConfirm) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = { showRtMasqueResetConfirm = false }, title = { Text("Сбросить регистрацию WARP?") }, text = { @@ -2384,6 +2402,8 @@ internal fun proxyTunnelAddressSummary( if (readyAddresses.isNotEmpty()) { if (running) append("готов: ") append(readyAddresses.distinct().joinToString(" · ")) + } else if (running) { + append("не запущен") } else { append(fallbackAddress) } @@ -2516,7 +2536,8 @@ private fun ProxySettingsDialog( return } - AlertDialog( + BoundedAlertDialog( + scrollableText = false, onDismissRequest = onDismiss, title = { Row( @@ -2549,7 +2570,7 @@ private fun ProxySettingsDialog( style = MaterialTheme.typography.titleSmall, ) Spacer(Modifier.width(3.dp)) - IconButton( + HintIconButton(hint = "Инструкция по протоколам прокси", onClick = { showProtocolHelp = true }, modifier = Modifier.size(32.dp).remoteHelpFocus(), ) { @@ -2609,7 +2630,7 @@ private fun ProxySettingsDialog( style = MaterialTheme.typography.titleSmall, ) Spacer(Modifier.width(3.dp)) - IconButton( + HintIconButton(hint = "Инструкция по доступу к прокси", onClick = { showAccessHelp = true }, modifier = Modifier.size(32.dp).remoteHelpFocus(), ) { @@ -2678,7 +2699,7 @@ private fun ProxySettingsDialog( }, ) if (includesLan) { - IconButton( + HintIconButton(hint = "Проверить локальную сеть снова", onClick = { if (!lanCheckInProgress) { lanCheckInProgress = true @@ -2903,7 +2924,7 @@ private fun ProxySettingsDialog( singleLine = true, isError = !isValidSocks5Credential(username), trailingIcon = { - IconButton( + HintIconButton(hint = "Скопировать логин", enabled = username.isNotBlank(), onClick = { clipboardManager.setText( @@ -2931,7 +2952,7 @@ private fun ProxySettingsDialog( }, trailingIcon = { Row { - IconButton( + HintIconButton(hint = "Создать новый пароль", onClick = { password = generateProxyPassword() passwordFocusRequester.requestFocus() @@ -2947,7 +2968,7 @@ private fun ProxySettingsDialog( contentDescription = "Создать новый пароль", ) } - IconButton( + HintIconButton(hint = "Скопировать пароль", enabled = password.isNotBlank(), onClick = { clipboardManager.setText( @@ -3010,7 +3031,8 @@ private fun ProxyCopyDialog( } var qrDialogState by remember { mutableStateOf?>(null) } var qrInProgress by remember { mutableStateOf(null) } - AlertDialog( + BoundedAlertDialog( + scrollableText = false, onDismissRequest = onDismiss, title = { Row( @@ -3060,7 +3082,7 @@ private fun ProxyCopyDialog( color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - IconButton( + HintIconButton(hint = "Показать QR-код: ${option.protocolLabel}, ${option.accessLabel}", enabled = qrInProgress == null, onClick = { qrInProgress = option.uri @@ -3100,7 +3122,7 @@ private fun ProxyCopyDialog( ) } } - IconButton( + HintIconButton(hint = "Скопировать ${option.protocolLabel}, ${option.accessLabel}", onClick = { copySensitiveProxyLink( context = context, @@ -3168,7 +3190,7 @@ private fun ProxyQrDialog( containsCredentials: Boolean, onDismiss: () -> Unit, ) { - AlertDialog( + BoundedAlertDialog( onDismissRequest = onDismiss, text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { @@ -3576,7 +3598,7 @@ private fun AccessLifecycleCard( modifier = Modifier.weight(1f), ) if (onRouteUpdate != null) { - IconButton( + HintIconButton(hint = "Обновить маршрут", onClick = onRouteUpdate, enabled = !actionBusy, modifier = Modifier.size(36.dp), @@ -3589,7 +3611,7 @@ private fun AccessLifecycleCard( ) } } - IconButton( + HintIconButton(hint = "Проверить профиль", onClick = onRefresh, enabled = !refreshing && !actionBusy, modifier = Modifier.size(36.dp), @@ -3806,16 +3828,17 @@ private fun tunnelLaunchParametersSummary( rtMasque: Boolean, ): String { val rtText = when { - rtNetwork && rtMasque -> "РТ + MASQUE" - rtNetwork -> "РТ вкл" - else -> "РТ выкл" + rtNetwork && rtMasque -> "TCP/TLS + MASQUE" + rtNetwork -> "TCP/TLS" + rtMasque -> "UDP + MASQUE" + else -> "UDP" } return buildList { add("$workers потоков") if (normalizeTunnelMode(tunnelMode) == TUNNEL_MODE_VPN) { add("DNS: ${dnsSettings.title}") } - add(if (vkCallsPreflight) "VKCalls вкл" else "VKCalls выкл") + add(if (vkCallsPreflight) "ВК Звонки вкл" else "ВК Звонки выкл") add(if (autoCaptchaEnabled) "Капча авто" else "Капча вручную") add(rtText) }.joinToString(" · ") @@ -3841,181 +3864,123 @@ private fun TunnelLaunchParametersDialog( onAutoCaptchaHelp: () -> Unit, onAutoCaptchaChange: (Boolean) -> Unit, onRtNetworkSettings: () -> Unit, - onRtNetworkHelp: () -> Unit, - onRtNetworkChange: (Boolean) -> Unit, onDismiss: () -> Unit, ) { - Dialog( - onDismissRequest = onDismiss, - properties = DialogProperties(usePlatformDefaultWidth = false), - ) { - BoxWithConstraints( - modifier = Modifier.fillMaxSize().padding(8.dp), - contentAlignment = Alignment.Center, + SettingsDialogLayout(title = "Параметры соединения", onDismiss = onDismiss) { + Text( + "Изменения сохраняются сразу и будут использованы при следующем подключении.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + if (normalizeTunnelMode(tunnelMode) == TUNNEL_MODE_VPN) { + VpnDnsSettingsCard( + settings = vpnDnsSettings, + onClick = onOpenDnsSettings, + ) + } + + ConnectionSettingsCard( + mode = when { + rtNetwork -> "TCP/TLS" + else -> "UDP" + }, + onClick = onRtNetworkSettings, + ) + + AppSectionCard( + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp), + verticalArrangement = Arrangement.spacedBy(0.dp), ) { - Surface( - modifier = Modifier - .fillMaxWidth(0.95f) - .heightIn(max = maxHeight * 0.92f), - shape = RoundedCornerShape(24.dp), - color = MaterialTheme.colorScheme.surface, - contentColor = MaterialTheme.colorScheme.onSurface, - tonalElevation = 8.dp, + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, ) { - Column( - modifier = Modifier.padding(20.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, + Text( + "Мощность", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.SemiBold, + ) + HintIconButton(hint = "Что такое мощность", + onClick = onPowerHelp, + modifier = Modifier.size(28.dp).remoteHelpFocus(), ) { - Text( - "Параметры соединения", - modifier = Modifier.weight(1f), - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary, + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Что такое мощность", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp), ) - IconButton( - onClick = onDismiss, - modifier = Modifier.remoteIconButtonFocus(), - ) { - Icon(Icons.Default.Close, contentDescription = "Закрыть") - } - } - - Column( - modifier = Modifier - .weight(1f, fill = false) - .verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - Text( - "Изменения сохраняются сразу и будут использованы при следующем подключении.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - if (normalizeTunnelMode(tunnelMode) == TUNNEL_MODE_VPN) { - VpnDnsSettingsCard( - settings = vpnDnsSettings, - onClick = onOpenDnsSettings, - ) - } - - AppSectionCard( - contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp), - verticalArrangement = Arrangement.spacedBy(0.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - Text( - "Мощность", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.primary, - fontWeight = FontWeight.SemiBold, - ) - IconButton( - onClick = onPowerHelp, - modifier = Modifier.size(28.dp).remoteHelpFocus(), - ) { - Icon( - Icons.AutoMirrored.Filled.HelpOutline, - contentDescription = "Что такое мощность", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(18.dp), - ) - } - } - Text( - text = "${currentWorkers.toInt()}", - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.primary, - ) - } - - Spacer(Modifier.height(2.dp)) - - val minWorkers = WORKERS_PER_GROUP.toFloat() - val currentWorkersVal = roundToGroup( - currentWorkers.coerceIn(minWorkers, dynamicMaxWorkers), - dynamicMaxWorkers, - ) - - CompactSteppedSlider( - value = currentWorkersVal, - onValueChange = onWorkersChange, - onValueChangeFinished = onWorkersChangeFinished, - valueRange = minWorkers..dynamicMaxWorkers, - stepSize = WORKERS_PER_GROUP.toFloat(), - enabled = !tunnelRunning && dynamicMaxWorkers > minWorkers, - modifier = Modifier.fillMaxWidth(), - ) - - if (profileMaxWorkers >= WORKERS_PER_GROUP) { - Text( - text = "Для этого профиля доступен выбор от ${WORKERS_PER_GROUP.toInt()} до $profileMaxWorkers потоков. Повысить значение выше нельзя.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(4.dp)) - } - - HorizontalDivider( - modifier = Modifier.padding(vertical = 2.dp), - color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f), - ) - - LaunchParameterSwitchRow( - title = "Быстрый VKCalls", - checked = vkCallsPreflight, - enabled = !tunnelRunning, - onCheckedChange = onVkCallsChange, - onHelp = onVkCallsHelp, - helpDescription = "Как работает VKCalls", - ) - - HorizontalDivider( - modifier = Modifier.padding(vertical = 2.dp), - color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f), - ) - - LaunchParameterSwitchRow( - title = if (autoCaptchaEnabled) "Авто капча" else "Всегда вручную", - checked = autoCaptchaEnabled, - enabled = true, - onCheckedChange = onAutoCaptchaChange, - onHelp = onAutoCaptchaHelp, - helpDescription = "Как работает режим капчи", - ) - - HorizontalDivider( - modifier = Modifier.padding(vertical = 2.dp), - color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f), - ) - - LaunchParameterSwitchRow( - title = "Сеть РТ", - checked = rtNetwork, - enabled = !tunnelRunning, - onCheckedChange = onRtNetworkChange, - onHelp = onRtNetworkHelp, - helpDescription = "Как работает Сеть РТ", - onTitleClick = onRtNetworkSettings, - ) - } } } + Text( + text = "${currentWorkers.toInt()}", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.primary, + ) } + + Spacer(Modifier.height(2.dp)) + + val minWorkers = WORKERS_PER_GROUP.toFloat() + val currentWorkersVal = roundToGroup( + currentWorkers.coerceIn(minWorkers, dynamicMaxWorkers), + dynamicMaxWorkers, + ) + + CompactSteppedSlider( + value = currentWorkersVal, + onValueChange = onWorkersChange, + onValueChangeFinished = onWorkersChangeFinished, + valueRange = minWorkers..dynamicMaxWorkers, + stepSize = WORKERS_PER_GROUP.toFloat(), + enabled = !tunnelRunning && dynamicMaxWorkers > minWorkers, + modifier = Modifier.fillMaxWidth(), + ) + + if (profileMaxWorkers >= WORKERS_PER_GROUP) { + Text( + text = "Для этого профиля доступен выбор от ${WORKERS_PER_GROUP.toInt()} до $profileMaxWorkers потоков. Повысить значение выше нельзя.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(4.dp)) + } + + HorizontalDivider( + modifier = Modifier.padding(vertical = 2.dp), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f), + ) + + LaunchParameterSwitchRow( + title = "Быстрые ВК Звонки", + checked = vkCallsPreflight, + enabled = !tunnelRunning, + onCheckedChange = onVkCallsChange, + onHelp = onVkCallsHelp, + helpDescription = "Как работают ВК Звонки", + ) + + HorizontalDivider( + modifier = Modifier.padding(vertical = 2.dp), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f), + ) + + LaunchParameterSwitchRow( + title = if (autoCaptchaEnabled) "Авто капча" else "Всегда вручную", + checked = autoCaptchaEnabled, + enabled = true, + onCheckedChange = onAutoCaptchaChange, + onHelp = onAutoCaptchaHelp, + helpDescription = "Как работает режим капчи", + ) + } } } @@ -4040,12 +4005,12 @@ private fun LaunchParameterSwitchRow( Row( modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), + horizontalArrangement = Arrangement.spacedBy(2.dp), ) { Text( title, modifier = Modifier - .weight(1f) + .weight(1f, fill = false) .then(if (onTitleClick != null) { Modifier .remoteFocusOutline(RoundedCornerShape(8.dp)) @@ -4062,7 +4027,7 @@ private fun LaunchParameterSwitchRow( style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium, ) - IconButton( + HintIconButton(hint = helpDescription, onClick = onHelp, modifier = Modifier.size(28.dp).remoteHelpFocus(), ) { @@ -4549,7 +4514,7 @@ internal fun tunnelPowerVisualState( } @Composable -private fun rememberUnderlyingNetworkAvailable(): Boolean { +internal fun rememberUnderlyingNetworkAvailable(): Boolean { val context = LocalContext.current.applicationContext var available by remember(context) { mutableStateOf(hasUnderlyingInternetNetwork(context)) @@ -4649,107 +4614,53 @@ private fun SettingsHelpDialog( secondaryActionEnabled: Boolean = true, onSecondaryActionDisabled: (() -> Unit)? = null, ) { - val television = isTelevisionDevice() - val scrollState = rememberScrollState() - Dialog( - onDismissRequest = onDismiss, - properties = DialogProperties(usePlatformDefaultWidth = !television), + SettingsDialogLayout( + title = title, + onDismiss = onDismiss, ) { - BoxWithConstraints( - modifier = Modifier.fillMaxSize().padding(8.dp), - contentAlignment = Alignment.Center - ) { - Surface( - modifier = Modifier - .televisionDialogWidth(television) - .heightIn(max = maxHeight * 0.92f), - shape = RoundedCornerShape(24.dp), - color = MaterialTheme.colorScheme.surface, - contentColor = MaterialTheme.colorScheme.onSurface, - tonalElevation = 8.dp - ) { - Column( - modifier = Modifier - .padding(22.dp) - .fillMaxWidth() - .verticalScroll(scrollState) - .tvDpadScrollable(scrollState, television), - verticalArrangement = Arrangement.spacedBy(12.dp) + paragraphs.forEachIndexed { index, paragraph -> + if (index in highlightedParagraphIndices) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.72f), + contentColor = MaterialTheme.colorScheme.onTertiaryContainer, + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.tertiary.copy(alpha = 0.32f), + ), ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - title, - modifier = Modifier.weight(1f), - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary - ) - IconButton( - onClick = onDismiss, - modifier = Modifier.remoteIconButtonFocus(), - ) { - Icon(Icons.Default.Close, contentDescription = "Закрыть") - } - } - paragraphs.forEachIndexed { index, paragraph -> - if (index in highlightedParagraphIndices) { - Surface( - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(14.dp), - color = MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.72f), - contentColor = MaterialTheme.colorScheme.onTertiaryContainer, - border = BorderStroke( - 1.dp, - MaterialTheme.colorScheme.tertiary.copy(alpha = 0.32f), - ), - ) { - SettingsHelpParagraph( - paragraph, - modifier = Modifier.padding(12.dp), - highlighted = true, - ) - } - } else { - SettingsHelpParagraph( - paragraph, - highlighted = false, - ) - } - } - if (secondaryActionLabel != null && onSecondaryAction != null) { - Box(modifier = Modifier.fillMaxWidth()) { - OutlinedButton( - onClick = onSecondaryAction, - enabled = secondaryActionEnabled, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), - ) { - FlexibleButtonText(secondaryActionLabel) - } - if (!secondaryActionEnabled && onSecondaryActionDisabled != null) { - Box( - modifier = Modifier - .matchParentSize() - .remoteFocusOutline(RoundedCornerShape(16.dp)) - .clickable(onClick = onSecondaryActionDisabled), - ) - } - } - } - Button( - onClick = onDismiss, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) - ) { - FlexibleButtonText("Понятно", fontWeight = FontWeight.Bold) - } - Spacer(Modifier.height(4.dp)) + SettingsHelpParagraph( + paragraph, + modifier = Modifier.padding(12.dp), + highlighted = true, + ) + } + } else { + SettingsHelpParagraph( + paragraph, + highlighted = false, + ) + } + } + if (secondaryActionLabel != null && onSecondaryAction != null) { + Box(modifier = Modifier.fillMaxWidth()) { + OutlinedButton( + onClick = onSecondaryAction, + enabled = secondaryActionEnabled, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), + ) { + FlexibleButtonText(secondaryActionLabel) + } + if (!secondaryActionEnabled && onSecondaryActionDisabled != null) { + Box( + modifier = Modifier + .matchParentSize() + .remoteFocusOutline(RoundedCornerShape(16.dp)) + .clickable(onClick = onSecondaryActionDisabled), + ) } } } @@ -4810,97 +4721,44 @@ private fun PowerHelpDialog( profileMaxWorkers: Int, onDismiss: () -> Unit ) { - val television = isTelevisionDevice() - val scrollState = rememberScrollState() - Dialog( - onDismissRequest = onDismiss, - properties = DialogProperties(usePlatformDefaultWidth = !television), + SettingsDialogLayout( + title = "Мощность", + onDismiss = onDismiss, ) { - BoxWithConstraints( - modifier = Modifier.fillMaxSize().padding(8.dp), - contentAlignment = Alignment.Center - ) { - Surface( - modifier = Modifier - .televisionDialogWidth(television) - .heightIn(max = maxHeight * 0.92f), - shape = RoundedCornerShape(24.dp), - color = MaterialTheme.colorScheme.surface, - contentColor = MaterialTheme.colorScheme.onSurface, - tonalElevation = 8.dp - ) { - Column( - modifier = Modifier - .padding(22.dp) - .fillMaxWidth() - .verticalScroll(scrollState) - .tvDpadScrollable(scrollState, television), - verticalArrangement = Arrangement.spacedBy(12.dp) - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - "Мощность", - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary - ) - IconButton( - onClick = onDismiss, - modifier = Modifier.remoteIconButtonFocus(), - ) { - Icon(Icons.Default.Close, contentDescription = "Закрыть") - } - } - Text( - "Мощность задаёт количество параллельных рабочих потоков TURN/DTLS для VK-звонка. Чем выше значение, тем больше каналов приложение пытается держать одновременно.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - "На что влияет: устойчивость при потерях сети, скорость восстановления, расход батареи, нагрев, нагрузка на сервер и вероятность чаще упираться в ограничения или капчу VK.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - "Ориентир: 9-18 для экономного режима, 18-36 обычно достаточно, выше 36 имеет смысл только если сеть нестабильная, сервер справляется и капча не мешает.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - if (profileMaxWorkers >= WORKERS_PER_GROUP) { - Text( - "Владелец этого профиля установил предел $profileMaxWorkers потоков с учётом возможностей сервера. Приложение не позволит выбрать больше для этого профиля. Ограничение не действует на другие самостоятельно настроенные профили.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.primary, - fontWeight = FontWeight.SemiBold - ) - } - Text( - "Сейчас: $currentWorkers. Доступный диапазон для текущего числа VK-хешей: $minWorkers-$maxWorkers.", - style = MaterialTheme.typography.bodySmall, - fontWeight = FontWeight.SemiBold, - color = MaterialTheme.colorScheme.onSurface - ) - Button( - onClick = onDismiss, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) - ) { - FlexibleButtonText("Понятно", fontWeight = FontWeight.Bold) - } - Spacer(Modifier.height(4.dp)) - } - } + Text( + "Мощность задаёт количество параллельных рабочих потоков TURN/DTLS для ВК-звонка. Чем выше значение, тем больше каналов приложение пытается держать одновременно.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + "На что влияет: устойчивость при потерях сети, скорость восстановления, расход батареи, нагрев, нагрузка на сервер и вероятность чаще упираться в ограничения или капчу ВК.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + "Ориентир: 9-18 для экономного режима, 18-36 обычно достаточно, выше 36 имеет смысл только если сеть нестабильная, сервер справляется и капча не мешает.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + if (profileMaxWorkers >= WORKERS_PER_GROUP) { + Text( + "Владелец этого профиля установил предел $profileMaxWorkers потоков с учётом возможностей сервера. Приложение не позволит выбрать больше для этого профиля. Ограничение не действует на другие самостоятельно настроенные профили.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.SemiBold + ) } + Text( + "Сейчас: $currentWorkers. Доступный диапазон для текущего числа ВК-хешей: $minWorkers-$maxWorkers.", + style = MaterialTheme.typography.bodySmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) } } @Composable -private fun FlexibleButtonText( +internal fun FlexibleButtonText( text: String, fontWeight: FontWeight = FontWeight.SemiBold, color: Color = LocalContentColor.current @@ -5116,89 +4974,35 @@ internal fun steppedSliderValue( // ═══ Important Info Dialog ═══ @Composable fun ImportantInfoDialog(onDismiss: () -> Unit) { - val television = isTelevisionDevice() - val scrollState = rememberScrollState() - Dialog( - onDismissRequest = onDismiss, - properties = DialogProperties(usePlatformDefaultWidth = false) - ) { - BoxWithConstraints( - modifier = Modifier.fillMaxSize().padding(8.dp), - contentAlignment = Alignment.Center - ) { - Surface( - modifier = (if (television) { - Modifier.televisionDialogWidth(television) - } else { - Modifier.fillMaxWidth(0.95f) - }) - .heightIn(max = maxHeight * 0.92f), - shape = RoundedCornerShape(24.dp), - color = MaterialTheme.colorScheme.surface, - contentColor = MaterialTheme.colorScheme.onSurface, - tonalElevation = 6.dp, - ) { - Column( - modifier = Modifier - .padding(24.dp) - .verticalScroll(scrollState) - .tvDpadScrollable(scrollState, television) - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text("Важная информация", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) - IconButton( - onClick = onDismiss, - modifier = Modifier.remoteIconButtonFocus(), - ) { - Icon(Icons.Default.Close, null) - } - } - - Spacer(Modifier.height(16.dp)) - - InfoSection( - "Профили подключения", - "В боковых настройках доступны три профиля. Короткое нажатие выбирает профиль и закрывает настройки, долгое открывает переименование и полную локальную очистку профиля." - ) - InfoSection( - "VK-хеши", - "VK-хеш нужен для работы туннеля. В настройке VK-хешей можно проверить каждый слот, скопировать отдельный хеш или все заполненные хеши сразу." - ) - InfoSection( - "Клиенты и сервер", - "В режиме «Я — админ» блок «Деплой» → «Клиенты и сервер» управляет клиентами без Telegram-бота: создание, продление, отключение, смена пароля, экспорт и импорт отдельного клиента." - ) - InfoSection( - "Передача подключения", - "Обычное подключение передаётся через «Настройки» → «Получить или передать». Перенос отдельного клиента выполняется именно в блоке «Клиенты и сервер»." - ) - InfoSection( - "После новых серверных функций", - "Если приложение пишет, что сервер не поддерживает действие, выполните во вкладке «Деплой» установку сервера с сохранением данных." - ) - InfoSection( - "Капча и мощность", - "Сначала работает быстрый VKCalls без капчи; авторешение подключается только для резервного способа. Несколько VK-хешей распределяют нагрузку, а мощность лучше держать умеренной: чем она выше, тем больше расход батареи и шанс чаще видеть капчу." - ) - - Spacer(Modifier.height(20.dp)) - Button( - onClick = onDismiss, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), - colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary) - ) { - FlexibleButtonText("Понятно") - } - Spacer(Modifier.height(4.dp)) - } - } - } + SettingsDialogLayout(title = "Справка", onDismiss = onDismiss) { + InfoSection( + "Туннель", + "VPN подключает приложения с учётом исключений. Прокси используют приложения, в которых настроен его адрес." + ) + InfoSection( + "Подключение", + "UDP выбран по умолчанию: сначала UDP, затем резервные способы. TCP/TLS подходит для сетей с ограничением UDP. Оба режима восстанавливают потерянные каналы." + ) + InfoSection( + "Параметры", + "DNS, режим подключения, мощность и капча — в параметрах туннеля. Начните с умеренной мощности; увеличение повышает расход батареи. ВК-хеши проверяются отдельно в настройках." + ) + InfoSection( + "Деплой", + "«Установить» — первая установка или обновление. На заполненном профиле «Обновить сервер» сразу проверяет VPS; «Изменить настройки» открывает мастер. «Подключить» читает готовый сервер без изменений на нём. После первой установки SSH и параметры сохранены, пустой «Туннель» подготовлен для ручного подключения — добавьте ВК-хеши. SSH и параметры — по значкам ключа и шестерёнки." + ) + InfoSection( + "Клиенты и сервер", + "В режиме «Я — админ» можно управлять доступом клиентов. Если сервер не поддерживает действие, обновите его через «Установить» с сохранением данных." + ) + InfoSection( + "Профили и перенос", + "Профиль выбирается в настройках; долгое нажатие открывает переименование и очистку. Для переноса откройте «Получить или передать» и следуйте подсказкам выбранного профиля." + ) + InfoSection( + "Если возникла проблема", + "Проверьте устройство в «Инфо → Действия», сервер — по лупе в «Деплой». Перед обращением включите запись в «Логи», повторите проблему и приложите журнал и нужный отчёт." + ) } } @@ -5283,6 +5087,31 @@ internal enum class BulkVkHashPasteMode { ReplaceAll } +internal const val VK_HASH_AUTO_HELP_TEXT = + "Войдите в ВК и подтвердите доступ, если потребуется. Если вход уже сохранён, " + + "проверьте имя аккаунта и нажмите «Продолжить». Для смены аккаунта выберите «Выйти из ВК».\n\n" + + "WDTT Plus получит четыре ВК-хеша и сохранит их в выбранном профиле. " + + "Дождитесь сообщения о завершении — заполнять поля вручную не нужно." + +internal fun localizeVkUiText(value: String): String { + return value + .replace("ВКонтакте", "ВК") + .replace(Regex("(? "Получение ВК-хешей…" + canRestore && canAcquire -> "Получить или вернуть ВК-хеши" + canRestore -> "Вернуть ВК-хеши" + canAcquire && hasCompleteHashes -> "Получить новые ВК-хеши" + else -> "Получить ВК-хеши" +} + internal data class BulkVkHashPasteResult( val slots: List, val insertedCount: Int, @@ -5387,6 +5216,7 @@ private fun Int.hashPlural(): String { @Composable private fun CompactTunnelProfileCard( + modifier: Modifier = Modifier, hasConnection: Boolean, connectionMethod: String, savedConnectionMethod: String, @@ -5422,7 +5252,7 @@ private fun CompactTunnelProfileCard( ).size.width.toDp() } AppSectionCard( - modifier = Modifier.alpha(if (enabled) 1f else 0.55f), + modifier = modifier.alpha(if (enabled) 1f else 0.55f), containerColor = if (needsAttention) { MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.24f) } else null, @@ -5552,7 +5382,7 @@ private fun UserManualConnectionDialog( ).all { it != null && it in 1..65535 } val canSave = isValidTunnelHost(peer) && passwordValid && portsValid - Dialog( + BoundedAppDialog( onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false) ) { @@ -5758,7 +5588,7 @@ private fun UserWdttLinkDialog( val invalid = linkText.isNotBlank() && parsed == null && !remoteDocument - Dialog( + BoundedAppDialog( onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false) ) { @@ -5786,31 +5616,23 @@ private fun UserWdttLinkDialog( horizontalArrangement = Arrangement.spacedBy(8.dp) ) { Column(modifier = Modifier.weight(1f)) { - Text( - title, - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary - ) - if (subtitle.isNotBlank()) { - Text( - subtitle, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) + Row(verticalAlignment = Alignment.CenterVertically) { + Text(title, style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary, + modifier = Modifier.weight(1f, fill = false)) + if (remoteUpdateOnly) { + HintIconButton(hint = "Как обновить маршрут", onClick = { showRemoteUpdateHelp = true }, + modifier = Modifier.size(40.dp).remoteHelpFocus()) { + Icon(Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Как обновить маршрут", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp)) + } + } } - } - if (remoteUpdateOnly) { - IconButton( - onClick = { showRemoteUpdateHelp = true }, - modifier = Modifier.size(40.dp).remoteHelpFocus(), - ) { - Icon( - Icons.AutoMirrored.Filled.HelpOutline, - contentDescription = "Как обновить маршрут", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(22.dp), - ) + if (subtitle.isNotBlank()) { + Text(subtitle, style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) } } IconButton(onClick = onDismiss) { @@ -5889,7 +5711,7 @@ private fun UserWdttLinkDialog( "Вставьте короткую HTTPS-ссылку обновления." parsed == null -> validation.userMessage() validation.canStartVpn -> "Ссылка распознана и готова к подключению." - else -> "Ссылка распознана. VK-хеши можно добавить после сохранения." + else -> "Ссылка распознана. ВК-хеши можно добавить после сохранения." }, color = if (invalid) { MaterialTheme.colorScheme.error @@ -5953,7 +5775,7 @@ private fun RemoteUpdateHelpDialog( ) { val television = isTelevisionDevice() val scrollState = rememberScrollState() - Dialog( + BoundedAppDialog( onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false), ) { @@ -6056,7 +5878,7 @@ private fun ManagedHashStatusCard(lifecycle: AccessLifecycleUiState) { modifier = Modifier.size(21.dp), ) Text( - lifecycle.title.ifBlank { "Автоматическое получение VK-хешей" }, + localizeVkUiText(lifecycle.title.ifBlank { "Автоматическое получение ВК-хешей" }), modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold, @@ -6250,7 +6072,7 @@ private fun DismissedNoticeCard( } // ═══ Модальное окно хешей ═══ -@OptIn(ExperimentalMaterial3Api::class) +@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class) @Composable fun HashesDialog( settingsStore: SettingsStore, @@ -6284,16 +6106,22 @@ fun HashesDialog( var checkJob by remember { mutableStateOf(null) } var isRemoteActionRunning by remember { mutableStateOf(false) } var remoteActionJob by remember { mutableStateOf(null) } + var isRestoreRunning by remember { mutableStateOf(false) } + var restoreJob by remember { mutableStateOf(null) } + var restoreCapability by remember(profileIndex) { + mutableStateOf(RemoteAccessCapability.Unavailable) + } var remoteActionMessage by rememberSaveable { mutableStateOf(null) } var remoteActionHasError by rememberSaveable { mutableStateOf(false) } var bulkPasteMessage by rememberSaveable { mutableStateOf(null) } var bulkPasteHasError by rememberSaveable { mutableStateOf(false) } var pendingBulkPasteHashes by remember { mutableStateOf(null) } - var showRemoteActionInfo by rememberSaveable { mutableStateOf(false) } var showHashesHelp by rememberSaveable { mutableStateOf(false) } + var showAcquisitionDialog by rememberSaveable { mutableStateOf(false) } var checkResults by remember { mutableStateOf>(emptyMap()) } var detailSlot by remember { mutableStateOf(null) } val dialogScrollState = rememberScrollState() + val snackbarHostState = remember { SnackbarHostState() } val currentHashes = remember(h1, h2, h3, h4) { listOf(h1, h2, h3, h4).map { stripVkUrlStatic(it) } } @@ -6307,26 +6135,49 @@ fun HashesDialog( if (VkJoinLink.isValidHash(hash)) index + 1 to hash else null } } + LaunchedEffect(profileIndex, remoteAccessLifecycle.checkedAtMillis) { + if (remoteAccessLifecycle.managed) { + AccessLifecycleCoordinator.refreshProfile( + context = context, + profileIndex = profileIndex, + force = false, + ) + } + restoreCapability = settingsStore + .accessLifecycleForProfile(profileIndex) + .capability + } val dialogHashErrors = remember(currentHashes) { buildList { currentHashes.forEachIndexed { index, hash -> if (hash.isNotBlank() && !VkJoinLink.isValidHash(hash)) { - add("VK Хеш ${index + 1} имеет неверный формат") + add("ВК-хеш ${index + 1} имеет неверный формат") } } val filled = currentHashes.filter(VkJoinLink::isValidHash) - if (filled.size != filled.distinct().size) add("Есть дубликаты VK-хешей") + if (filled.size != filled.distinct().size) add("Есть дубликаты ВК-хешей") } } val canSaveHashes = dialogHashErrors.isEmpty() val completedChecks = checkResults.values.count { it.status !in setOf("pending", "checking", "solving_captcha") } val currentCheckSlot = checkResults.entries.firstOrNull { it.value.status in setOf("checking", "solving_captcha") }?.key val detailResult = detailSlot?.let { slot -> checkResults[slot]?.let { slot to it } } + val acquisitionScrollState = rememberScrollState() + fun showNotice(message: String) { + scope.launch { + snackbarHostState.currentSnackbarData?.dismiss() + snackbarHostState.showSnackbar( + message = localizeVkUiText(message), + duration = SnackbarDuration.Short, + ) + } + } fun cancelHashCheck(updateUi: Boolean = true) { - checkJob?.cancel(CancellationException("Hash check cancelled by user")) + val runningJob = checkJob + val wasRunning = isChecking || runningJob?.isActive == true checkJob = null - ManlCaptchaWebViewManager.cancelCaptcha() - if (updateUi) { + runningJob?.cancel() + if (updateUi && wasRunning) { isChecking = false val activeSlots = checkResults.filterValues { it.status in setOf("pending", "checking", "solving_captcha") } if (activeSlots.isNotEmpty()) { @@ -6334,6 +6185,7 @@ fun HashesDialog( result.copy(status = "cancelled", message = "Проверка остановлена пользователем") } } + showNotice("Проверка ВК-хешей остановлена.") } } fun cancelRemoteAction(updateUi: Boolean = true) { @@ -6404,46 +6256,82 @@ fun HashesDialog( ?.takeIf { it.isNotBlank() } ?: "Подготавливаю переход..." try { - if ( - TunnelManager.running.value || - TunnelManager.transition.value != TunnelTransition.IDLE - ) { - remoteActionMessage = remoteAction?.stoppingMessage + val activity = mainActivityFrom(context) + val deviceId = settingsStore.getOrCreateConnectDeviceId() + val localDocument = settingsStore.remoteActionProfileDocument(profileIndex) + if (LocalContinuationExtensions.available && activity != null) { + remoteActionMessage = "Связываемся с WDTT Plus через ещё работающее соединение..." + val target = RemoteContinuationLauncher.begin( + context = context, + capability = remoteContinuation, + device = deviceId, + localDocument = localDocument, + ) + val hasCompleteLocalValues = VkJoinLink.hasCompleteHashSet( + currentHashes.joinToString(","), + ) + val progress: (String) -> Unit = { message -> + remoteActionMessage = message + } + val documentUri = LocalContinuationExtensions.execute( + activity = activity, + target = target.copy(localProfile = settingsStore.localContinuationProfile(profileIndex)), + deviceId = deviceId, + hasCompleteLocalValues = hasCompleteLocalValues, + onProgress = progress, + ) + activity.acceptLocalContinuationDocument(documentUri) + remoteActionMessage = "Хеши получены. Обновляем профиль..." + onDismiss() + } else { + // Preserve the legacy stop-first behavior exactly; only the + // privately selected in-app build uses split destination routing. + if ( + TunnelManager.running.value || + TunnelManager.transition.value != TunnelTransition.IDLE + ) { + remoteActionMessage = remoteAction?.stoppingMessage + ?.takeIf { it.isNotBlank() } + ?: "Останавливаю соединение перед продолжением..." + } + val stopResult = TunnelStopCoordinator.stopAndAwait(context) + if (!stopResult.succeeded) { + throw IllegalStateException( + if (stopResult == TunnelStopResult.TIMED_OUT) { + "Соединение не остановилось за 20 секунд. Повторите попытку." + } else { + "Не удалось запросить остановку соединения. Остановите его и повторите попытку." + } + ) + } + if (stopResult == TunnelStopResult.STOPPED) { + delay(TunnelStopCoordinator.DIRECT_NETWORK_SETTLE_MS) + } + remoteActionMessage = remoteAction?.openingMessage ?.takeIf { it.isNotBlank() } - ?: "Останавливаю соединение перед продолжением..." - } - val stopResult = TunnelStopCoordinator.stopAndAwait(context) - if (!stopResult.succeeded) { - throw IllegalStateException( - if (stopResult == TunnelStopResult.TIMED_OUT) { - "Соединение не остановилось за 20 секунд. Повторите попытку." - } else { - "Не удалось запросить остановку соединения. Остановите его и повторите попытку." - } + ?: "Открываю продолжение..." + val target = RemoteContinuationLauncher.begin( + context = context, + capability = remoteContinuation, + device = deviceId, + localDocument = localDocument, ) + try { + launchRemoteTarget(context, target) + } catch (error: Exception) { + throw IllegalStateException( + error.message + ?: "Не удалось открыть страницу. Проверьте доступные приложения и браузер." + ) + } + remoteActionMessage = remoteAction?.successMessage + ?.takeIf { it.isNotBlank() } + ?: "Страница открыта. Завершите действие и вернитесь в WDTT Plus." } - if (stopResult == TunnelStopResult.STOPPED) { - delay(TunnelStopCoordinator.DIRECT_NETWORK_SETTLE_MS) - } - remoteActionMessage = remoteAction?.openingMessage + } catch (_: LocalContinuationCancelledException) { + remoteActionMessage = remoteAction?.cancelledMessage ?.takeIf { it.isNotBlank() } - ?: "Открываю продолжение..." - val target = RemoteContinuationLauncher.begin( - capability = remoteContinuation, - device = settingsStore.getOrCreateConnectDeviceId(), - localDocument = settingsStore.remoteActionProfileDocument(profileIndex), - ) - try { - launchRemoteTarget(context, target) - } catch (error: Exception) { - throw IllegalStateException( - error.message - ?: "Не удалось открыть страницу. Проверьте доступные приложения и браузер." - ) - } - remoteActionMessage = remoteAction?.successMessage - ?.takeIf { it.isNotBlank() } - ?: "Страница открыта. Завершите действие и вернитесь в WDTT Plus." + ?: "Действие остановлено." } catch (cancelled: CancellationException) { remoteActionMessage = remoteAction?.cancelledMessage ?.takeIf { it.isNotBlank() } @@ -6463,6 +6351,64 @@ fun HashesDialog( } } } + fun restoreSavedProfileValues() { + if (isRestoreRunning) return + cancelHashCheck() + val expected = restoreCapability + if (!expected.available || !expected.exchange.actionAvailable) { + remoteActionHasError = true + remoteActionMessage = "Сохранённые данные для этого профиля сейчас недоступны." + return + } + restoreJob?.cancel() + restoreJob = scope.launch { + val runningJob = coroutineContext[Job] + isRestoreRunning = true + remoteActionHasError = false + remoteActionMessage = expected.exchange.message.ifBlank { + "Получаем сохранённые данные профиля…" + } + try { + AccessLifecycleCoordinator.restoreProfileValues( + context = context, + profileIndex = profileIndex, + expectedCapability = expected, + ) + val restored = settingsStore.tunnelProfileSnapshot(profileIndex) + .vkHashes + .split(',') + .map(VkJoinLink::extractHash) + .filter(VkJoinLink::isValidHash) + .distinct() + .take(4) + h1 = restored.getOrElse(0) { "" } + h2 = restored.getOrElse(1) { "" } + h3 = restored.getOrElse(2) { "" } + h4 = restored.getOrElse(3) { "" } + restoreCapability = settingsStore + .accessLifecycleForProfile(profileIndex) + .capability + remoteActionMessage = "Сохранённые данные добавлены в профиль." + } catch (_: CancellationException) { + // Closing the dialog cancels the request. It must not escape from + // the UI scope or be presented as a failed restore operation. + } catch (error: Exception) { + remoteActionHasError = true + remoteActionMessage = error.message + ?: "Не удалось получить сохранённые данные профиля." + TunnelManager.noteAccessLifecycleEvent( + key = "profile_values_restore_$profileIndex", + message = remoteActionMessage.orEmpty(), + warning = true, + ) + } finally { + if (restoreJob === runningJob) { + isRestoreRunning = false + restoreJob = null + } + } + } + } fun pasteHashesFromClipboard() { val clipboard = context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager val raw = clipboard.primaryClip @@ -6474,7 +6420,7 @@ fun HashesDialog( val hashes = parseBulkVkHashes(raw) if (hashes.isEmpty()) { bulkPasteHasError = true - bulkPasteMessage = "В буфере обмена не нашёл VK-хеши или ссылки VK Звонков." + bulkPasteMessage = "В буфере обмена не нашёл ВК-хеши или ссылки ВК Звонков." return } val hasExistingHashes = listOf(h1, h2, h3, h4) @@ -6486,9 +6432,60 @@ fun HashesDialog( applyBulkHashes(hashes, BulkVkHashPasteMode.ReplaceAll) } } + fun startHashCheck() { + if (isChecking) return + if (checkableHashes.isEmpty()) { + showNotice("Сначала заполните хотя бы один ВК-хеш.") + return + } + checkJob?.cancel() + checkJob = scope.launch { + val runningJob = coroutineContext[Job] + isChecking = true + checkResults = checkableHashes.associate { (slot, hash) -> + slot to HashCheckResult(hash = hash, status = "pending", message = "Ожидает проверки") + } + try { + val finalResults = checkVkHashes( + context = context, + hashes = checkableHashes, + fingerprint = activeFingerprint, + clientIds = activeClientIds, + customVkCredentialsEnabled = customVkCredentialsEnabled, + customVkClientId = customVkClientId, + customVkClientSecret = customVkClientSecret, + vkCallsPreflight = vkCallsPreflight, + captchaMode = captchaMode, + selectedWebViewManual = selectedWebViewManual, + onUpdate = { slot, result -> + checkResults = checkResults + (slot to result) + }, + ) + checkResults = checkResults + finalResults + val available = finalResults.values.count { it.status == "ok" } + showNotice("Проверка завершена: доступно $available из ${finalResults.size}.") + } catch (_: CancellationException) { + // cancelHashCheck already updates the visible state immediately. + // Cancellation is an expected control-flow event, not an error. + } catch (error: Exception) { + val message = error.message ?: "Не удалось выполнить проверку" + checkResults = checkResults + checkableHashes.associate { (slot, hash) -> + slot to HashCheckResult(hash = hash, status = "error", message = message) + } + showNotice("Не удалось проверить ВК-хеши: $message") + } finally { + if (checkJob === runningJob) { + isChecking = false + checkJob = null + } + } + } + } fun closeDialog() { - cancelHashCheck() + cancelHashCheck(updateUi = false) cancelRemoteAction(updateUi = false) + restoreJob?.cancel() + restoreJob = null onDismiss() } @@ -6496,13 +6493,30 @@ fun HashesDialog( onDispose { cancelHashCheck(updateUi = false) cancelRemoteAction(updateUi = false) + restoreJob?.cancel() + restoreJob = null + } + } + + LaunchedEffect(remoteActionMessage, isRemoteActionRunning, showAcquisitionDialog) { + val message = remoteActionMessage + if (!isRemoteActionRunning && !showAcquisitionDialog && !message.isNullOrBlank()) { + snackbarHostState.currentSnackbarData?.dismiss() + snackbarHostState.showSnackbar(localizeVkUiText(message), duration = SnackbarDuration.Short) + } + } + LaunchedEffect(bulkPasteMessage) { + val message = bulkPasteMessage + if (!message.isNullOrBlank()) { + snackbarHostState.currentSnackbarData?.dismiss() + snackbarHostState.showSnackbar(localizeVkUiText(message), duration = SnackbarDuration.Short) } } detailResult?.let { (slot, result) -> - AlertDialog( + BoundedAlertDialog( onDismissRequest = { detailSlot = null }, - title = { Text("VK Хеш $slot: ${hashStatusLabel(result.status)}") }, + title = { Text("ВК-хеш $slot: ${hashStatusLabel(result.status)}") }, text = { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text(result.message) @@ -6524,62 +6538,11 @@ fun HashesDialog( ) } - if (showRemoteActionInfo) { - AlertDialog( - onDismissRequest = { showRemoteActionInfo = false }, - title = { - Text( - remoteAction?.confirmationTitle - ?.takeIf { it.isNotBlank() } - ?: remoteAction?.title?.takeIf { it.isNotBlank() } - ?: "Получение VK-хешей", - ) - }, - text = { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - ( - remoteAction?.confirmationMessage - ?.takeIf { it.isNotBlank() } - ?: remoteAction?.message?.takeIf { it.isNotBlank() } - ?: "Продолжите действие на открывшейся странице." - ) - .split("\n\n") - .filter { it.isNotBlank() } - .forEach { paragraph -> Text(paragraph) } - } - }, - confirmButton = { - TextButton( - onClick = { - showRemoteActionInfo = false - startRemoteAction() - }, - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) - ) { - FlexibleButtonText( - remoteAction?.confirmationLabel - ?.takeIf { it.isNotBlank() } - ?: remoteAction?.label?.takeIf { it.isNotBlank() } - ?: "Получить 4 хеша через VK", - ) - } - }, - dismissButton = { - TextButton( - onClick = { showRemoteActionInfo = false }, - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) - ) { - FlexibleButtonText("Отмена") - } - } - ) - } - pendingBulkPasteHashes?.let { pending -> val hashes = pending.hashes val titleText = "Вставить хеши из буфера?" val sourceText = "В буфере найдено" - AlertDialog( + BoundedAlertDialog( onDismissRequest = { pendingBulkPasteHashes = null }, title = { Row( @@ -6645,7 +6608,160 @@ fun HashesDialog( ) } - Dialog( + if (showAcquisitionDialog) { + val showManagedStatus = shouldShowManagedHashStatusCard( + continuationAvailable = remoteContinuation.available, + lifecycle = remoteAccessLifecycle, + ) + BoundedAlertDialog( + scrollableText = false, + onDismissRequest = { + if (!isRemoteActionRunning && !isRestoreRunning) showAcquisitionDialog = false + }, + title = { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + Icons.Default.Key, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + ) + Spacer(Modifier.width(8.dp)) + Text( + "Получение ВК-хешей", + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + ) + IconButton( + onClick = { showAcquisitionDialog = false }, + enabled = !isRemoteActionRunning && !isRestoreRunning, + modifier = Modifier.size(44.dp), + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.78f), + modifier = Modifier.size(34.dp), + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + Icons.Default.Close, + contentDescription = "Закрыть", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp), + ) + } + } + } + } + }, + text = { + Column( + modifier = Modifier.verticalScroll(acquisitionScrollState), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text( + "Выберите подходящее действие. Вход ВК сохраняется в защищённом хранилище приложения.", + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + if (restoreCapability.exchange.actionAvailable) { + HashAcquisitionOptionCard( + title = "Сохранённые ВК-хеши", + description = localizeVkUiText( + restoreCapability.exchange.message.ifBlank { + "В профиле есть ранее сохранённые ВК-хеши. Их можно вернуть без нового входа в ВК." + }, + ), + buttonText = "Вернуть сохранённые ВК-хеши", + icon = Icons.Default.Cloud, + busy = isRestoreRunning, + enabled = !isChecking && !isRemoteActionRunning && !isRestoreRunning, + onClick = { restoreSavedProfileValues() }, + ) + } + + if (remoteContinuation.available) { + val hasCompleteHashes = VkJoinLink.hasCompleteHashSet(currentHashes.joinToString(",")) + HashAcquisitionOptionCard( + title = if (hasCompleteHashes) "Новые ВК-хеши" else "ВК-хеши из ВК", + description = if (hasCompleteHashes) { + "Новое получение заменит четыре ВК-хеша текущего профиля. Перед созданием ссылок приложение попросит подтверждение." + } else { + "При необходимости войдите в ВК или подтвердите сохранённый аккаунт. Четыре ВК-хеша будут получены и сохранены в этом профиле." + }, + buttonText = if (hasCompleteHashes) { + "Получить новые ВК-хеши" + } else { + "Получить ВК-хеши" + }, + icon = Icons.Default.Key, + busy = isRemoteActionRunning, + enabled = !isChecking && !isRemoteActionRunning && !isRestoreRunning, + onClick = { startRemoteAction() }, + ) + } else if (showManagedStatus) { + ManagedHashStatusCard(remoteAccessLifecycle) + } else if (remoteAction != null) { + RemoteActionCard( + action = remoteAction, + onLinkClick = { + showAcquisitionDialog = false + closeDialog() + onOpenProjectSupport() + }, + onClick = { + scope.launch { + val opened = RemoteUiActionLauncher.open(context, remoteAction) + if (!opened) showNotice("Не удалось открыть страницу. Проверьте браузер.") + } + }, + ) + } + + remoteActionMessage?.takeIf { it.isNotBlank() }?.let { message -> + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = if (remoteActionHasError) { + MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.72f) + } else { + MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f) + }, + ) { + Text( + localizeVkUiText(message), + modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp), + style = MaterialTheme.typography.bodySmall, + ) + } + } + + if (isRemoteActionRunning) { + TextButton( + onClick = { cancelRemoteAction() }, + modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), + ) { + Icon(Icons.Default.Stop, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + FlexibleButtonText("Остановить", color = MaterialTheme.colorScheme.error) + } + } + + Text( + "Для создания ссылок нужна краткая защищённая связь с WDTT Plus. Если она временно недоступна, вход ВК останется сохранён — действие можно продолжить позже без повторной авторизации.", + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + confirmButton = {}, + ) + } + + BoundedAppDialog( onDismissRequest = { closeDialog() }, properties = DialogProperties(usePlatformDefaultWidth = false) ) { @@ -6665,67 +6781,64 @@ fun HashesDialog( .widthIn(max = 720.dp) .heightIn(max = maxHeight * 0.92f) ) { - Column( - modifier = Modifier - .padding(24.dp) - .fillMaxWidth() - .verticalScroll(dialogScrollState), - verticalArrangement = Arrangement.spacedBy(12.dp) - ) { + Box { + Column( + modifier = Modifier + .padding(24.dp) + .fillMaxWidth() + .verticalScroll(dialogScrollState), + verticalArrangement = Arrangement.spacedBy(9.dp) + ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { - Row(verticalAlignment = Alignment.CenterVertically) { + Row( + modifier = Modifier.weight(1f), + verticalAlignment = Alignment.CenterVertically, + ) { Icon(Icons.Default.Tag, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(24.dp)) Spacer(Modifier.width(8.dp)) - Text("VK Хеши", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + Text("ВК-хеши", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) Spacer(Modifier.width(4.dp)) - IconButton( + HintIconButton(hint = "Как получить ВК-хеши", onClick = { showHashesHelp = true }, - modifier = Modifier.size(36.dp).remoteHelpFocus() + modifier = Modifier.size(36.dp).remoteHelpFocus(), ) { - Surface( - shape = CircleShape, - color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.72f), - modifier = Modifier.size(28.dp) - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - Icons.AutoMirrored.Filled.HelpOutline, - contentDescription = "Как получить VK-хеши", - tint = MaterialTheme.colorScheme.onPrimaryContainer, - modifier = Modifier.size(18.dp) - ) - } - } + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Как получить ВК-хеши", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp), + ) } + CheckActionIcon( + checking = isChecking, + idleIcon = Icons.Default.Refresh, + description = "Проверить ВК-хеши", + cancelDescription = "Остановить проверку ВК-хешей", + onClick = { if (isChecking) cancelHashCheck() else startHashCheck() }, + onLongClick = { + showNotice(if (isChecking) { + "Нажмите, чтобы остановить проверку ВК-хешей." + } else { + "Проверить доступность заполненных ВК-хешей." + }) + }, + ) } IconButton( onClick = { closeDialog() }, - modifier = Modifier.size(44.dp) + modifier = Modifier.size(44.dp), ) { - Surface( - shape = CircleShape, - color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.78f), - modifier = Modifier.size(34.dp) - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - Icons.Default.Close, - contentDescription = "Закрыть", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(22.dp) - ) - } - } + Icon(Icons.Default.Close, contentDescription = "Закрыть") } } Text( text = if (isChecking) { - val current = currentCheckSlot?.let { " Сейчас: VK Хеш $it." } ?: "" + val current = currentCheckSlot?.let { " Сейчас: ВК-хеш $it." } ?: "" "Проверено $completedChecks из ${checkableHashes.size}.$current" } else if (isRemoteActionRunning) { remoteActionMessage @@ -6739,69 +6852,39 @@ fun HashesDialog( modifier = Modifier.padding(bottom = 4.dp) ) - remoteActionMessage?.takeIf { it.isNotBlank() && !isRemoteActionRunning }?.let { message -> - Surface( - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - color = if (remoteActionHasError) { - MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.72f) - } else { - MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f) - }, - contentColor = if (remoteActionHasError) { - MaterialTheme.colorScheme.onErrorContainer - } else { - MaterialTheme.colorScheme.onSecondaryContainer - } - ) { - Text( - text = message, - modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp), - style = MaterialTheme.typography.bodySmall - ) - } - } - - OutlinedButton( - onClick = { pasteHashesFromClipboard() }, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - enabled = !isChecking && !isRemoteActionRunning, - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - FlexibleButtonText("Вставить хеши из буфера", fontWeight = FontWeight.SemiBold) - } - - bulkPasteMessage?.takeIf { it.isNotBlank() }?.let { message -> - Surface( - modifier = Modifier.fillMaxWidth(), + OutlinedButton( + onClick = { pasteHashesFromClipboard() }, + modifier = Modifier.weight(1f).heightIn(min = 44.dp), shape = RoundedCornerShape(14.dp), - color = if (bulkPasteHasError) { - MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.62f) - } else { - MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f) - }, - contentColor = if (bulkPasteHasError) { - MaterialTheme.colorScheme.onErrorContainer - } else { - MaterialTheme.colorScheme.onSecondaryContainer - } + enabled = !isChecking && !isRemoteActionRunning && !isRestoreRunning, + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 7.dp), ) { - Text( - text = message, - modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp), - style = MaterialTheme.typography.bodySmall - ) + Icon(Icons.Default.ContentPaste, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(5.dp)) + FlexibleButtonText("Вставить", fontWeight = FontWeight.SemiBold) + } + OutlinedButton( + onClick = { copyVkHashesToClipboard(context, "ВК-хеши WDTT Plus", copiedHashesText) }, + modifier = Modifier.weight(1f).heightIn(min = 44.dp), + shape = RoundedCornerShape(14.dp), + enabled = copiedHashesText.isNotBlank(), + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 7.dp), + ) { + Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(5.dp)) + FlexibleButtonText("Копировать", fontWeight = FontWeight.SemiBold) } } listOf( - Triple("VK Хеш 1", h1) { v: String -> h1 = v }, - Triple("VK Хеш 2", h2) { v: String -> h2 = v }, - Triple("VK Хеш 3", h3) { v: String -> h3 = v }, - Triple("VK Хеш 4", h4) { v: String -> h4 = v } + Triple("ВК-хеш 1", h1) { v: String -> h1 = v }, + Triple("ВК-хеш 2", h2) { v: String -> h2 = v }, + Triple("ВК-хеш 3", h3) { v: String -> h3 = v }, + Triple("ВК-хеш 4", h4) { v: String -> h4 = v } ).forEachIndexed { idx, (label, value, onChange) -> val slot = idx + 1 val cleanedValue = stripVkUrlStatic(value) @@ -6816,7 +6899,7 @@ fun HashesDialog( result = checkResults[slot], onInfoClick = { detailSlot = slot }, canCopy = cleanedValue.isNotBlank(), - onCopyClick = { copyVkHashesToClipboard(context, "VK Хеш $slot", cleanedValue) }, + onCopyClick = { copyVkHashesToClipboard(context, "ВК-хеш $slot", cleanedValue) }, canClear = value.isNotBlank(), onClearClick = { onChange("") @@ -6825,157 +6908,42 @@ fun HashesDialog( ) } - OutlinedButton( - onClick = { copyVkHashesToClipboard(context, "VK Хеши WDTT Plus", copiedHashesText) }, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - enabled = copiedHashesText.isNotBlank(), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + val showManagedStatus = shouldShowManagedHashStatusCard( + continuationAvailable = remoteContinuation.available, + lifecycle = remoteAccessLifecycle, + ) + if ( + restoreCapability.exchange.actionAvailable || + remoteContinuation.available || + showManagedStatus || + remoteAction != null ) { - Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - FlexibleButtonText("Скопировать все хеши", fontWeight = FontWeight.SemiBold) - } - - if (remoteContinuation.available) { OutlinedButton( - onClick = { showRemoteActionInfo = true }, + onClick = { showAcquisitionDialog = true }, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), shape = RoundedCornerShape(16.dp), - enabled = !isChecking && !isRemoteActionRunning, - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + enabled = !isChecking, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), ) { - if (isRemoteActionRunning) { + if (isRemoteActionRunning || isRestoreRunning) { CircularProgressIndicator( modifier = Modifier.size(18.dp), strokeWidth = 2.dp, - color = MaterialTheme.colorScheme.primary - ) - Spacer(Modifier.width(6.dp)) - FlexibleButtonText( - remoteAction?.progressLabel - ?.takeIf { it.isNotBlank() } - ?: "Выполняется…", + color = MaterialTheme.colorScheme.primary, ) } else { Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - FlexibleButtonText( - remoteAction?.label - ?.takeIf { it.isNotBlank() } - ?: "Получить 4 хеша через VK", - fontWeight = FontWeight.SemiBold, - ) } - } - } else if ( - shouldShowManagedHashStatusCard( - continuationAvailable = remoteContinuation.available, - lifecycle = remoteAccessLifecycle, - ) - ) { - ManagedHashStatusCard(remoteAccessLifecycle) - } else if (remoteAction != null) { - RemoteActionCard( - action = remoteAction, - onLinkClick = { - closeDialog() - onOpenProjectSupport() - }, - onClick = { - scope.launch { - val opened = RemoteUiActionLauncher.open(context, remoteAction) - if (!opened) { - Toast.makeText( - context, - "Не удалось открыть страницу. Проверьте браузер.", - Toast.LENGTH_LONG, - ).show() - } - } - }, - ) - } - - if (isRemoteActionRunning) { - TextButton( - onClick = { cancelRemoteAction() }, - modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) - ) { - FlexibleButtonText( - remoteAction?.cancelLabel?.takeIf { it.isNotBlank() } ?: "Остановить", - color = MaterialTheme.colorScheme.error, - ) - } - } - - OutlinedButton( - onClick = { - checkJob?.cancel(CancellationException("Restarting hash check")) - checkJob = scope.launch { - isChecking = true - checkResults = checkableHashes.associate { (slot, hash) -> - slot to HashCheckResult(hash = hash, status = "pending", message = "Ожидает проверки") - } - val finalResults = runCatching { - checkVkHashes( - context = context, - hashes = checkableHashes, - fingerprint = activeFingerprint, - clientIds = activeClientIds, - customVkCredentialsEnabled = customVkCredentialsEnabled, - customVkClientId = customVkClientId, - customVkClientSecret = customVkClientSecret, - vkCallsPreflight = vkCallsPreflight, - captchaMode = captchaMode, - selectedWebViewManual = selectedWebViewManual, - onUpdate = { slot, result -> - checkResults = checkResults + (slot to result) - } - ) - }.getOrElse { error -> - if (error is CancellationException) { - checkableHashes.associate { (slot, hash) -> - slot to (checkResults[slot] ?: HashCheckResult(hash = hash, status = "cancelled", message = "Проверка остановлена")) - } - } else { - val message = error.message ?: "Не удалось выполнить проверку" - checkableHashes.associate { (slot, hash) -> - slot to HashCheckResult(hash = hash, status = "error", message = message) - } - } - } - checkResults = checkResults + finalResults - isChecking = false - checkJob = null - } - }, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp), - enabled = !isChecking && checkableHashes.isNotEmpty(), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) - ) { - if (isChecking) { - CircularProgressIndicator( - modifier = Modifier.size(18.dp), - strokeWidth = 2.dp, - color = MaterialTheme.colorScheme.primary - ) Spacer(Modifier.width(6.dp)) - FlexibleButtonText("Проверка $completedChecks/${checkableHashes.size}") - } else { - FlexibleButtonText("Проверить хеши", fontWeight = FontWeight.SemiBold) - } - } - - if (isChecking) { - TextButton( - onClick = { cancelHashCheck() }, - modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) - ) { - FlexibleButtonText("Остановить проверку", color = MaterialTheme.colorScheme.error) + FlexibleButtonText( + hashAcquisitionButtonLabel( + hasCompleteHashes = VkJoinLink.hasCompleteHashSet(currentHashes.joinToString(",")), + canRestore = restoreCapability.exchange.actionAvailable, + canAcquire = remoteContinuation.available, + busy = isRemoteActionRunning || isRestoreRunning, + ), + fontWeight = FontWeight.SemiBold, + ) } } @@ -6989,7 +6957,7 @@ fun HashesDialog( Button( onClick = { - cancelHashCheck() + cancelHashCheck(updateUi = false) onSave(h1, h2, h3, h4) }, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), @@ -7000,6 +6968,16 @@ fun HashesDialog( ) { FlexibleButtonText("Сохранить", fontWeight = FontWeight.SemiBold) } + } + SnackbarHost( + hostState = snackbarHostState, + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { data -> + WdttInlineNotice(data.visuals.message) + } + } } } } @@ -7007,6 +6985,7 @@ fun HashesDialog( if (showHashesHelp) { VkHashesInstructionDialog( remoteAction = remoteAction, + automaticAvailable = remoteContinuation.available, onOpenProjectSupport = { showHashesHelp = false closeDialog() @@ -7016,207 +6995,138 @@ fun HashesDialog( ) } } -} @Composable private fun VkHashesInstructionDialog( remoteAction: RemoteUiAction?, + automaticAvailable: Boolean, onOpenProjectSupport: () -> Unit, onDismiss: () -> Unit, ) { val context = LocalContext.current val scope = rememberCoroutineScope() - val television = isTelevisionDevice() - val scrollState = rememberScrollState() - Dialog( - onDismissRequest = onDismiss, - properties = DialogProperties(usePlatformDefaultWidth = false) + SettingsDialogLayout( + title = "Как получить ВК-хеши", + onDismiss = onDismiss, ) { - BoxWithConstraints( - modifier = Modifier.fillMaxSize().padding(8.dp), - contentAlignment = Alignment.Center + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f), + contentColor = MaterialTheme.colorScheme.onSecondaryContainer ) { - Surface( - modifier = (if (television) { - Modifier.televisionDialogWidth(television) - } else { - Modifier.fillMaxWidth(0.96f).widthIn(max = 680.dp) - }) - .heightIn(max = maxHeight * 0.92f), - shape = RoundedCornerShape(24.dp), - color = MaterialTheme.colorScheme.surface, - contentColor = MaterialTheme.colorScheme.onSurface, - tonalElevation = 8.dp + Text( + "ВК-хеш не нужно вычислять: это часть ссылки-приглашения в групповой звонок ВК.", + modifier = Modifier.padding(14.dp), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold + ) + } + + if (automaticAvailable) { + Text( + "Получить автоматически", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + ) + Text( + "Откройте меню получения ВК-хешей и выберите получение из ВК.", + style = MaterialTheme.typography.bodyMedium, + ) + Text( + VK_HASH_AUTO_HELP_TEXT, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + } + + Text( + "Из приложения ВК", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + VkHashInstructionStep(1, "Откройте приложение ВК или ВК Звонки.") + VkHashInstructionStep(2, "Создайте либо откройте групповой звонок.") + VkHashInstructionStep(3, "Нажмите приглашение участников и выберите «Поделиться ссылкой».") + VkHashInstructionStep(4, "В системном меню Android выберите WDTT Plus.") + VkHashInstructionStep(5, "Приложение извлечёт хэш и добавит его в первое свободное поле активного профиля.") + VkHashInstructionStep(6, "Для дополнительных хэшей повторите действия с другими звонками. Можно использовать до четырёх хэшей.") + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + + Text( + "Как добавить вручную", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + Text( + "Скопируйте ссылку из ВК Звонков и вставьте её целиком в поле либо нажмите «Вставить».", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.72f) + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) ) { - Box { - Column( - modifier = Modifier - .padding(22.dp) - .fillMaxWidth() - .verticalScroll(scrollState) - .tvDpadScrollable(scrollState, television), - verticalArrangement = Arrangement.spacedBy(14.dp) - ) { - Row( - modifier = Modifier.fillMaxWidth().padding(end = 44.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp) - ) { - Surface( - shape = CircleShape, - color = MaterialTheme.colorScheme.primaryContainer, - modifier = Modifier.size(38.dp) - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - Icons.AutoMirrored.Filled.HelpOutline, - contentDescription = null, - tint = MaterialTheme.colorScheme.onPrimaryContainer, - modifier = Modifier.size(22.dp) - ) - } - } - Text( - "Как получить VK-хеши", - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary - ) - } - } - - Surface( - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f), - contentColor = MaterialTheme.colorScheme.onSecondaryContainer - ) { - Text( - "VK-хеш не нужно вычислять: это часть ссылки-приглашения в групповой звонок VK.", - modifier = Modifier.padding(14.dp), - style = MaterialTheme.typography.bodyMedium, - fontWeight = FontWeight.SemiBold - ) - } - - Text( - "Самый простой способ", - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.Bold - ) - VkHashInstructionStep(1, "Откройте приложение VK или VK Звонки.") - VkHashInstructionStep(2, "Создайте либо откройте групповой звонок.") - VkHashInstructionStep(3, "Нажмите приглашение участников и выберите «Поделиться ссылкой».") - VkHashInstructionStep(4, "В системном меню Android выберите WDTT Plus.") - VkHashInstructionStep(5, "Приложение извлечёт хэш и добавит его в первое свободное поле активного профиля.") - VkHashInstructionStep(6, "Для дополнительных хэшей повторите действия с другими звонками. Можно использовать до четырёх хэшей.") - - HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) - - Text( - "Как добавить вручную", - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.Bold - ) - Text( - "Скопируйте ссылку из VK Звонков и вставьте её целиком в поле либо нажмите «Вставить хеши из буфера».", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Surface( - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(14.dp), - color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.72f) - ) { - Column( - modifier = Modifier.padding(14.dp), - verticalArrangement = Arrangement.spacedBy(8.dp) - ) { - Text( - "https://vk.ru/call/join/AbCdEf123456789", - style = MaterialTheme.typography.bodySmall, - fontWeight = FontWeight.SemiBold - ) - Text( - "Хэш — часть после /join/:", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - "AbCdEf123456789", - style = MaterialTheme.typography.bodyMedium, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary - ) - } - } - Text( - "Параметр ?from=share необязателен. Если после хэша есть знак ? или #, он и всё после него в хэш не входят. Поддерживаются ссылки vk.ru и vk.com.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - Surface( - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.72f), - contentColor = MaterialTheme.colorScheme.onErrorContainer - ) { - Column( - modifier = Modifier.padding(14.dp), - verticalArrangement = Arrangement.spacedBy(4.dp) - ) { - Text("Важно", fontWeight = FontWeight.Bold) - Text( - "Не выбирайте «Завершить для всех»: после закрытия комнаты ссылка может перестать работать. Можно просто выйти из звонка — постоянно оставаться в нём не требуется.", - style = MaterialTheme.typography.bodyMedium - ) - } - } - - if (remoteAction != null) { - RemoteActionCard( - action = remoteAction, - onLinkClick = onOpenProjectSupport, - onClick = { - scope.launch { - RemoteUiActionLauncher.open(context, remoteAction) - } - }, - ) - } - - Spacer(Modifier.height(4.dp)) - } - IconButton( - onClick = onDismiss, - modifier = Modifier - .align(Alignment.TopEnd) - .padding(top = 10.dp, end = 10.dp) - .remoteIconButtonFocus() - ) { - Surface( - shape = CircleShape, - color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.78f), - modifier = Modifier.size(34.dp) - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - Icons.Default.Close, - contentDescription = "Вернуться к настройке VK-хешей", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(22.dp) - ) - } - } - } - } + Text( + "https://vk.ru/call/join/AbCdEf123456789", + style = MaterialTheme.typography.bodySmall, + fontWeight = FontWeight.SemiBold + ) + Text( + "Хэш — часть после /join/:", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + "AbCdEf123456789", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary + ) } } + Text( + "Параметр ?from=share необязателен. Если после хэша есть знак ? или #, он и всё после него в хэш не входят. Поддерживаются ссылки vk.ru и vk.com.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.72f), + contentColor = MaterialTheme.colorScheme.onErrorContainer + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text("Важно", fontWeight = FontWeight.Bold) + Text( + "Не выбирайте «Завершить для всех»: после закрытия комнаты ссылка может перестать работать. Можно просто выйти из звонка — постоянно оставаться в нём не требуется.", + style = MaterialTheme.typography.bodyMedium + ) + } + } + + if (remoteAction != null) { + RemoteActionCard( + action = remoteAction, + onLinkClick = onOpenProjectSupport, + onClick = { + scope.launch { + RemoteUiActionLauncher.open(context, remoteAction) + } + }, + ) + } } } @@ -7256,6 +7166,114 @@ private data class HashCheckResult( val message: String ) +@Composable +internal fun WdttInlineNotice(message: String, modifier: Modifier = Modifier) { + Surface( + modifier = modifier, + shape = RoundedCornerShape(28.dp), + color = MaterialTheme.colorScheme.surfaceContainerHighest, + contentColor = MaterialTheme.colorScheme.onSurface, + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f), + ), + shadowElevation = 10.dp, + ) { + Row( + modifier = Modifier.padding(horizontal = 18.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + // R.mipmap.ic_launcher resolves to an adaptive-icon XML on Android 8+. + // Compose painterResource only accepts vector/raster drawables and throws + // during composition for adaptive icons, which used to close the activity + // as soon as this notice appeared. Android's ImageView handles every + // launcher-icon variant selected for the current device. + AndroidView( + factory = { viewContext -> + android.widget.ImageView(viewContext).apply { + scaleType = android.widget.ImageView.ScaleType.FIT_CENTER + setImageResource(R.mipmap.ic_launcher) + importantForAccessibility = android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO + } + }, + modifier = Modifier.size(28.dp), + ) + Text( + message, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + ) + } + } +} + +@Composable +private fun HashAcquisitionOptionCard( + title: String, + description: String, + buttonText: String, + icon: ImageVector, + busy: Boolean, + enabled: Boolean, + onClick: () -> Unit, +) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.42f), + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f), + ), + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp), + ) + Text( + title, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + ) + } + Text( + description, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedButton( + onClick = onClick, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + enabled = enabled, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), + ) { + if (busy) { + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp, + ) + } else { + Icon(icon, contentDescription = null, modifier = Modifier.size(18.dp)) + } + Spacer(Modifier.width(6.dp)) + FlexibleButtonText(buttonText, fontWeight = FontWeight.SemiBold) + } + } + } +} + @Composable private fun HashInputField( slot: Int, @@ -7283,7 +7301,7 @@ private fun HashInputField( Column( modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(4.dp) + verticalArrangement = Arrangement.spacedBy(3.dp) ) { OutlinedTextField( value = value, @@ -7304,26 +7322,26 @@ private fun HashInputField( ) { Icon( Icons.Default.Close, - contentDescription = "Очистить VK Хеш $slot", + contentDescription = "Очистить ВК-хеш $slot", modifier = Modifier.size(18.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant ) } } - IconButton( + HintIconButton(hint = "Скопировать ВК-хеш $slot", onClick = onCopyClick, enabled = canCopy, modifier = Modifier.size(34.dp) ) { Icon( Icons.Default.ContentCopy, - contentDescription = "Скопировать VK Хеш $slot", + contentDescription = "Скопировать ВК-хеш $slot", modifier = Modifier.size(18.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = if (canCopy) 1f else 0.38f) ) } if (visibleResult != null) { - IconButton( + HintIconButton(hint = "Результат проверки ВК-хеша", onClick = onInfoClick, modifier = Modifier.size(34.dp) ) { @@ -7346,8 +7364,8 @@ private fun HashInputField( } } }, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = 54.dp), + shape = RoundedCornerShape(14.dp), colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = borderColor, unfocusedBorderColor = borderColor, @@ -7375,7 +7393,7 @@ private fun HashInputField( private fun hashStatusColor(status: String): Color { return when (status) { "ok" -> WDTTColors.connected - "dead", "blocked" -> MaterialTheme.colorScheme.error + "dead", "blocked", "auth_required" -> MaterialTheme.colorScheme.error "full", "captcha", "solving_captcha", "limited", "network" -> WDTTColors.warning "checking" -> MaterialTheme.colorScheme.primary "pending" -> MaterialTheme.colorScheme.outline @@ -7389,10 +7407,11 @@ private fun hashStatusLabel(status: String): String { "ok" -> "живой" "dead" -> "закрыт" "blocked" -> "вход запрещён" + "auth_required" -> "нужен вход" "full" -> "заполнен" "captcha" -> "капча" "solving_captcha" -> "решаем капчу" - "limited" -> "лимит VK" + "limited" -> "лимит ВК" "network" -> "сеть" "checking" -> "проверяется" "pending" -> "ожидает" @@ -7423,7 +7442,7 @@ private suspend fun solveHashCheckCaptcha( ): String { val normalizedMode = mode.lowercase().trim() if (normalizedMode == "manual" || (normalizedMode == "selected" && selectedWebViewManual)) { - onProgress("Открыта ручная VK Captcha") + onProgress("Открыта ручная капча ВК") return ManlCaptchaWebViewManager.solveCaptchaAsync(context, redirectUri, sessionToken) } @@ -7491,14 +7510,13 @@ private suspend fun checkVkHashes( val byOrder = hashes.mapIndexed { order, pair -> order + 1 to pair }.toMap() val parsed = mutableMapOf() val startedAutoWebView = !TunnelManager.running.value - var timedOut = false + val timedOut = AtomicBoolean(false) var currentSlot: Int? = null val timeoutMs = (hashes.size * 120_000L).coerceAtLeast(120_000L) - var cleanedUp = false + val cleanedUp = AtomicBoolean(false) fun cleanupCheckProcess() { - if (cleanedUp) return - cleanedUp = true + if (!cleanedUp.compareAndSet(false, true)) return if (process.isAlive) { process.destroyForcibly() } @@ -7522,7 +7540,7 @@ private suspend fun checkVkHashes( try { Thread.sleep(timeoutMs) if (process.isAlive) { - timedOut = true + timedOut.set(true) process.destroyForcibly() } } catch (_: InterruptedException) { @@ -7549,7 +7567,7 @@ private suspend fun checkVkHashes( HashCheckResult( hash = original.second, status = "checking", - message = "Проверяется VK Хеш ${original.first}" + message = "Проверяется ВК-хеш ${original.first}" ), parsed, onUpdate @@ -7570,12 +7588,12 @@ private suspend fun checkVkHashes( HashCheckResult( hash = currentHash, status = "solving_captcha", - message = "VK запросил капчу, решаем..." + message = "ВК запросил капчу, решаем..." ), parsed, onUpdate ) - val captchaResult = runCatching { + val captchaResult = try { solveHashCheckCaptcha( context, mode, @@ -7590,7 +7608,9 @@ private suspend fun checkVkHashes( onUpdate ) } - }.getOrElse { error -> + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { "error:${error.message ?: "captcha failed"}" } val resultPayload = if (requestId.isBlank()) captchaResult else "$requestId|$captchaResult" @@ -7635,8 +7655,8 @@ private suspend fun checkVkHashes( } hashes.associate { (slot, hash) -> - val fallbackMessage = if (timedOut) "Проверка не завершилась за отведённое время" else "Нет ответа проверки" - val fallbackStatus = if (timedOut) "network" else "error" + val fallbackMessage = if (timedOut.get()) "Проверка не завершилась за отведённое время" else "Нет ответа проверки" + val fallbackStatus = if (timedOut.get()) "network" else "error" slot to (parsed[slot] ?: HashCheckResult(hash = hash, status = fallbackStatus, message = fallbackMessage)) } } @@ -7647,8 +7667,8 @@ private fun hashStatusMessage(status: String): String { "dead" -> "Звонок не найден или закрыт" "blocked" -> "Звонок существует, но в нём запрещён анонимный вход" "full" -> "Звонок существует, но сейчас в нём нет свободных мест" - "captcha" -> "VK запросил капчу, но решить её не удалось" - "limited" -> "VK временно ограничил запросы" + "captcha" -> "ВК запросил капчу, но решить её не удалось" + "limited" -> "ВК временно ограничил запросы" "network" -> "Сетевая ошибка при проверке" "cancelled" -> "Проверка остановлена" else -> "Не удалось проверить хеш" @@ -7684,7 +7704,7 @@ fun SecretsDialog( return value.toIntOrNull()?.takeIf { it in 1..65535 }?.toString() ?: fallback } - Dialog(onDismissRequest = onDismiss) { + BoundedAppDialog(properties = androidx.compose.ui.window.DialogProperties(), onDismissRequest = onDismiss) { BoxWithConstraints( modifier = Modifier.fillMaxSize().padding(8.dp), contentAlignment = Alignment.Center diff --git a/app/src/main/java/com/wdtt/plus/ui/SleepTimerDialog.kt b/app/src/main/java/com/wdtt/plus/ui/SleepTimerDialog.kt index b6b59e3..85b05b6 100644 --- a/app/src/main/java/com/wdtt/plus/ui/SleepTimerDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/SleepTimerDialog.kt @@ -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), ) { diff --git a/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt b/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt index 2f05718..7c96885 100644 --- a/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt +++ b/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt @@ -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(null) } + var opening by remember(profile, identity) { mutableStateOf(false) } + var failure by remember(profile, identity) { mutableStateOf(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(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(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)) { diff --git a/app/src/main/java/com/wdtt/plus/ui/TrustedWifiSettingsDialog.kt b/app/src/main/java/com/wdtt/plus/ui/TrustedWifiSettingsDialog.kt index 5ef3d3f..c032147 100644 --- a/app/src/main/java/com/wdtt/plus/ui/TrustedWifiSettingsDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/TrustedWifiSettingsDialog.kt @@ -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) }, diff --git a/app/src/main/java/com/wdtt/plus/ui/VkClientSettingsDialog.kt b/app/src/main/java/com/wdtt/plus/ui/VkClientSettingsDialog.kt index 5a2f63d..cf9a339 100644 --- a/app/src/main/java/com/wdtt/plus/ui/VkClientSettingsDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/VkClientSettingsDialog.kt @@ -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 = "Копировать") } } diff --git a/app/src/main/java/com/wdtt/plus/ui/VpnDnsSettingsDialog.kt b/app/src/main/java/com/wdtt/plus/ui/VpnDnsSettingsDialog.kt index 5feb979..bc0b412 100644 --- a/app/src/main/java/com/wdtt/plus/ui/VpnDnsSettingsDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/VpnDnsSettingsDialog.kt @@ -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(null) } val selectedPreset = vpnDnsPresets.firstOrNull { it.id == selectionId } - Dialog( + BoundedAppDialog( onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false), ) { diff --git a/app/src/main/java/com/wdtt/plus/vk/ModernVkContainerActivity.kt b/app/src/main/java/com/wdtt/plus/vk/ModernVkContainerActivity.kt new file mode 100644 index 0000000..f5aa4ca --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/ModernVkContainerActivity.kt @@ -0,0 +1,1284 @@ +package com.wdtt.plus.vk + +import android.annotation.SuppressLint +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.graphics.Bitmap +import android.net.Uri +import android.net.ConnectivityManager +import android.net.http.SslError +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.os.ResultReceiver +import android.view.WindowManager +import android.view.View +import android.webkit.ConsoleMessage +import android.webkit.CookieManager +import android.webkit.SslErrorHandler +import android.webkit.WebChromeClient +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import android.webkit.RenderProcessGoneDetail +import android.widget.FrameLayout +import androidx.activity.ComponentActivity +import androidx.activity.OnBackPressedCallback +import androidx.activity.compose.setContent +import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +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.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.wrapContentHeight +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Key +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInRoot +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.zIndex +import androidx.compose.ui.viewinterop.AndroidView +import com.wdtt.plus.WDTTTheme +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.launch +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature +import java.net.URI + +/** + * Top-level VK web container for the preferred in-app flow. The protected + * runtime may request a short-lived Mini App token before the first guarded + * call; no token is exposed to Android or persisted here. + */ +open class ModernVkContainerActivity : ComponentActivity() { + private var receiver: ResultReceiver? = null + private var session = "" + private var page by mutableStateOf(null) + private var status by mutableStateOf("Открываю официальный контейнер ВК…") + private var loading by mutableStateOf(true) + private var error by mutableStateOf(false) + private var confirmClose by mutableStateOf(false) + private var confirmReplace by mutableStateOf(false) + private var receiverRegistered = false + private var desktopLandingZoomed = false + private var desktopContainerActivated = false + private var webContentVisible by mutableStateOf(true) + private var canLogout by mutableStateOf(false) + private var logoutInProgress by mutableStateOf(false) + private var completedHashes by mutableIntStateOf(0) + private var activeHashAttempt by mutableIntStateOf(0) + private var vkMutationStarted = false + private var fallbackRequested by mutableStateOf(false) + private var flowGuard = ModernVkFlowGuard() + private var accountChoice by mutableStateOf(null) + private var continueAccount: (() -> Unit)? = null + private var confirmedAccountId: Long? = null + private var replacementApproved = false + private var waitingForConsent = false + private var captcha: VkInPlaceCaptcha? = null + private var captchaState by mutableStateOf(VkCaptchaPolicy.State.IDLE) + private var captchaObserverSupported by mutableStateOf(true) + private var captchaPageVisible by mutableStateOf(false) + private var foreground = false + private val captchaVisible get() = captchaState != VkCaptchaPolicy.State.IDLE || captchaPageVisible + private val preflightHandler = Handler(Looper.getMainLooper()) + private val revealConsent = Runnable { + if (waitingForConsent && !flowGuard.terminal && !fallbackRequested) { + webContentVisible = true + loading = false + } + } + private val preflightTimeout = VkCaptchaTimeout { + if (flowGuard.canFallback && !fallbackRequested && !isFinishing && !isDestroyed) { + loading = false + error = true + activeHashAttempt = 0 + if (captchaVisible) { + status = "Время ожидания проверки ВК истекло. Закройте окно и повторите позже." + flowGuard.close() + log("CAPTCHA / TIMEOUT") + disposePage() + return@VkCaptchaTimeout + } + status = "ВК не ответил. Перехожу к резервному способу…" + requestSafeFallback("PREFLIGHT_TIMEOUT") + } + } + private val mutationTimeout = VkCaptchaTimeout { + if (flowGuard.mutationPossible && !isFinishing && !isDestroyed) { + flowGuard.close() + loading = false + error = true + status = "Получение остановлено: ВК не ответил вовремя. Повторные запросы не отправляются." + log("BRIDGE / FLOW_FAILED / NONE / NONE / TIMEOUT") + disposePage() + } + } + private lateinit var localProfile: com.wdtt.plus.LocalContinuationProfile + private val vkSession by lazy { VkLocalSession.forContext(this, localProfile) } + + private val finishReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action == HANDOFF_ACTION) { + if (fallbackRequested) finish() + return + } + if (intent?.getStringExtra(EXTRA_SESSION) != session) return + if (fallbackRequested) { finish(); return } + val successful = intent.getBooleanExtra(EXTRA_SUCCESS, false) + if (successful) { + log("COMPLETE / получены четыре ВК-хеша") + setResult(RESULT_OK) + } else { + log("CLOSE / новые ВК-хеши не получены") + setResult(RESULT_CANCELED) + } + cancelPreflightTimeout() + finish() + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + @Suppress("DEPRECATION") + receiver = intent.getParcelableExtra(EXTRA_RECEIVER) + setContent { WDTTTheme { ProfileSessionPreparation(status, error) { + receiver?.send(RESULT_CANCEL, Bundle()); finish() + } } } + status = "Подготавливаю вход для выбранного профиля…" + lifecycleScope.launch { + try { + localProfile = ProfileWebSessionScope.read(this@ModernVkContainerActivity, intent) + vkSession.prepareProfile(localProfile.identity) { VkLocalSession.clearWebData() } + if (!isFinishing && !isDestroyed) openPreparedContainer() + } catch (timeout: TimeoutCancellationException) { + error = true + status = "Не удалось подготовить отдельный сеанс профиля. Закройте окно и повторите." + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + error = true + status = "Не удалось подготовить отдельный сеанс профиля. Получение не запускалось." + } + } + } + + @SuppressLint("SetJavaScriptEnabled") + private fun openPreparedContainer() { + // The fallback engine pins this profile process to a particular network. + // Its saved token remains route-bound, but a NEW browser flow must not + // inherit an obsolete Wi-Fi/mobile binding from a previous invocation. + val connectivity = getSystemService(ConnectivityManager::class.java) + check(connectivity.boundNetworkForProcess == null || connectivity.bindProcessToNetwork(null)) { + "Не удалось подготовить соединение с ВК." + } + window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) + @Suppress("DEPRECATION") + receiver = intent.getParcelableExtra(EXTRA_RECEIVER) + session = intent.getStringExtra(EXTRA_SESSION).orEmpty() + confirmReplace = intent.getBooleanExtra(EXTRA_HAS_COMPLETE_VALUES, false) && !replacementApproved + val hasRememberedSession = vkSession.remembered + val confirmAccount = VkAccountChoicePolicy.required(hasRememberedSession, CookieManager.getInstance().hasCookies()) + val launchUrl = runCatching { + ModernVkContainerProtocol.launchUrl(intent.getStringExtra( + if (confirmAccount) "confirmation_url" else EXTRA_URL).orEmpty()) + }.getOrElse { + log("LAUNCH_URL / INVALID") + receiver?.send(RESULT_SAFE_FALLBACK, Bundle().apply { + putString("reason", "LAUNCH_URL_INVALID") + }) + finish() + return + } + val mobileEntryUrl = intent.getStringExtra( + if (confirmAccount) "confirmation_login_url" else "login_url").orEmpty() + val presentationContext = intent.getStringExtra("context").orEmpty() + if (!ModernVkContainerProtocol.validLoginUrl(mobileEntryUrl) || + !presentationContext.matches(Regex("[A-Za-z0-9_.-]{24,2048}"))) { + log("LAUNCH_URL / INVALID") + receiver?.send(RESULT_SAFE_FALLBACK, Bundle()) + finish() + return + } + val pendingLogout = vkSession.logoutPending + if (pendingLogout) confirmReplace = false + canLogout = hasRememberedSession || pendingLogout + webContentVisible = !hasRememberedSession && !pendingLogout + desktopContainerActivated = hasRememberedSession + if (!receiverRegistered) { + registerFinishReceiver() + onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + if (fallbackRequested) return + val current = page + if (webContentVisible && !flowGuard.mutationPossible && current?.canGoBack() == true) current.goBack() else confirmClose = true + } + }) + } + + fun createPage(desktop: Boolean): WebView = WebView(this).apply { + val sourcePage = this + WebView.setWebContentsDebuggingEnabled(false) + settings.javaScriptEnabled = true + settings.domStorageEnabled = true + settings.databaseEnabled = false + settings.allowFileAccess = false + settings.allowContentAccess = false + settings.javaScriptCanOpenWindowsAutomatically = false + settings.setSupportMultipleWindows(false) + settings.useWideViewPort = true + settings.loadWithOverviewMode = true + settings.setSupportZoom(true) + settings.builtInZoomControls = true + settings.displayZoomControls = false + // Configure only an unloaded WebView. Changing UA on a loading auth + // page makes Android reload it, potentially replaying its login redirect. + settings.userAgentString = if (desktop) { + ModernVkContainerProtocol.DESKTOP_USER_AGENT + } else { + WebSettings.getDefaultUserAgent(this@ModernVkContainerActivity) + } + CookieManager.getInstance().setAcceptCookie(true) + CookieManager.getInstance().setAcceptThirdPartyCookies(this, true) + if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { + WebViewCompat.addWebMessageListener(this, "WDTTProfileAccount", setOf("https://wdttplus.ru")) { + view, message, origin, isMainFrame, reply -> + if (!isCurrentRenderer(view) || isMainFrame || origin.scheme != "https" || origin.host != "wdttplus.ru" || + origin.port !in setOf(-1, 443) || + !confirmAccount || flowGuard.mutationPossible || !flowGuard.acceptsPageCallbacks || + fallbackRequested || logoutInProgress) return@addWebMessageListener + val request = runCatching { + VkAccountMessage.parse(message.data.orEmpty(), presentationContext) + }.getOrNull() ?: return@addWebMessageListener + flowGuard.accept("ACCOUNT_WAIT") + vkSession.rememberAuthenticatedWebSession() + canLogout = true + if (confirmedAccountId == request.account.id) { + reply.postMessage(request.continueReply()) + } else { + cancelPreflightTimeout() + accountChoice = request.account + webContentVisible = false + loading = false + status = "Подтвердите аккаунт перед получением ВК-хешей." + continueAccount = { + if (!flowGuard.mutationPossible && !logoutInProgress && page === view) { + confirmedAccountId = request.account.id + accountChoice = null + continueAccount = null + loading = true + status = "Подготавливаю получение ВК-хешей…" + armPreflightTimeout(PRE_MUTATION_TIMEOUT_MS) + reply.postMessage(request.continueReply()) + } + } + } + } + } + // Keep the renderer attached even while the native progress card covers it. + // An invisible page must never receive taps intended for that card. + setOnTouchListener { _, event -> + if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN) captcha?.userInteraction() + !webContentVisible && !captchaVisible && captchaObserverSupported + } + webChromeClient = object : WebChromeClient() { + override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean { + if (!isCurrentRenderer(sourcePage)) return true + ModernVkContainerProtocol.diagnosticFromConsole(consoleMessage?.message().orEmpty()) + ?.let { + log(it) + handleBridgeDiagnostic(it) + } + return super.onConsoleMessage(consoleMessage) + } + } + webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { + if (view !== page || !flowGuard.acceptsPageCallbacks || logoutInProgress || fallbackRequested) return true + val uri = request.url + if ( + request.isForMainFrame && + ModernVkContainerProtocol.isMiniAppLanding(uri.toString()) && + !desktopContainerActivated + ) { + activateDesktopContainer(view, launchUrl) { createPage(desktop = true) } + return true + } + // id/login redirects also perform silent session refresh and + // consent. Their URL is NOT evidence that VK logged the user out. + if (request.isForMainFrame && !ModernVkContainerProtocol.allowedNavigation(uri.toString())) { + error = true + status = "Внешний переход заблокирован. Оставайтесь в окне ВК." + log("NAV_BLOCK / ${uri.scheme.orEmpty()} / ${uri.host.orEmpty()}") + return true + } + // Let WebView follow allowed redirects itself; restarting every + // navigation with loadUrl loses POST/history and rebuilds the container. + return false + } + + override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { + if (view == null || view !== page || !flowGuard.acceptsPageCallbacks || fallbackRequested) return + captchaPageVisible = VkCaptchaPolicy.captchaPage(url.orEmpty()) + updateCaptchaTimers() + if (ModernVkContainerProtocol.isAuthenticationPage(url.orEmpty())) { + cancelPreflightTimeout() + webContentVisible = true + } else if (!waitingForConsent && (desktopContainerActivated || ModernVkContainerProtocol.shouldFocusDesktopLanding(url.orEmpty()))) { + webContentVisible = false + } + if (!ModernVkContainerProtocol.shouldFocusDesktopLanding(url.orEmpty()) && desktopLandingZoomed) { + view?.zoomBy(1f / DESKTOP_LANDING_ZOOM) + view?.scrollTo(0, 0) + desktopLandingZoomed = false + } + if (flowGuard.allowPageStatus) { + loading = true + error = false + status = "Загружаю страницу ВК…" + } + log("PAGE_START / ${runCatching { Uri.parse(url).host }.getOrNull().orEmpty()}") + } + + override fun onPageFinished(view: WebView?, url: String?) { + if (!isCurrentRenderer(view)) return + CookieManager.getInstance().flush() + if (!flowGuard.acceptsPageCallbacks || fallbackRequested) return + if (!ModernVkContainerProtocol.isCurrentPage(view?.url, url)) return + if ( + view != null && + !desktopContainerActivated && + ModernVkContainerProtocol.shouldPromoteAuthenticatedMobilePage(url.orEmpty()) + ) { + log("MOBILE_AUTH_RETURN / ${runCatching { Uri.parse(url).path }.getOrNull().orEmpty()}") + activateDesktopContainer(view, launchUrl) { createPage(desktop = true) } + return + } + if (flowGuard.allowPageStatus) { + loading = desktopContainerActivated && !webContentVisible + status = if (ModernVkContainerProtocol.isAuthenticationPage(url.orEmpty())) { + "Войдите в ВК. После входа получение продолжится автоматически." + } else if (ModernVkContainerProtocol.shouldFocusDesktopLanding(url.orEmpty())) { + "Проверяю вход в ВК и подготавливаю получение…" + } else { + "Завершаю вход в ВК и подготавливаю получение хешей…" + } + } + focusDesktopLanding(view, url.orEmpty()) + if (flowGuard.allowPageStatus && ModernVkContainerProtocol.isMiniAppLanding(url.orEmpty())) { + // Repeated PAGE_READY is not progress and must not prolong + // preparation indefinitely. Auth pages explicitly pause it. + preflightTimeout.armIfIdle(PREFLIGHT_TIMEOUT_MS) + updateCaptchaTimers() + } + log("PAGE_READY / ${runCatching { Uri.parse(url).host }.getOrNull().orEmpty()}") + } + + override fun onReceivedError( + view: WebView?, + request: WebResourceRequest?, + resourceError: WebResourceError?, + ) { + if (!isCurrentRenderer(view) || request == null) return + if (!request.isForMainFrame && !(captchaVisible && VkCaptchaPolicy.captchaPage(request.url.toString()))) return + loading = false + error = true + status = "Страница ВК не загрузилась. Проверьте сеть и повторите." + log("WEB / ${resourceError?.errorCode ?: 0}") + requestSafeFallback("WEB_${resourceError?.errorCode ?: 0}") + } + + override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { + if (!isCurrentRenderer(view)) return true + if (flowGuard.canFallback && !captchaVisible) { + requestSafeFallback("RENDERER_GONE") + } else { + flowGuard.close() + loading = false + error = true + webContentVisible = false + status = "Окно ВК остановлено системой. Повторные запросы не отправляются." + log("BRIDGE / FLOW_FAILED / NONE / NONE / RENDERER") + disposePage() + } + return true + } + + override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) { + if (!isCurrentRenderer(view) || !(request.isForMainFrame || + (captchaVisible && VkCaptchaPolicy.captchaPage(request.url.toString())))) return + loading = false + error = true + status = "ВК не загрузил страницу проверки. Попробуйте позже." + log("WEB / HTTP_${response.statusCode}") + requestSafeFallback("HTTP_${response.statusCode}") + } + + override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, sslError: SslError?) { + handler.cancel() + if (!isCurrentRenderer(view)) return + val failedUrl = sslError?.url.orEmpty() + val currentUrl = view?.url.orEmpty() + val failedHost = runCatching { Uri.parse(failedUrl).host }.getOrNull().orEmpty() + val isTopLevel = failedUrl.isNotBlank() && currentUrl.substringBefore('#') == failedUrl.substringBefore('#') + if (isTopLevel || (captchaVisible && VkCaptchaPolicy.captchaPage(failedUrl))) { + loading = false + error = true + status = "Защищённое соединение со страницей ВК не подтверждено." + requestSafeFallback("SSL_${sslError?.primaryError ?: -1}") + } + val category = if (ModernVkContainerProtocol.isVkTelemetryHost(failedHost)) { + "SSL_TELEMETRY" + } else { + "SSL" + } + log("$category / ${sslError?.primaryError ?: -1} / ${failedHost.take(80)} / ${if (isTopLevel) "MAIN" else "RESOURCE"}") + } + } + } + val webView = createPage(desktop = hasRememberedSession) + attachPage(webView) + if (!confirmReplace && !pendingLogout) { + webView.loadUrl(ModernVkContainerProtocol.initialLaunchUrl( + desktopUrl = launchUrl, + mobileLoginUrl = mobileEntryUrl, + hasRememberedSession = hasRememberedSession, + )) + } + if (hasRememberedSession && !confirmReplace) armPreflightTimeout() + + setContent { + WDTTTheme { + val compact = !webContentVisible && !captchaVisible && captchaObserverSupported + var rootOffset by remember { mutableStateOf(IntOffset.Zero) } + BoxWithConstraints( + Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.58f)) + .systemBarsPadding().imePadding().onGloballyPositioned { + val position = it.positionInRoot() + rootOffset = IntOffset(position.x.toInt(), position.y.toInt()) + }, + contentAlignment = Alignment.Center, + ) { + val density = LocalDensity.current + var browserOffset by remember { mutableStateOf(IntOffset.Zero) } + var browserSize by remember { mutableStateOf(IntSize.Zero) } + // A single composition site for the entire session. Never remove + // AndroidView when login turns into compact progress: detached + // WebViews may suspend Bridge callbacks/timers on OEM firmware. + val width = if (browserSize.width > 0) with(density) { browserSize.width.toDp() } else maxWidth + val height = if (browserSize.height > 0) with(density) { browserSize.height.toDp() } else maxHeight + if (!fallbackRequested && !logoutInProgress && page != null) AndroidView( + factory = { FrameLayout(it) }, + update = { host -> + val current = page + if (host.getChildAt(0) !== current) { + host.removeAllViews() + current?.let { host.addView(it, FrameLayout.LayoutParams(-1, -1)) } + } + host.importantForAccessibility = if (compact) View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS else View.IMPORTANT_FOR_ACCESSIBILITY_AUTO + }, + modifier = Modifier.align(Alignment.TopStart).offset { browserOffset }.size(width, height) + .clip(RoundedCornerShape(18.dp)).alpha(if (compact) 0f else 1f) + .zIndex(if (compact) -1f else 1f), + ) + Surface( + modifier = (if (compact) { + Modifier.fillMaxWidth().widthIn(max = 560.dp).wrapContentHeight() + .padding(horizontal = 12.dp) + } else { + Modifier.fillMaxSize().padding(horizontal = 1.dp, vertical = 6.dp) + }).animateContentSize(animationSpec = tween(280)), + shape = RoundedCornerShape(22.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + ) { + Column( + modifier = (if (compact) Modifier.wrapContentHeight() else Modifier.fillMaxSize()) + .padding( + horizontal = if (compact) 18.dp else 8.dp, + vertical = if (compact) 16.dp else 12.dp, + ), + verticalArrangement = Arrangement.spacedBy(if (compact) 12.dp else 8.dp), + ) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text( + if (compact) "ВК-хеши" else "Получение ВК-хешей", + style = MaterialTheme.typography.titleLarge, + modifier = Modifier.weight(1f), + ) + if (canLogout && accountChoice == null) { + TextButton( + onClick = { logoutVkSession() }, + enabled = !logoutInProgress && !fallbackRequested, + ) { Text("Выйти из ВК") } + } + IconButton(onClick = { confirmClose = true }, enabled = !fallbackRequested) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + Text( + if (compact) { + "Получение внутри приложения" + } else { + "Войдите в ВК на официальной странице. Остальное приложение выполнит автоматически." + }, + style = MaterialTheme.typography.bodySmall, + color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + ) + Surface( + shape = RoundedCornerShape(50), + color = MaterialTheme.colorScheme.surfaceContainerHighest, + ) { + Text( + if (captchaVisible && !error) VkCaptchaPolicy.message(captchaState.takeUnless { + it == VkCaptchaPolicy.State.IDLE + } ?: VkCaptchaPolicy.State.MANUAL) else status, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp), + style = MaterialTheme.typography.labelMedium, + ) + } + if (accountChoice != null) { + VkAccountChoicePanel(accountChoice!!, !logoutInProgress, + onContinue = { continueAccount?.invoke() }, onLogout = { logoutVkSession() }) + } else if (compact) { + VkHashProgressPanel( + completed = completedHashes, + activeAttempt = activeHashAttempt, + loading = loading, + error = error, + ) + } else { + Box(Modifier.fillMaxWidth().weight(1f).onGloballyPositioned { + // Root padding is outside BoxWithConstraints' content. + val position = it.positionInRoot() + browserOffset = IntOffset(position.x.toInt(), position.y.toInt()) - rootOffset + browserSize = it.size + }) { + if (loading) { + Surface( + modifier = Modifier.align(Alignment.Center), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surface.copy(alpha = 0.92f), + ) { + Column( + Modifier.padding(horizontal = 24.dp, vertical = 18.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + CircularProgressIndicator() + Spacer(Modifier.height(10.dp)) + Text("Загрузка…") + } + } + } + } + } + } + } + } + if (confirmClose) { + AlertDialog( + onDismissRequest = { confirmClose = false }, + title = { Text("Закрыть получение?") }, + text = { Text("Уже отправленный запрос ВК нельзя отменить закрытием окна. Автоматического повтора не будет.") }, + confirmButton = { + TextButton(onClick = { + receiver?.send(RESULT_CANCEL, Bundle()) + finish() + }) { Text("Закрыть") } + }, + dismissButton = { + TextButton(onClick = { confirmClose = false }) { Text("Назад") } + }, + ) + } + if (confirmReplace) { + AlertDialog( + onDismissRequest = {}, + title = { Text("Заменить ВК-хеши?") }, + text = { Text("В профиле уже заполнены четыре ВК-хеша. Приложение создаст четыре новые ссылки и заменит текущие после успешного завершения.") }, + confirmButton = { + TextButton(onClick = { + confirmReplace = false + replacementApproved = true + val remembered = hasRememberedSession + canLogout = remembered + webContentVisible = !remembered + desktopContainerActivated = remembered + page?.loadUrl( + ModernVkContainerProtocol.initialLaunchUrl( + launchUrl, + mobileEntryUrl, + remembered, + ), + ) + if (remembered) armPreflightTimeout() + log("REPLACE_CONFIRMED") + }) { Text("Получить новые") } + }, + dismissButton = { + TextButton(onClick = { + receiver?.send(RESULT_CANCEL, Bundle()) + finish() + }) { Text("Назад") } + }, + ) + } + } + } + log("OPEN / STRICT_BRIDGE_V1") + // Finish an interrupted local logout before loading any VK page. + if (pendingLogout) logoutVkSession() + } + + private fun registerFinishReceiver() { + val filter = IntentFilter(FINISH_ACTION).apply { addAction(HANDOFF_ACTION) } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + registerReceiver(finishReceiver, filter, RECEIVER_NOT_EXPORTED) + } else { + @Suppress("DEPRECATION") + registerReceiver(finishReceiver, filter) + } + receiverRegistered = true + } + + private fun focusDesktopLanding(view: WebView?, url: String) { + if (view == null || desktopLandingZoomed || !ModernVkContainerProtocol.shouldFocusDesktopLanding(url)) return + desktopLandingZoomed = true + view.postDelayed({ + if (isFinishing || isDestroyed || page !== view) return@postDelayed + view.zoomBy(DESKTOP_LANDING_ZOOM) + view.postDelayed({ + if (isFinishing || isDestroyed || page !== view) return@postDelayed + val centeredX = (view.width * (DESKTOP_LANDING_ZOOM - 1f) / 2f).toInt() + view.scrollTo(centeredX, 0) + }, 120L) + }, 180L) + } + + private fun isCurrentRenderer(view: WebView?): Boolean = + view != null && view === page && !flowGuard.containerHandoffPending + + private fun attachPage(view: WebView) { + page = view + captcha = VkInPlaceCaptcha(view, { foreground && !confirmClose && !logoutInProgress }, + apiBridgeEnabled = true, changed = { state -> + if (isCurrentRenderer(view)) onCaptchaState(state) + }) + captchaObserverSupported = captcha?.supported == true + } + + private fun activateDesktopContainer(view: WebView, launchUrl: String, createPage: () -> WebView) { + if (!isCurrentRenderer(view) || !flowGuard.beginContainerHandoff()) return + CookieManager.getInstance().flush() + canLogout = true + webContentVisible = false + desktopContainerActivated = true + loading = true + status = "Проверяю вход в ВК и подготавливаю получение…" + log("MOBILE_AUTH_COMPLETE / DESKTOP_BRIDGE") + // Leave the navigation callback before retiring its renderer. The new + // renderer uses the SAME profile's cookie jar, not a new login/storage. + // Only the WebView child changes; the Activity/progress window stays put. + preflightHandler.post { + if (page !== view || isFinishing || isDestroyed || fallbackRequested || logoutInProgress || + !flowGuard.completeContainerHandoff()) return@post + disposePage() + desktopLandingZoomed = false + try { + attachPage(createPage()) + page?.loadUrl(launchUrl) + armPreflightTimeout() + } catch (_: Exception) { + requestSafeFallback("CONTAINER_START_FAILED") + } + } + } + + private fun handleBridgeDiagnostic(message: String) { + if (fallbackRequested || isFinishing || isDestroyed || logoutInProgress) return + val stage = message.substringAfter("BRIDGE / ").substringBefore(" / ") + if (!flowGuard.accept(stage)) return + // Only an authenticated Bridge stage confirms the saved-session hint. + // In particular AUTH_READY repairs hints erased by older APKs on consent. + vkSession.observeBridgeStage(stage) + if (vkSession.remembered) canLogout = true + if (flowGuard.terminal || stage == "DELIVER_FAILED") { + mutationTimeout.cancel() + } + when { + stage == "INIT_WAIT" -> { + status = "Подключаюсь к ВК для получения хешей…" + preflightTimeout.armIfIdle(PREFLIGHT_TIMEOUT_MS) + updateCaptchaTimers() + } + stage == "SESSION_WAIT" -> status = "Проверяю сохранённый вход в ВК…" + stage == "PROFILE_WAIT" -> status = "Подтверждаю аккаунт ВК…" + stage == "ACCOUNT_WAIT" -> if (accountChoice == null) armPreflightTimeout(15_000L) + stage == "ACCOUNT_READY" -> armPreflightTimeout(PRE_MUTATION_TIMEOUT_MS) + message.startsWith("BRIDGE / CALL_SUPPORT /") && + message.endsWith("/ UNSUPPORTED") -> { + loading = false + error = true + status = "Этот способ не поддерживается. Перехожу к резервному…" + requestSafeFallback("CALL_UNSUPPORTED") + } + message.startsWith("BRIDGE / AUTH_REQUEST /") -> { + cancelPreflightTimeout() + waitingForConsent = true + loading = true + error = false + completedHashes = 0 + activeHashAttempt = 0 + preflightHandler.removeCallbacks(revealConsent) + preflightHandler.postDelayed(revealConsent, 900L) + status = "Подтвердите доступ на странице ВК. Он нужен только для создания ссылок." + } + message.startsWith("BRIDGE / AUTH_READY /") -> { + loading = true + error = false + webContentVisible = false + status = "Доступ подтверждён. Получаю четыре ВК-хеша…" + waitingForConsent = false + preflightHandler.removeCallbacks(revealConsent) + armPreflightTimeout(PRE_MUTATION_TIMEOUT_MS) + } + message.startsWith("BRIDGE / AUTH_FAILED /") -> { + cancelPreflightTimeout() + loading = false + error = true + activeHashAttempt = 0 + status = "Доступ не подтверждён. Перехожу к резервному способу…" + requestSafeFallback("AUTH_FAILED") + } + message.startsWith("BRIDGE / CLAIM_BUSY /") -> { + cancelPreflightTimeout() + loading = false + error = true + activeHashAttempt = 0 + status = "Первичный вход ВК перезапустился. Перехожу к резервному способу…" + requestSafeFallback("CLAIM_BUSY") + } + message.startsWith("BRIDGE / CLAIM_BLOCKED /") -> { + cancelPreflightTimeout() + loading = false + error = true + activeHashAttempt = 0 + status = "Запрос ВК уже отправлен. Автоматический повтор отключён." + } + message.startsWith("BRIDGE / CLAIM_WAIT /") -> { + loading = true + error = false + webContentVisible = false + status = "Завершаю вход и подготавливаю получение…" + armPreflightTimeout(PRE_MUTATION_TIMEOUT_MS) + } + message.startsWith("BRIDGE / CLAIM_READY /") -> { + loading = true + error = false + webContentVisible = false + status = "Получение подготовлено. Создаю первую ссылку…" + armPreflightTimeout(PRE_MUTATION_TIMEOUT_MS) + } + message.startsWith("BRIDGE / AUTO_READY /") -> { + loading = true + error = false + completedHashes = 0 + activeHashAttempt = 1 + status = "Вход выполнен. Получаю четыре ВК-хеша…" + armPreflightTimeout(PRE_MUTATION_TIMEOUT_MS) + } + message.startsWith("BRIDGE / PERMIT_WAIT_") -> { + // Once a permit request is in flight its outcome may be unknown. + // Do not start another engine, even if CALL_SENT has not arrived. + cancelPreflightTimeout() + activeHashAttempt = stage.substringAfterLast('_').toIntOrNull() ?: 1 + loading = true + status = "Подготавливаю ссылку $activeHashAttempt из 4…" + armMutationTimeout() + } + message.startsWith("BRIDGE / CALL_SENT_") -> { + cancelPreflightTimeout() + vkMutationStarted = true + loading = true + error = false + val attempt = message.substringAfter("CALL_SENT_").substringBefore('/').trim() + .toIntOrNull()?.coerceIn(1, 4) + activeHashAttempt = attempt ?: 0 + armMutationTimeout() + status = if (attempt == null) { + "Создаю ссылку ВК Звонков…" + } else { + "Создаю ссылку $attempt из 4…" + } + } + message.startsWith("BRIDGE / CALL_HASH_") -> { + armMutationTimeout() + val count = message.substringAfterLast('/').trim().toIntOrNull()?.coerceIn(1, 4) + if (count != null) { + completedHashes = count + activeHashAttempt = if (count < 4) count + 1 else 0 + } + status = if (count == null) "Ссылка ВК Звонков получена…" else "Получено $count из 4 ВК-хешей…" + } + message.startsWith("BRIDGE / PREP_FAILED /") || + message.startsWith("BRIDGE / FLOW_FAILED /") -> { + cancelPreflightTimeout() + preflightHandler.removeCallbacks(revealConsent) + waitingForConsent = false + webContentVisible = false + loading = false + error = true + status = if (flowGuard.mutationPossible) { + "Получение остановлено. Новые запросы автоматически не отправляются." + } else { + "Не удалось подготовить получение. Открываю резервный способ…" + } + requestSafeFallback("PREPARATION_FAILED") + } + message.startsWith("BRIDGE / DELIVER_WAIT /") -> { + armMutationTimeout() + loading = true + status = "Сохраняю четыре ВК-хеша в профиле…" + } + message.startsWith("BRIDGE / DELIVER_FAILED /") -> { + loading = false + error = true + status = "Хеши созданы, но не переданы. Повторите только сохранение на странице ВК." + webContentVisible = true + } + message.startsWith("BRIDGE / CALL_TIMEOUT_") -> { + loading = false + error = true + activeHashAttempt = 0 + status = "ВК не ответил на создание ссылки. Закройте окно и повторите позже." + } + message.startsWith("BRIDGE / CALL_FAILED_") -> { + loading = false + error = true + activeHashAttempt = 0 + status = if (message.split('/').getOrNull(3)?.trim() == "14") + "Проверка ВК не завершена. Повторные запросы не отправляются." + else "ВК отклонил создание ссылки. Подробности сохранены в журнале." + } + message.startsWith("BRIDGE / CALL_INVALID_") || + message.startsWith("BRIDGE / CALL_EMPTY_") -> { + loading = false + error = true + activeHashAttempt = 0 + status = "ВК не вернул ссылку звонка. Новая попытка автоматически не запускается." + } + } + } + + private fun requestSafeFallback(reason: String) { + if (captchaVisible) { + loading = false + error = true + webContentVisible = true + status = "Не удалось продолжить проверку ВК. Ошибка на странице оставлена видимой; автоматический повтор отключён." + cancelPreflightTimeout() + log("CAPTCHA / ERROR") + return + } + if (!flowGuard.canFallback || vkMutationStarted || fallbackRequested || isFinishing || isDestroyed) return + cancelPreflightTimeout() + preflightHandler.removeCallbacks(revealConsent) + fallbackRequested = true + flowGuard.close() + webContentVisible = false + loading = true + error = false + waitingForConsent = false + status = "Открываю резервный способ…" + // Destroy the old renderer before notifying the next engine. A delayed + // token/claim response must not create links after the handoff. + disposePage() + log("SAFE_FALLBACK / ${reason.take(80)}") + receiver?.send(RESULT_SAFE_FALLBACK, Bundle().apply { + putString("reason", reason.take(80)) + }) + // The replacement Activity closes this presentation once it is visible. + // Until then keep one compact card, instead of flashing the profile UI. + } + + private fun logoutVkSession() { + if (logoutInProgress) return + val canLoginAgain = !flowGuard.mutationPossible && !fallbackRequested + cancelPreflightTimeout() + preflightHandler.removeCallbacks(revealConsent) + waitingForConsent = false + logoutInProgress = true + flowGuard.close() + continueAccount = null + accountChoice = null + confirmedAccountId = null + disposePage() + webContentVisible = false + loading = true + error = false + completedHashes = 0 + activeHashAttempt = 0 + status = "Выхожу из ВК…" + lifecycleScope.launch { + try { + vkSession.logout { VkLocalSession.clearWebData() } + canLogout = false + log("LOGOUT / COMPLETE") + // A committed or ambiguous request cannot be reset by logging out. + if (canLoginAgain && !isFinishing && !isDestroyed) { + flowGuard = ModernVkFlowGuard() + logoutInProgress = false + loading = true + openPreparedContainer() + } else { + receiver?.send(RESULT_CANCEL, Bundle()) + finish() + } + } catch (timeout: TimeoutCancellationException) { + showLogoutFailure() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + showLogoutFailure() + } finally { + logoutInProgress = false + } + } + } + + private fun showLogoutFailure() { + loading = false + error = true + canLogout = true + status = "Не удалось полностью выйти из ВК. Нажмите «Выйти из ВК» ещё раз. Получение остановлено." + log("LOGOUT / FAILED") + } + + private fun armPreflightTimeout(delayMillis: Long = PREFLIGHT_TIMEOUT_MS) { + preflightTimeout.arm(delayMillis) + updateCaptchaTimers() + } + + private fun armMutationTimeout() { + mutationTimeout.arm(90_000L) + updateCaptchaTimers() + } + + private fun cancelPreflightTimeout() { + preflightTimeout.cancel() + } + + private fun updateCaptchaTimers() { + preflightTimeout.pause(captchaVisible) + mutationTimeout.pause(captchaVisible) + } + + private fun onCaptchaState(state: VkCaptchaPolicy.State) { + if (page == null || fallbackRequested || logoutInProgress || isFinishing) return + captchaState = state + if (state == VkCaptchaPolicy.State.IDLE && captchaObserverSupported) captchaPageVisible = false + updateCaptchaTimers() + if (state != VkCaptchaPolicy.State.IDLE) loading = false + log("CAPTCHA / ${state.name}") + } + + override fun onResume() { super.onResume(); foreground = true } + override fun onPause() { foreground = false; captcha?.userInteraction(); super.onPause() } + + private fun log(message: String) { + receiver?.send(RESULT_LOG, Bundle().apply { putString("message", message.take(240)) }) + } + + override fun onDestroy() { + mutationTimeout.cancel() + cancelPreflightTimeout() + preflightHandler.removeCallbacks(revealConsent) + if (receiverRegistered) runCatching { unregisterReceiver(finishReceiver) } + CookieManager.getInstance().flush() + disposePage() + super.onDestroy() + } + + override fun finish() { + super.finish() + @Suppress("DEPRECATION") + overridePendingTransition(0, 0) + } + + private fun disposePage() { + preflightTimeout.cancel() + mutationTimeout.cancel() + val previous = page + page = null // Ignore callbacks synchronously emitted by stopLoading/close. + captcha?.close(); captcha = null + captchaState = VkCaptchaPolicy.State.IDLE + captchaPageVisible = false + continueAccount = null + accountChoice = null + previous?.apply { + webChromeClient = null + webViewClient = WebViewClient() + stopLoading() + (parent as? android.view.ViewGroup)?.removeView(this) + destroy() + } + } + + companion object { + private const val EXTRA_URL = "url" + private const val EXTRA_SESSION = "session" + private const val EXTRA_RECEIVER = "receiver" + private const val EXTRA_HAS_COMPLETE_VALUES = "has_complete_values" + private const val EXTRA_SUCCESS = "success" + private const val FINISH_ACTION = "com.wdtt.plus.vk.MODERN_VK_FINISH" + private const val HANDOFF_ACTION = "com.wdtt.plus.vk.MODERN_VK_HANDOFF" + private const val DESKTOP_LANDING_ZOOM = 1.7f + private const val PREFLIGHT_TIMEOUT_MS = 75_000L + private const val PRE_MUTATION_TIMEOUT_MS = 25_000L + private const val RESULT_CANCEL = 0 + private const val RESULT_LOG = 2 + private const val RESULT_SAFE_FALLBACK = 3 + } +} + +@Composable +internal fun VkHashProgressPanel( + completed: Int, + activeAttempt: Int, + loading: Boolean, + error: Boolean, +) { + val pulse by rememberInfiniteTransition(label = "vk-hash-progress").animateFloat( + initialValue = 0.38f, + targetValue = 1f, + animationSpec = infiniteRepeatable( + animation = tween(durationMillis = 720), + repeatMode = RepeatMode.Reverse, + ), + label = "active-segment", + ) + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surfaceContainerHighest, + ) { + Column( + modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Surface( + modifier = Modifier.size(42.dp), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.primaryContainer, + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + Icons.Default.Key, + contentDescription = null, + modifier = Modifier.size(22.dp), + tint = MaterialTheme.colorScheme.onPrimaryContainer, + ) + } + } + Column(Modifier.weight(1f)) { + Text( + "Получение ВК-хешей", + style = MaterialTheme.typography.titleSmall, + ) + Text( + "Четыре ссылки создаются по очереди", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(7.dp), + ) { + repeat(4) { index -> + val number = index + 1 + val segmentColor = when { + index < completed -> MaterialTheme.colorScheme.primary + error && number == activeAttempt -> MaterialTheme.colorScheme.error + loading && number == activeAttempt -> + MaterialTheme.colorScheme.primary.copy(alpha = pulse) + else -> MaterialTheme.colorScheme.outlineVariant + } + Box( + Modifier.weight(1f).height(9.dp) + .clip(RoundedCornerShape(50)) + .background(segmentColor), + ) + } + } + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text( + when { + completed == 4 -> "Готово" + error -> "Получение остановлено" + loading && activeAttempt > 0 -> "Получаю ссылку $activeAttempt из 4" + else -> "Подготавливаю получение" + }, + style = MaterialTheme.typography.bodyMedium, + color = if (error) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + modifier = Modifier.weight(1f), + ) + Text( + "$completed / 4", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + } + } +} + +internal object ModernVkContainerProtocol { + private const val DIAGNOSTIC_PREFIX = "[WDTT_VK_DIAG]" + const val DESKTOP_USER_AGENT = + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " + + "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" + + /** Validate the provider destination, then open it byte-for-byte. */ + fun launchUrl(raw: String): String { + val source = URI(raw) + require(raw.length <= 4096 && source.scheme == "https" && source.host == "vk.ru") + require(source.rawUserInfo == null && source.port in setOf(-1, 443)) + require(source.path == "/app54670800") + return raw + } + + fun allowedNavigation(raw: String): Boolean { + val uri = runCatching { URI(raw) }.getOrNull() ?: return false + if (uri.scheme != "https" || uri.rawUserInfo != null || uri.port !in setOf(-1, 443)) return false + val host = uri.host?.lowercase().orEmpty() + return host == "vk.ru" || host.endsWith(".vk.ru") || + host == "vk.com" || host.endsWith(".vk.com") || + host == "wdttplus.ru" || host.endsWith(".wdttplus.ru") + } + + fun validLoginUrl(raw: String): Boolean = runCatching { + val uri = URI(raw) + raw.length <= 4096 && uri.scheme == "https" && uri.host == "m.vk.ru" && + uri.rawPath == "/login" && uri.rawUserInfo == null && uri.port in setOf(-1, 443) + }.getOrDefault(false) + + fun isMiniAppLanding(raw: String): Boolean { + val uri = runCatching { URI(raw) }.getOrNull() ?: return false + val host = uri.host?.lowercase().orEmpty() + return uri.scheme == "https" && + (host == "vk.ru" || host == "www.vk.ru" || host == "m.vk.ru") && + uri.path == "/app54670800" + } + + fun isAuthenticationPage(raw: String): Boolean { + val uri = runCatching { URI(raw) }.getOrNull() ?: return false + val host = uri.host?.lowercase().orEmpty() + if (uri.scheme != "https") return false + return host == "id.vk.ru" || host.endsWith(".id.vk.ru") || + host == "id.vk.com" || host.endsWith(".id.vk.com") || + host == "login.vk.ru" || host.endsWith(".login.vk.ru") || + host == "login.vk.com" || host.endsWith(".login.vk.com") || + ((host == "m.vk.ru" || host == "vk.ru" || host == "www.vk.ru") && + uri.path.orEmpty().startsWith("/login")) + } + + fun shouldPromoteAuthenticatedMobilePage(raw: String): Boolean { + val uri = runCatching { URI(raw) }.getOrNull() ?: return false + if (uri.scheme != "https" || uri.host?.lowercase() != "m.vk.ru") return false + val path = uri.path.orEmpty().trimEnd('/') + return path.isEmpty() || path == "/feed" + } + + fun shouldFocusDesktopLanding(raw: String): Boolean { + val uri = runCatching { URI(raw) }.getOrNull() ?: return false + val host = uri.host?.lowercase().orEmpty() + return uri.scheme == "https" && + (host == "vk.ru" || host == "www.vk.ru") && + uri.path == "/app54670800" + } + + fun diagnosticFromConsole(raw: String): String? { + if (!raw.startsWith(DIAGNOSTIC_PREFIX)) return null + val payload = raw.removePrefix(DIAGNOSTIC_PREFIX).trim() + .replace(Regex("https?://\\S+", RegexOption.IGNORE_CASE), "URL") + .replace(Regex("[A-Za-z0-9_-]{16,}"), "VALUE") + .replace(Regex("[\\r\\n\\t]+"), " ") + .take(180) + if (payload.isBlank()) return null + return "BRIDGE / $payload" + } + + fun isVkTelemetryHost(host: String): Boolean = + host.equals("akashi.vk-portal.net", ignoreCase = true) + + fun initialLaunchUrl( + desktopUrl: String, + mobileLoginUrl: String, + hasRememberedSession: Boolean, + ): String = if (hasRememberedSession) desktopUrl else mobileLoginUrl + + fun isCurrentPage(current: String?, completed: String?): Boolean = + !current.isNullOrBlank() && !completed.isNullOrBlank() && + current.substringBefore('#') == completed.substringBefore('#') + + +} diff --git a/app/src/main/java/com/wdtt/plus/vk/ModernVkFlowGuard.kt b/app/src/main/java/com/wdtt/plus/vk/ModernVkFlowGuard.kt new file mode 100644 index 0000000..c4b51ea --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/ModernVkFlowGuard.kt @@ -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 } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkAccountActions.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkAccountActions.kt new file mode 100644 index 0000000..d195e48 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkAccountActions.kt @@ -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, + ): Boolean { + if (busy) return false + if (journalPhases.any { it !in setOf("received", "uploaded") }) return false + return hasError || journalPhases.isNotEmpty() + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkActivity.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkActivity.kt new file mode 100644 index 0000000..cc6c326 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkActivity.kt @@ -0,0 +1,1004 @@ +package com.wdtt.plus.vk + +import android.annotation.SuppressLint +import android.content.* +import android.net.* +import android.net.http.SslError +import android.os.* +import android.view.WindowManager +import android.webkit.* +import androidx.activity.ComponentActivity +import androidx.activity.OnBackPressedCallback +import androidx.activity.compose.setContent +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.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.lifecycle.lifecycleScope +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature +import com.wdtt.plus.SecureStringStore +import com.wdtt.plus.RemoteDocumentGateway +import com.wdtt.plus.WDTTTheme +import kotlinx.coroutines.* +import okhttp3.OkHttpClient +import org.json.JSONArray +import org.json.JSONObject +import java.io.ByteArrayInputStream + +/** Official login and four explicit local Calls requests, entirely in our task. */ +open class NativeVkActivity : ComponentActivity() { + companion object { + private var current = java.lang.ref.WeakReference(null) + private val SAFE_FALLBACK_STAGES = setOf( + "BROKER_LOST", + "BROKER_BIND", + "PREPARE", + "IDENTITY", + "NETWORK", + "NETWORK_LOST", + "LOGIN", + "WEB_TLS", + "WEB_PAGE", + "WEB_RENDER", + "OAUTH_CALLBACK", + "VK_ID_CALLBACK", + "RESTORE", + ) + } + private lateinit var localProfile: com.wdtt.plus.LocalContinuationProfile + private val prefs by lazy { getSharedPreferences("native-vk-ledger-profile-${localProfile.index}", MODE_PRIVATE) } + private val tokenPrefs by lazy { VkLocalSession.nativeTokenPreferences(this, localProfile) } + private val vkSession by lazy { VkLocalSession.forContext(this, localProfile) } + private val secrets by lazy { SecureStringStore(this) } + private val cm by lazy { getSystemService(ConnectivityManager::class.java) } + private var key = "" + private var device = "" + private var expires = 0L + private var hasCompleteLocalValues = false + private var receiver: ResultReceiver? = null + private var broker: Messenger? = null + private var sequence = 0 + private val replies = mutableMapOf>() + private var bound = false + private var callback: ConnectivityManager.NetworkCallback? = null + private var network: Network? = null + private var http: OkHttpClient? = null + private var useDefaultNetwork = false + private var tokenRoute = "" + private var operationStage = "PREPARE" + private val pendingLogs = ArrayDeque() + private var foreground = false + private var disposed = false + private var page by mutableStateOf(null) + private var mainFrameUrl = "" + private var origin by mutableStateOf("") + private var status by mutableStateOf("Подготовка…") + private var hasError by mutableStateOf(false) + private var busy by mutableStateOf(true) + private var authorized by mutableStateOf(false) + private var completed by mutableIntStateOf(0) + private var activeHashAttempt by mutableIntStateOf(0) + private var confirmClose by mutableStateOf(false) + private var token: VkApiProtocol.Token? = null + private var requireAccountChoice = false + private var confirmedAccountToken: String? = null + private var offeredAccountToken: String? = null + private var accountChoice by mutableStateOf(null) + private var loginStage by mutableStateOf(LoginStage.NONE) + private var vkIdAuth: VkApiProtocol.AuthAttempt? = null + private var miniAppAuth: VkOAuthProtocol.AuthAttempt? = null + private var journal = JSONArray() + private var prepared = false + private var replacementConfirmed by mutableStateOf(false) + private var operationJob: Job? = null + private var networkLabel by mutableStateOf("") + private var fallbackDispatched = false + private var captcha: VkInPlaceCaptcha? = null + private var captchaState by mutableStateOf(VkCaptchaPolicy.State.IDLE) + private var apiCaptchaResult: CompletableDeferred? = null + private val inbox = Messenger(object : Handler(Looper.getMainLooper()) { + override fun handleMessage(message: Message) { + val pending = replies.remove(message.arg1) ?: return + val answer = runCatching { JSONObject(message.data.getString("body").orEmpty()) } + answer.fold(pending::complete) { pending.completeExceptionally(IllegalStateException("Повреждён ответ WDTT Plus.")) } + } + }) + private val connection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, service: IBinder) { + broker = Messenger(service) + flushLogs() + if (!prepared && foreground) work { prepare() } + } + override fun onServiceDisconnected(name: ComponentName) { + broker = null + replies.values.forEach { it.completeExceptionally(IllegalStateException("Служебный канал прерван. Новые звонки не запускаются.")) } + replies.clear() + fail("BROKER_LOST", IllegalStateException(), "Соединение прервано. Попробуйте ещё раз.") + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val previous = current.get() + if (previous != null && !previous.isFinishing && !previous.isDestroyed) { + @Suppress("DEPRECATION") + val reply = intent.getParcelableExtra("receiver") + reply?.send(0, Bundle()); finish(); return + } + current = java.lang.ref.WeakReference(this) + // Owner explicitly requested screenshots for diagnosing this prerelease. + window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) + key = intent.getStringExtra("key").orEmpty() + device = intent.getStringExtra("device").orEmpty() + expires = intent.getLongExtra("expires", 0) + hasCompleteLocalValues = intent.getBooleanExtra("has_complete_values", false) + @Suppress("DEPRECATION") + receiver = intent.getParcelableExtra("receiver") + if (runCatching { NativeVkProtocol.payload(key, device, "prepare") }.isFailure || expires <= System.currentTimeMillis() / 1000) { + receiver?.send(3, Bundle().apply { putString("reason", "INVALID_SESSION") }) + finish(); return + } + setContent { WDTTTheme { ProfileSessionPreparation(status, hasError) { + receiver?.send(0, Bundle()); finish() + } } } + status = "Подготавливаю вход для выбранного профиля…" + lifecycleScope.launch { + try { + localProfile = ProfileWebSessionScope.read(this@NativeVkActivity, intent) + vkSession.prepareProfile(localProfile.identity) { VkLocalSession.clearWebData() } + if (!isFinishing && !isDestroyed) openPreparedSession() + } catch (timeout: TimeoutCancellationException) { + hasError = true + status = "Не удалось подготовить отдельный сеанс профиля. Закройте окно и повторите." + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + hasError = true + status = "Не удалось подготовить отдельный сеанс профиля. Получение не запускалось." + } + } + } + + private fun openPreparedSession() { + restore() + requireAccountChoice = VkAccountChoicePolicy.required(vkSession.remembered, + CookieManager.getInstance().hasCookies(), token != null) + onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { closeRequested() } + }) + setContent { WDTTTheme { + Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = .55f)).systemBarsPadding().imePadding(), + contentAlignment = Alignment.Center) { + val loginPageOpen = page != null + val panelModifier = if (loginPageOpen) { + Modifier.fillMaxSize().padding(horizontal = 1.dp, vertical = 6.dp) + } else { + Modifier.fillMaxWidth().wrapContentHeight().padding(horizontal = 8.dp) + } + Surface( + panelModifier, + shape = RoundedCornerShape(if (loginPageOpen) 22.dp else 28.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh) { + Column( + Modifier.padding( + horizontal = if (loginPageOpen) 8.dp else 18.dp, + vertical = if (loginPageOpen) 12.dp else 18.dp, + ), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + val journalPhases = (0 until journal.length()).map { + journal.optJSONObject(it)?.optString("phase").orEmpty() + } + val acquireFallbackAvailable = NativeVkAccountActions.acquireFallbackAvailable( + busy = busy, + hasError = hasError, + journalPhases = journalPhases, + ) + val replacementConfirmationNeeded = + NativeVkAccountActions.replacementConfirmationNeeded( + hasCompleteLocalValues = hasCompleteLocalValues, + replacementConfirmed = replacementConfirmed, + hasRecoveredOperation = journal.length() > 0, + ) + val accountActions = NativeVkAccountActions.forState( + loginPageOpen = loginPageOpen, + authorized = authorized, + hasToken = token != null, + acquireFallbackAvailable = acquireFallbackAvailable, + replacementConfirmationNeeded = replacementConfirmationNeeded, + logoutPending = vkSession.logoutPending, + ) + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(when (loginStage) { + LoginStage.VK_ID -> "Вход в ВК" + LoginStage.MINI_APP -> "Подтверждение доступа" + LoginStage.CAPTCHA -> "Проверка ВК" + LoginStage.NONE -> "Получение ВК-хешей" + }, style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f)) + IconButton(onClick = { closeRequested() }) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + if (loginPageOpen) { + Text(when (loginStage) { + LoginStage.VK_ID -> "Войдите в аккаунт ВК на официальной странице." + LoginStage.MINI_APP -> "Подтвердите доступ в уже открытой сессии ВК." + LoginStage.CAPTCHA -> "Пройдите проверку. Получение продолжится в этом же профиле." + LoginStage.NONE -> "Официальная страница ВК" + }, style = MaterialTheme.typography.bodyMedium) + Surface(shape = RoundedCornerShape(50), color = MaterialTheme.colorScheme.surfaceContainerHighest) { + Text("Официальная страница ВК · $origin", + modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp), + style = MaterialTheme.typography.labelMedium) + } + if (captchaState != VkCaptchaPolicy.State.IDLE && !hasError) { + Text(VkCaptchaPolicy.message(captchaState), style = MaterialTheme.typography.bodySmall) + } + if (hasError) Text(status, color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall) + AndroidView(factory = { page!! }, modifier = Modifier.fillMaxWidth().weight(1f).clip(RoundedCornerShape(18.dp))) + } else { + Surface( + shape = RoundedCornerShape(50), + color = MaterialTheme.colorScheme.surfaceContainerHighest, + ) { + Text( + status, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp), + style = MaterialTheme.typography.labelMedium, + color = if (hasError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface, + ) + } + if (accountChoice != null) { + VkAccountChoicePanel(accountChoice!!, !busy, + onContinue = { + confirmedAccountToken = offeredAccountToken + accountChoice = null + work { continuePreparedFlow(openWindow = true) } + }, + onLogout = { work { logout() } }) + } else { + VkHashProgressPanel( + completed = if (replacementConfirmationNeeded) 4 else completed, + activeAttempt = activeHashAttempt, + loading = busy && !replacementConfirmationNeeded, + error = hasError, + ) + if (accountActions.showReplace) Button( + onClick = { + replacementConfirmed = true + work { continuePreparedFlow(openWindow = true) } + }, + enabled = !busy, + modifier = Modifier.fillMaxWidth(), + ) { + Text("Получить новые ВК-хеши") + } else if (accountActions.showAcquire) Button(onClick = { work { continuePreparedFlow(openWindow = true) } }, enabled = !busy, + modifier = Modifier.fillMaxWidth()) { + Text(if (journal.length() == 0) "Повторить получение" else "Продолжить безопасно") + } else if (accountActions.showLogin) Button(onClick = { work { if (!prepared) prepare(false); openLogin() } }, enabled = !busy, + modifier = Modifier.fillMaxWidth()) { Text("Войти в ВК") } + if (networkLabel.isNotBlank()) Text(networkLabel, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + if (accountActions.showLogout && accountChoice == null) { + TextButton(onClick = { work { logout() } }, enabled = !busy) { + Text("Выйти из ВК") + } + } + } + } + } + if (confirmClose) AlertDialog(onDismissRequest = { confirmClose = false }, + title = { Text("Закрыть получение?") }, + text = { Text("Уже отправленный запрос ВК нельзя отменить закрытием окна. Автоповтора не будет. Если ссылки ещё не переданы, останьтесь здесь и повторите передачу.") }, + confirmButton = { TextButton(onClick = { receiver?.send(0, Bundle()); finish() }) { Text("Закрыть") } }, + dismissButton = { TextButton(onClick = { confirmClose = false }) { Text("Назад") } }) + } } + bound = bindService(Intent(this, NativeVkBrokerService::class.java), connection, BIND_AUTO_CREATE) + if (!bound) { busy = false; fail("BROKER_BIND", IllegalStateException(), "Не удалось подключиться. Попробуйте ещё раз.") } + } + + override fun onResume() { + super.onResume() + window.decorView.post { + sendBroadcast(Intent("com.wdtt.plus.vk.MODERN_VK_HANDOFF").setPackage(packageName)) + } + foreground = true + if (!prepared && broker != null) work { prepare() } + } + override fun onPause() { foreground = false; captcha?.userInteraction(); super.onPause() } + private fun closeRequested() { + if (busy || journal.length() > 0) confirmClose = true + else { receiver?.send(0, Bundle()); finish() } + } + private fun work(block: suspend () -> Unit) { + // Clicks and a reconnecting bound service must not start overlapping login work. + if (disposed || operationJob?.isActive == true) return + busy = true; hasError = false + operationJob = lifecycleScope.launch { + try { block() } + catch (error: TimeoutCancellationException) { + fail(operationStage, error, "Не удалось дождаться ответа. Подробности — в «Логах».") + } + catch (cancelled: CancellationException) { throw cancelled } + catch (error: Exception) { + fail(operationStage, error, if (operationStage == "CAPTCHA") + "ВК запросил проверку, но не удалось её завершить. Повторные запросы не отправляются." + else if (operationStage == "CALL") + "ВК не вернул ссылку. Подробности — в «Логах»." + else if (operationStage in setOf("PREPARE", "IDENTITY", "PERMIT", "UPLOAD", "FINISH")) + "Не удалось связаться с WDTT Plus. Вход ВК сохранён — повторите позже." + else "Не удалось завершить действие. Подробности — в «Логах».") + } finally { busy = false } + } + } + private fun record(stage: String, error: Throwable) { + pendingLogs.addLast(NativeVkFeedback.diagnostic(stage, error)) + while (pendingLogs.size > 32) pendingLogs.removeFirst() + flushLogs() + } + private fun flushLogs() { + val service = broker ?: return + while (pendingLogs.isNotEmpty()) { + try { + service.send(Message.obtain().apply { + what = 2; data = Bundle().apply { putString("code", pendingLogs.first()) } + }) + pendingLogs.removeFirst() + } catch (_: RemoteException) { return } + } + } + private fun fail(stage: String, error: Throwable, message: String) { + record(stage, error); hasError = true; status = message + if (captchaState == VkCaptchaPolicy.State.IDLE && journal.length() == 0 && completed == 0 && stage in SAFE_FALLBACK_STAGES) { + dispatchSafeFallback(stage) + } + } + private fun dispatchSafeFallback(stage: String) { + if (fallbackDispatched || disposed || isFinishing || isDestroyed) return + fallbackDispatched = true + receiver?.send(3, Bundle().apply { putString("reason", stage.take(80)) }) + finish() + } + private suspend fun rpc(op: String, extra: JSONObject = JSONObject()): JSONObject { + check(!disposed && expires > System.currentTimeMillis() / 1000) { "Разрешение устарело. Новые звонки не запускаются." } + val service = broker ?: error("Служебный канал ещё не подключён.") + val raw = NativeVkProtocol.payload(key, device, op, extra) + val id = ++sequence + val result = CompletableDeferred() + replies[id] = result + try { + service.send(Message.obtain().apply { + what = 1; arg1 = id; replyTo = inbox + data = Bundle().apply { putString("body", raw) } + }) + val response = withTimeout(35_000) { result.await() } + if (response.has("error")) { + record("BACKEND_${op.uppercase()}", IllegalStateException("HTTP_${response.optInt("http", 500)}")) + error(response.getString("error")) + } + return response + } finally { replies.remove(id) } + } + private suspend fun prepare(openWindow: Boolean = true) { + if (vkSession.logoutPending) { + operationStage = "LOGOUT" + token = null; tokenRoute = ""; authorized = false + vkSession.finishPendingLogout { VkLocalSession.clearWebData() } + } + if (journal.length() > 0) { + ensureBackendPrepared() + // A recovered operation may only upload known results. No automatic mutation. + authorized = true + val phases = (0 until journal.length()).map { + journal.getJSONObject(it).optString("phase") + } + if (phases.any { it !in setOf("received", "uploaded") }) { + hasError = true + status = "Результат предыдущего запроса неизвестен. Автоповтор отключён; подробности — в «Логах»." + } else { + status = "Есть сохранённые результаты. Продолжение не повторит уже выполненные запросы." + } + } else if (NativeVkAccountActions.replacementConfirmationNeeded( + hasCompleteLocalValues = hasCompleteLocalValues, + replacementConfirmed = replacementConfirmed, + hasRecoveredOperation = false, + )) { + authorized = false + status = "В профиле уже сохранены четыре хеша. Новое получение заменит их." + } else if (token != null && token!!.expiresAt > System.currentTimeMillis()) { + ensureBackendPrepared() + continuePreparedFlow(openWindow) + } else { + status = "Войдите в аккаунт ВК внутри этого окна." + if (openWindow) openLogin() + } + } + private suspend fun ensureBackendPrepared() { + if (prepared) return + operationStage = "PREPARE" + rpc("prepare") + prepared = true + } + private suspend fun continuePreparedFlow(openWindow: Boolean) { + if (token != null && token!!.expiresAt > System.currentTimeMillis()) { + connect() + if (NativeVkRoutePolicy.needsLogin(tokenRoute, routeStamp())) { + authorized = false + if (openWindow) openLogin() + } else { + authorizeAndGenerate() + } + } else { + status = "Войдите в аккаунт ВК внутри этого окна." + if (openWindow) openLogin() + } + } + private suspend fun authorizeToken() { + check(!vkSession.logoutPending) { "LOGOUT_PENDING" } + operationStage = "IDENTITY" + val saved = token ?: error("Войдите в ВК.") + check(saved.expiresAt > System.currentTimeMillis()) { "Сессия истекла. Войдите в ВК снова." } + status = "Завершаем вход…" + val parts = saved.value.chunked(96) + parts.forEachIndexed { index, part -> + val reply = rpc("auth", JSONObject().put("i", index).put("n", parts.size).put("v", part)) + if (index == parts.lastIndex) check(reply.optString("state") == "authorized") + } + authorized = true + status = "Можно получать хеши" + } + private suspend fun authorizeAndGenerate() { + if (journal.length() == 0 && requireAccountChoice && confirmedAccountToken != token?.value) { + operationStage = "ACCOUNT" + status = "Проверяю аккаунт ВК этого профиля…" + val saved = token ?: error("Войдите в ВК.") + val client = http ?: error("Соединение с ВК потеряно.") + val account = withContext(Dispatchers.IO) { + VkAccountIdentity.fromApi(VkHttp.post(client, VkApiProtocol.USER_ENDPOINT, + mapOf("access_token" to saved.value, "v" to "5.199"))) + } + check(token === saved && !vkSession.logoutPending) + offeredAccountToken = saved.value + accountChoice = account + status = "Подтвердите аккаунт перед получением ВК-хешей." + return + } + ensureBackendPrepared() + authorizeToken() + status = "Вход выполнен. Получаем четыре хеша…" + generate() + } + private suspend fun connect() { + if (network != null && http != null) return + operationStage = "NETWORK" + try { selectNetwork(useDefaultNetwork) } + catch (cancelled: CancellationException) { throw cancelled } + catch (error: Exception) { + if (!NativeVkRoutePolicy.mayFallback(useDefaultNetwork, journal.length())) throw error + record("DIRECT_FALLBACK", error) + useDefaultNetwork = true + selectNetwork(true) + } + } + private fun routeStamp(): String { + val boot = android.provider.Settings.Global.getInt(contentResolver, + android.provider.Settings.Global.BOOT_COUNT, -1) + return "$boot:${network?.networkHandle}:${if (useDefaultNetwork) "default" else "direct"}" + } + private suspend fun openLogin() { + check(!vkSession.logoutPending) { "LOGOUT_PENDING" } + connect() + try { pinLoginNetwork() } + catch (error: Exception) { + if (!NativeVkRoutePolicy.mayFallback(useDefaultNetwork, journal.length())) throw error + record("WEB_FALLBACK", error) + releaseNetwork() + useDefaultNetwork = true + selectNetwork(true) + pinLoginNetwork() + } + operationStage = "LOGIN" + login() + } + private suspend fun selectNetwork(defaultNetwork: Boolean) { + status = "Подключаемся…" + val ready = CompletableDeferred() + val gate = NativeVkNetworkGate(Build.VERSION.SDK_INT >= 29) + var kind = "сеть телефона" + var failure = "Android не сообщил о готовой прямой сети (NET_WAIT)." + var pendingNetwork: Network? = null + val cb = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(value: Network) = runOnUiThread { + if (disposed || callback !== this) return@runOnUiThread + if (network != null && network != value) { + // requestNetwork now tracks the new best network; old onLost is not guaranteed. + dropNetwork("Сеть телефона сменилась. Продолжите вход в этом окне; автоповтора запросов ВК нет.") + } + gate.available(value) + } + override fun onCapabilitiesChanged(value: Network, caps: NetworkCapabilities) = runOnUiThread { + if (disposed || callback !== this) return@runOnUiThread + gate.capabilities(value, caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN), + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) + kind = when { + caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> "VPN" + caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "Wi-Fi" + else -> "мобильная сеть" + } + select(value) + } + override fun onLinkPropertiesChanged(value: Network, properties: LinkProperties) = runOnUiThread { + if (disposed || callback !== this) return@runOnUiThread + gate.linkProperties(value) + select(value) + } + override fun onBlockedStatusChanged(value: Network, blocked: Boolean) = runOnUiThread { + if (disposed || callback !== this) return@runOnUiThread + gate.blocked(value, blocked) + if (blocked) { + failure = "Android заблокировал прямую сеть для приложения (NET_BLOCKED). Проверьте системный запрет соединений без VPN." + if (network == value) dropNetwork(failure) + if (!ready.isCompleted) ready.completeExceptionally(IllegalStateException(failure)) + } else select(value) + } + private fun select(value: Network) { + if (disposed || callback !== this || network != null || ready.isCompleted || + !gate.ready(value) || pendingNetwork == value) return + pendingNetwork = value + val selectedKind = kind + val owner = this + lifecycleScope.launch { + var stage = "NET_HTTP" + try { + val client = withContext(Dispatchers.IO) { + VkHttp.client(value).also { + stage = "NET_SOCKET" + // No remote connection or VK operation. The socket factory + // explicitly binds this socket; no process-wide binding needed. + VkHttp.checkSocketAccess(it) + } + } + if (disposed || callback !== owner || ready.isCompleted || !gate.ready(value)) { + client.connectionPool.evictAll() + return@launch + } + // Publish both together only after a direct socket was permitted. + http = client; network = value + networkLabel = "Соединение: $selectedKind" + ready.complete(Unit) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + if (!disposed && callback === owner && !ready.isCompleted && gate.ready(value)) { + val errno = generateSequence(error) { it.cause } + .take(8).filterIsInstance().firstOrNull()?.errno + val detail = error.javaClass.simpleName + (errno?.let { " / errno=$it" } ?: "") + ready.completeExceptionally(IllegalStateException( + "$stage / $detail", error)) + } + } finally { + if (pendingNetwork == value) pendingNetwork = null + } + } + } + override fun onUnavailable() = runOnUiThread { + if (!disposed && callback === this) ready.completeExceptionally(IllegalStateException(failure)) + } + override fun onLost(value: Network) = runOnUiThread { + if (disposed || callback !== this) return@runOnUiThread + gate.lost(value) + if (network == value) dropNetwork("Сеть телефона потеряна. Запросы ВК автоматически не повторяются.") + } + } + callback?.let { runCatching { cm.unregisterNetworkCallback(it) } } + callback = cb + try { + if (defaultNetwork) cm.registerDefaultNetworkCallback(cb) + else cm.requestNetwork(NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), cb, 4_000) + try { withTimeout(if (defaultNetwork) 8_000 else 5_000) { ready.await() } } + catch (_: TimeoutCancellationException) { error(failure) } + } catch (error: SecurityException) { + throw IllegalStateException("Android запретил запрос прямой сети (NET_REQUEST / SecurityException).") + } finally { + if (network == null && callback === cb) { + callback = null + runCatching { cm.unregisterNetworkCallback(cb) } + } + } + } + + private fun dropNetwork(message: String) { + network = null; http?.dispatcher?.cancelAll(); http?.connectionPool?.evictAll(); http = null + closePage(); networkLabel = ""; + fail("NETWORK_LOST", IllegalStateException(message), "Соединение изменилось. Попробуйте ещё раз.") + } + private fun releaseNetwork() { + callback?.let { runCatching { cm.unregisterNetworkCallback(it) } }; callback = null + network = null; http?.dispatcher?.cancelAll(); http?.connectionPool?.evictAll(); http = null + closePage() + } + + private fun pinLoginNetwork() { + val direct = network ?: error("Сначала выберите сеть для ВК.") + // WebView has no per-request SocketFactory, unlike the Calls API client. + // Never render login on the default/VPN network if process binding fails. + val pinned = try { + cm.boundNetworkForProcess == direct || cm.bindProcessToNetwork(direct) + } catch (error: Exception) { + throw IllegalStateException("Не удалось привязать окно входа: NET_WEB_BIND / ${error.javaClass.simpleName}.") + } + check(pinned) { + "Android не разрешил привязку страницы входа (NET_WEB_BIND_FALSE). " + + if (authorized) "Сохранённая сессия не удалена. Можно вернуться к кнопке получения хешей." + else "Страница входа не открывалась; внешние приложения не запускаются." + } + } + @SuppressLint("SetJavaScriptEnabled") + private fun login(captchaUrl: String? = null) { + closePage() + if (captchaUrl == null) authorized = false + status = if (captchaUrl == null) "Войдите в аккаунт ВК" else "Пройдите проверку ВК в этом окне." + loginStage = if (captchaUrl == null) LoginStage.VK_ID else LoginStage.CAPTCHA + val attempt = if (captchaUrl == null) VkApiProtocol.newAttempt().also { vkIdAuth = it } else null + val view = WebView(this) + captcha = VkInPlaceCaptcha(view, { foreground && !confirmClose && !disposed }) { state -> + if (page === view && !disposed) { + captchaState = state + pendingLogs.addLast("CAPTCHA_${state.name} / READY") + flushLogs() + } + } + view.setOnTouchListener { _, event -> + if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN) captcha?.userInteraction() + false + } + view.settings.apply { + javaScriptEnabled = true; domStorageEnabled = true + allowFileAccess = false; allowContentAccess = false + mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW + useWideViewPort = true; loadWithOverviewMode = true + setSupportMultipleWindows(true); javaScriptCanOpenWindowsAutomatically = false + saveFormData = false + } + CookieManager.getInstance().apply { setAcceptCookie(true); setAcceptThirdPartyCookies(view, true) } + view.webChromeClient = object : WebChromeClient() { + override fun onCreateWindow(v: WebView?, d: Boolean, g: Boolean, m: Message?) = false + } + view.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(v: WebView, r: WebResourceRequest) = + navigate(v, r.url.toString(), r.isForMainFrame) + @Deprecated("Old WebView") + override fun shouldOverrideUrlLoading(v: WebView, url: String) = navigate(v, url, true) + override fun onPageStarted(v: WebView, url: String?, icon: android.graphics.Bitmap?) { + if (navigate(v, url.orEmpty(), true)) { if (page === v) v.stopLoading() } + else { + mainFrameUrl = url.orEmpty() + origin = Uri.parse(url).host.orEmpty() + } + } + override fun shouldInterceptRequest(v: WebView, r: WebResourceRequest): WebResourceResponse? { + if (r.url.scheme == "https" && !VkOAuthProtocol.blockResource(r.url.toString(), r.isForMainFrame) + && (!r.isForMainFrame || VkApiProtocol.allowedPage(r.url.toString()))) return null + return WebResourceResponse("text/plain", "UTF-8", ByteArrayInputStream(ByteArray(0))) + } + override fun onReceivedSslError(v: WebView, handler: SslErrorHandler, error: SslError) { + // Never accept an invalid certificate. WebView also reports TLS failures + // for subresources here; cancelling one optional resource must not tear + // down an otherwise valid VK login page. + handler.cancel() + if (disposed || page !== v) return + if (captcha?.active == true && (NativeVkSslPolicy.isMainFrameFailure(mainFrameUrl, error.url) || + VkCaptchaPolicy.captchaPage(error.url))) { + fail("CAPTCHA_WEB_TLS", IllegalStateException("WEB_TLS_MAIN"), + "Не удалось безопасно загрузить проверку ВК. Повторный запрос не отправлен.") + } else if (NativeVkSslPolicy.isMainFrameFailure(mainFrameUrl, error.url)) { + closePage() + fail("WEB_TLS", IllegalStateException("WEB_TLS_MAIN"), + "Не удалось проверить безопасное соединение с ВК.") + } else { + record("WEB_TLS_RESOURCE", IllegalStateException("WEB_TLS_RESOURCE")) + } + } + override fun onReceivedError(v: WebView, r: WebResourceRequest, error: WebResourceError) { + if (disposed || page !== v) return + record("WEB_RESOURCE", IllegalStateException("NET_WEB_RESOURCE")) + if (captcha?.active == true && (r.isForMainFrame || VkCaptchaPolicy.captchaPage(r.url.toString()))) { + fail("CAPTCHA_WEB_PAGE", IllegalStateException(), "Проверка ВК не загрузилась. Проверьте соединение.") + } else if (r.isForMainFrame) { + closePage() + fail("WEB_PAGE", IllegalStateException(), "Не удалось загрузить ВК. Попробуйте ещё раз.") + } + } + override fun onReceivedHttpError(v: WebView, r: WebResourceRequest, response: WebResourceResponse) { + if (disposed || page !== v) return + record("WEB_HTTP", VkHttpFailure(response.statusCode)) + if (captcha?.active == true && (r.isForMainFrame || VkCaptchaPolicy.captchaPage(r.url.toString()))) { + fail("CAPTCHA_WEB_HTTP", VkHttpFailure(response.statusCode), "ВК не загрузил страницу проверки. Попробуйте позже.") + } else if (r.isForMainFrame) { + closePage() + fail("WEB_PAGE", VkHttpFailure(response.statusCode), "ВК временно недоступен. Попробуйте позже.") + } + } + override fun onRenderProcessGone(v: WebView, detail: RenderProcessGoneDetail): Boolean { + if (disposed || page !== v) return true + val stage = if (captcha?.active == true) "CAPTCHA_WEB_RENDER" else "WEB_RENDER" + closePage(); fail(stage, IllegalStateException(), "Окно входа закрылось. Попробуйте ещё раз."); return true + } + } + view.setDownloadListener { _, _, _, _, _ -> } + page = view + if (captchaUrl != null) { + check(WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) && + WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { + "Не удалось безопасно открыть проверку ВК. Обновите Android System WebView." + } + val pending = CompletableDeferred().also { apiCaptchaResult = it } + val proofNonce = java.util.UUID.randomUUID().toString() + WebViewCompat.addWebMessageListener(view, "WDTTApiCaptchaResult", VkCaptchaPolicy.origins) { source, message, sourceOrigin, _, reply -> + if (page !== source || loginStage != LoginStage.CAPTCHA || apiCaptchaResult !== pending || + !VkCaptchaPolicy.trustedOrigin(sourceOrigin.toString()) || disposed) return@addWebMessageListener + val value = message.data.orEmpty() + if (value.length > 17000) return@addWebMessageListener + val data = runCatching { JSONObject(value) }.getOrNull() ?: return@addWebMessageListener + if (data.optString("page") == captchaUrl) { + reply.postMessage(JSONObject().put("observe", proofNonce).toString()) + } else if (data.optString("nonce") == proofNonce && VkApiCaptcha.validProof(data.optString("proof"))) { + pending.complete(data.optString("proof")) + } + } + WebViewCompat.addDocumentStartJavaScript(view, VkApiCaptcha.completionScript, VkCaptchaPolicy.origins) + } + val url = captchaUrl ?: requireNotNull(attempt).url() + origin = Uri.parse(url).host.orEmpty() + view.loadUrl(url) + } + private fun navigate(view: WebView, raw: String, main: Boolean): Boolean { + // Destroyed login pages must not restore a token after logout/cancellation. + if (disposed || page !== view || vkSession.logoutPending) return true + if (loginStage == LoginStage.CAPTCHA) return !VkApiProtocol.allowedPage(raw) + if (VkApiProtocol.isCallback(raw)) { + if (main) receiveVkIdCallback(view, raw) + return true + } + if (VkOAuthProtocol.isCallback(raw)) { + if (main) { + val attempt = miniAppAuth ?: return true + miniAppAuth = null + val result = runCatching { VkOAuthProtocol.callback(raw, attempt.state, System.currentTimeMillis()) } + closePage() + result.fold(onSuccess = { + vkSession.rememberAuthenticatedWebSession() + token = it + tokenRoute = routeStamp() + val data = JSONObject().put("value", it.value).put("expires", it.expiresAt).put("route", tokenRoute) + work { + check(tokenPrefs.edit().putString("token", secrets.encrypt(data.toString())).commit()) { + "Не удалось сохранить сессию ВК. Звонки не создавались." + } + authorizeAndGenerate() + } + }, onFailure = { fail("OAUTH_CALLBACK", it, "Не удалось завершить вход. Попробуйте ещё раз.") }) + } + return true + } + if (VkOAuthProtocol.containsCredential(raw)) { + record("OAUTH_TARGET", IllegalArgumentException()); return true + } + val allowed = VkApiProtocol.allowedPage(raw) + if (!allowed && main) fail("WEB_EXTERNAL", IllegalArgumentException(), "Завершите вход в этом окне.") + return !allowed + } + + private fun receiveVkIdCallback(view: WebView, raw: String) { + if (loginStage != LoginStage.VK_ID) return + val attempt = vkIdAuth ?: return + vkIdAuth = null // A duplicate redirect cannot advance the flow twice. + val accepted = runCatching { VkTwoStageLoginProtocol.continueWithMiniApp(raw, attempt) } + accepted.fold(onSuccess = { nextAttempt -> + // The authorization code intentionally is not exchanged, persisted or sent + // anywhere. Successful callback only establishes the official VK session in + // this isolated WebView. The compatible Mini App token is requested next in + // the same cookie jar and remains subject to its own state validation. + loginStage = LoginStage.MINI_APP + status = "Вход подтверждён. Получаем разрешение для Звонков ВК…" + val mini = nextAttempt.also { miniAppAuth = it } + view.post { + if (!disposed && page === view && loginStage == LoginStage.MINI_APP) { + origin = "oauth.vk.ru" + view.loadUrl(mini.url()) + } + } + }, onFailure = { + closePage() + fail("VK_ID_CALLBACK", it, "ВК не подтвердил вход. Попробуйте ещё раз.") + }) + } + + private suspend fun generate() { + check(!vkSession.logoutPending) { "LOGOUT_PENDING" } + // The profile action is the user's explicit request. Normal login continues + // automatically; a visible button is used only for a safe recovery path. + // Resume, service reconnect and background work never call this method. + check(foreground) { "Вернитесь в окно получения." } + check(authorized) + for (index in 0 until journal.length()) { + val entry = journal.getJSONObject(index) + if (entry.optString("phase") == "received") upload(entry) + check(entry.optString("phase") == "uploaded") { + "Ответ предыдущего звонка неизвестен. Повтор запрещён; проверьте звонки в ВК." + } + } + if (journal.length() < 4) { + check(token != null && token!!.expiresAt > System.currentTimeMillis()) { "Сессия ВК истекла. Сохранённые результаты не удалены." } + connect() + if (NativeVkRoutePolicy.needsLogin(tokenRoute, routeStamp())) { + // A token observed on another route can be IP-bound. Refresh through + // the official page, never retry a Calls request with it on a new path. + openLogin() + return + } + } + while (journal.length() < 4) { + check(NativeVkProtocol.mayCreate((0 until journal.length()).map { journal.getJSONObject(it).optString("phase") })) + check(foreground && network != null && http != null) { "Получение приостановлено. Продолжите в этом окне." } + val attempt = "va1_" + VkOAuthProtocol.newAttempt().state + val entry = JSONObject().put("a", attempt).put("phase", "reserved") + journal.put(entry); persist() + activeHashAttempt = journal.length().coerceIn(1, 4) + operationStage = "PERMIT" + val permit = rpc("permit", JSONObject().put("a", attempt)) + check(!permit.optBoolean("replayed", true) && permit.optString("state") == "committed") { + "Эта попытка уже была разрешена ранее. Повторный звонок не отправлен." + } + check(foreground && network != null) { "Окно или сеть изменились. Повторный звонок не отправлен." } + val callClient = http ?: error("Выбранная сеть потеряна. Запрос ВК не отправлен.") + val callToken = token?.value ?: error("Сессия ВК недоступна. Запрос ВК не отправлен.") + entry.put("phase", "dispatched"); persist() // Durable BEFORE account mutation. + operationStage = "CALL" + status = "Получаем ссылку ${journal.length()} из 4…" + var result = withContext(Dispatchers.IO) { + VkHttp.post(callClient, VkApiProtocol.START_ENDPOINT, + mapOf("access_token" to callToken, "v" to "5.199")) + } + if (result.optJSONObject("error")?.optInt("error_code") == 14) { + operationStage = "CAPTCHA" + // Only a definitive error 14 (no success payload) can continue the + // same permit. One continuation maximum; NEVER retry a timeout. + result = VkApiCaptcha.continueRejected(result, solve = { challenge -> + entry.put("phase", "captcha_wait"); persist() + pinLoginNetwork() + try { + login(challenge.url) + withTimeout(180_000) { requireNotNull(apiCaptchaResult).await() } + } + finally { closePage() } + }, send = { proofFields -> + check(foreground && http === callClient && token?.value == callToken && network != null && + expires > System.currentTimeMillis() / 1000 && !vkSession.logoutPending) { + "Сеть или сеанс изменились. Повторный запрос не отправлен." + } + entry.put("phase", "dispatched").put("captcha_continued", true); persist() + operationStage = "CALL" + withContext(Dispatchers.IO) { + VkHttp.post(callClient, VkApiProtocol.START_ENDPOINT, + mapOf("access_token" to callToken, "v" to "5.199") + proofFields) + } + }) + if (result.optJSONObject("error")?.optInt("error_code") == 14) operationStage = "CAPTCHA" + } + val value = NativeVkProtocol.hash(result) + check((0 until journal.length() - 1).none { journal.getJSONObject(it).optString("v") == value }) { + "ВК вернул повторную ссылку. Новые звонки не запускаются." + } + entry.put("v", value).put("phase", "received"); persist() + upload(entry) + if (journal.length() < 4) delay(800) + } + status = "Сохраняем четыре ссылки в выбранном профиле…" + activeHashAttempt = 0 + operationStage = "FINISH" + val result = rpc("finish") + val document = RemoteDocumentGateway.extractLink(result.optString("document")) + ?: error("Backend не вернул документ профиля. Повторите передачу сохранённого результата.") + status = "Готово. Возвращаемся в профиль WDTT Plus." + receiver?.send(1, Bundle().apply { putString("document", document.url) }) + prefs.edit().remove("operation").commit() + finish() + } + private suspend fun upload(entry: JSONObject) { + operationStage = "UPLOAD" + val parts = entry.getString("v").chunked(96) + parts.forEachIndexed { index, value -> + rpc("result", JSONObject().put("a", entry.getString("a")).put("v", value) + .put("i", index).put("n", parts.size)) + } + entry.put("phase", "uploaded"); persist() + completed = (0 until journal.length()).count { journal.getJSONObject(it).optString("phase") == "uploaded" } + activeHashAttempt = if (completed < 4) completed + 1 else 0 + } + private fun persist() { + val data = JSONObject().put("key", key).put("device", device).put("expires", expires).put("attempts", journal) + check(prefs.edit().putString("operation", secrets.encrypt(data.toString())).commit()) { + "Не удалось сохранить состояние. Запрос ВК не будет повторён." + } + } + private fun restore() { + runCatching { + secrets.decrypt(tokenPrefs.getString("token", null).takeUnless { vkSession.logoutPending })?.let { + val json = JSONObject(it) + if (json.getLong("expires") > System.currentTimeMillis()) { + token = VkApiProtocol.Token(json.getString("value"), json.getLong("expires")) + tokenRoute = json.optString("route") + } + } + // Never import the old shared token. A legacy ledger may be recovered + // only for the exact same opaque operation+device, preserving its budget. + val operation = prefs.getString("operation", null) + ?: getSharedPreferences("native-vk-v1", MODE_PRIVATE).getString("operation", null) + secrets.decrypt(operation)?.let { + val json = JSONObject(it) + if (json.optString("key") == key && json.optString("device") == device) journal = json.getJSONArray("attempts") + } + completed = (0 until journal.length()).count { journal.getJSONObject(it).optString("phase") == "uploaded" } + }.onFailure { fail("RESTORE", it, "Не удалось прочитать сохранённую сессию.") } + } + private suspend fun logout() { + operationStage = "LOGOUT" + closePage() + accountChoice = null + confirmedAccountToken = null + offeredAccountToken = null + requireAccountChoice = false + token = null; tokenRoute = ""; authorized = false + // Same semantics as VK Android SDK logout: local token + this WebView's + // isolated cookie jar. This does NOT claim provider-wide revocation. + vkSession.logout { VkLocalSession.clearWebData() } + status = "Вы вышли из ВК. Можно войти в другой аккаунт." + if (journal.length() > 0) { + // Preserve the old durable ledger and results. A new explicit profile + // action obtains a fresh backend-authorized batch; never reset permits. + receiver?.send(0, Bundle()); finish() + } else { + openLogin() + } + } + private fun closePage() { + apiCaptchaResult?.let { if (!it.isCompleted) it.completeExceptionally(IllegalStateException("Проверка ВК закрыта.")) } + apiCaptchaResult = null + captcha?.close(); captcha = null + captchaState = VkCaptchaPolicy.State.IDLE + vkIdAuth = null + miniAppAuth = null + loginStage = LoginStage.NONE + mainFrameUrl = "" + val view = page; page = null + view?.stopLoading(); view?.destroy() + if (view != null) CookieManager.getInstance().flush() + } + override fun onDestroy() { + if (current.get() === this) current.clear() + disposed = true; closePage(); http?.dispatcher?.cancelAll(); http?.connectionPool?.evictAll() + callback?.let { runCatching { cm.unregisterNetworkCallback(it) } } + // Keep the isolated process pinned. Never unbind it onto the VPN network. + if (bound) unbindService(connection) + replies.values.forEach { it.cancel() }; replies.clear() + super.onDestroy() + } + + private enum class LoginStage { NONE, VK_ID, MINI_APP, CAPTCHA } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkBrokerService.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkBrokerService.kt new file mode 100644 index 0000000..b91855c --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkBrokerService.kt @@ -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}).") + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkContinuation.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkContinuation.kt new file mode 100644 index 0000000..1d4c589 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkContinuation.kt @@ -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() + 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() + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkCrypto.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkCrypto.kt new file mode 100644 index 0000000..6797c09 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkCrypto.kt @@ -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)) + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkFeedback.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkFeedback.kt new file mode 100644 index 0000000..c2a0398 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkFeedback.kt @@ -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().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" + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkNetworkGate.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkNetworkGate.kt new file mode 100644 index 0000000..65753c6 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkNetworkGate.kt @@ -0,0 +1,20 @@ +package com.wdtt.plus.vk + +/** Callback snapshots only: onAvailable is not proof that capabilities are readable. */ +internal class NativeVkNetworkGate(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 +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkProtocol.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkProtocol.kt new file mode 100644 index 0000000..cd63e0b --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkProtocol.kt @@ -0,0 +1,33 @@ +package com.wdtt.plus.vk + +import java.net.URI +import org.json.JSONObject + +internal object NativeVkProtocol { + fun mayCreate(phases: List): 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) } + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkRoutePolicy.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkRoutePolicy.kt new file mode 100644 index 0000000..dc2f821 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkRoutePolicy.kt @@ -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 +} diff --git a/app/src/main/java/com/wdtt/plus/vk/NativeVkSslPolicy.kt b/app/src/main/java/com/wdtt/plus/vk/NativeVkSslPolicy.kt new file mode 100644 index 0000000..f9d5f65 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/NativeVkSslPolicy.kt @@ -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() +} diff --git a/app/src/main/java/com/wdtt/plus/vk/ProfileSessionPreparation.kt b/app/src/main/java/com/wdtt/plus/vk/ProfileSessionPreparation.kt new file mode 100644 index 0000000..5b670e3 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/ProfileSessionPreparation.kt @@ -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()) + } + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/ProfileWebSessionScope.kt b/app/src/main/java/com/wdtt/plus/vk/ProfileWebSessionScope.kt new file mode 100644 index 0000000..f424967 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/ProfileWebSessionScope.kt @@ -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 + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkAccountChoice.kt b/app/src/main/java/com/wdtt/plus/vk/VkAccountChoice.kt new file mode 100644 index 0000000..94b512a --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkAccountChoice.kt @@ -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("Выйти из ВК") } + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkApiCaptcha.kt b/app/src/main/java/com/wdtt/plus/vk/VkApiCaptcha.kt new file mode 100644 index 0000000..1cde7c9 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkApiCaptcha.kt @@ -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) { + fun continuation(success: String): Map { + 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) -> 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() + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkApiProtocol.kt b/app/src/main/java/com/wdtt/plus/vk/VkApiProtocol.kt new file mode 100644 index 0000000..a397aed --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkApiProtocol.kt @@ -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 = 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() + 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 не выполнялся." + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkCaptchaPolicy.kt b/app/src/main/java/com/wdtt/plus/vk/VkCaptchaPolicy.kt new file mode 100644 index 0000000..1a0d4aa --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkCaptchaPolicy.kt @@ -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() + private val attempted = mutableSetOf() + private val manual = mutableSetOf() + 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 -> "Проверка завершена. Продолжаю…" + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkCaptchaScript.kt b/app/src/main/java/com/wdtt/plus/vk/VkCaptchaScript.kt new file mode 100644 index 0000000..368695c --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkCaptchaScript.kt @@ -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() +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkCaptchaTimeout.kt b/app/src/main/java/com/wdtt/plus/vk/VkCaptchaTimeout.kt new file mode 100644 index 0000000..94d4b3c --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkCaptchaTimeout.kt @@ -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 } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkContinuationExecutor.kt b/app/src/main/java/com/wdtt/plus/vk/VkContinuationExecutor.kt new file mode 100644 index 0000000..05751e4 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkContinuationExecutor.kt @@ -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) + 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", + ) +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkHttp.kt b/app/src/main/java/com/wdtt/plus/vk/VkHttp.kt new file mode 100644 index 0000000..666fe6d --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkHttp.kt @@ -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 = + 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): 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): 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) + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkInPlaceCaptcha.kt b/app/src/main/java/com/wdtt/plus/vk/VkInPlaceCaptcha.kt new file mode 100644 index 0000000..ea6297c --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkInPlaceCaptcha.kt @@ -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>() + 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 = "" + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkLocalSession.kt b/app/src/main/java/com/wdtt/plus/vk/VkLocalSession.kt new file mode 100644 index 0000000..46bda71 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkLocalSession.kt @@ -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() + 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() + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkOAuthProtocol.kt b/app/src/main/java/com/wdtt/plus/vk/VkOAuthProtocol.kt new file mode 100644 index 0000000..c68728c --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkOAuthProtocol.kt @@ -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 { + val result = mutableMapOf() + 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 не отправлялся." + } +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkProcessInitializer.kt b/app/src/main/java/com/wdtt/plus/vk/VkProcessInitializer.kt new file mode 100644 index 0000000..1b65a8d --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkProcessInitializer.kt @@ -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 +} diff --git a/app/src/main/java/com/wdtt/plus/vk/VkProfileActivities.kt b/app/src/main/java/com/wdtt/plus/vk/VkProfileActivities.kt new file mode 100644 index 0000000..6bc486b --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkProfileActivities.kt @@ -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() diff --git a/app/src/main/java/com/wdtt/plus/vk/VkTwoStageLoginProtocol.kt b/app/src/main/java/com/wdtt/plus/vk/VkTwoStageLoginProtocol.kt new file mode 100644 index 0000000..c6be19b --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/vk/VkTwoStageLoginProtocol.kt @@ -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() + } +} diff --git a/app/src/test/java/com/wdtt/plus/ConnectionDiagnosticsTest.kt b/app/src/test/java/com/wdtt/plus/ConnectionDiagnosticsTest.kt new file mode 100644 index 0000000..1057aed --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ConnectionDiagnosticsTest.kt @@ -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)) + } +} diff --git a/app/src/test/java/com/wdtt/plus/DeviceCompatibilityTest.kt b/app/src/test/java/com/wdtt/plus/DeviceCompatibilityTest.kt index af4ba4e..d568b5c 100644 --- a/app/src/test/java/com/wdtt/plus/DeviceCompatibilityTest.kt +++ b/app/src/test/java/com/wdtt/plus/DeviceCompatibilityTest.kt @@ -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) diff --git a/app/src/test/java/com/wdtt/plus/ProxyStartupErrorTest.kt b/app/src/test/java/com/wdtt/plus/ProxyStartupErrorTest.kt new file mode 100644 index 0000000..77ada65 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ProxyStartupErrorTest.kt @@ -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")) + } +} diff --git a/app/src/test/java/com/wdtt/plus/RemoteDocumentTransportTest.kt b/app/src/test/java/com/wdtt/plus/RemoteDocumentTransportTest.kt new file mode 100644 index 0000000..7346279 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/RemoteDocumentTransportTest.kt @@ -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) + } +} diff --git a/app/src/test/java/com/wdtt/plus/RtTurnSniTest.kt b/app/src/test/java/com/wdtt/plus/RtTurnSniTest.kt index 56cdcc5..b2f8d5d 100644 --- a/app/src/test/java/com/wdtt/plus/RtTurnSniTest.kt +++ b/app/src/test/java/com/wdtt/plus/RtTurnSniTest.kt @@ -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("сеть РТ")) + } } diff --git a/app/src/test/java/com/wdtt/plus/ServerAdminSudoTest.kt b/app/src/test/java/com/wdtt/plus/ServerAdminSudoTest.kt new file mode 100644 index 0000000..d7e0838 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ServerAdminSudoTest.kt @@ -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 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): 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, + ) +} diff --git a/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt b/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt index b31590c..6504484 100644 --- a/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt +++ b/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt @@ -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")) diff --git a/app/src/test/java/com/wdtt/plus/VkJoinLinkTest.kt b/app/src/test/java/com/wdtt/plus/VkJoinLinkTest.kt index a393977..9b08b8a 100644 --- a/app/src/test/java/com/wdtt/plus/VkJoinLinkTest.kt +++ b/app/src/test/java/com/wdtt/plus/VkJoinLinkTest.kt @@ -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,нельзя")) + } } diff --git a/app/src/test/java/com/wdtt/plus/VpnAddressRoutingTest.kt b/app/src/test/java/com/wdtt/plus/VpnAddressRoutingTest.kt index 02aab82..ba32b3d 100644 --- a/app/src/test/java/com/wdtt/plus/VpnAddressRoutingTest.kt +++ b/app/src/test/java/com/wdtt/plus/VpnAddressRoutingTest.kt @@ -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( diff --git a/app/src/test/java/com/wdtt/plus/ui/DeployDataSafetyTest.kt b/app/src/test/java/com/wdtt/plus/ui/DeployDataSafetyTest.kt index 699ba91..5493f6d 100644 --- a/app/src/test/java/com/wdtt/plus/ui/DeployDataSafetyTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/DeployDataSafetyTest.kt @@ -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( diff --git a/app/src/test/java/com/wdtt/plus/ui/DeployRootAccessTest.kt b/app/src/test/java/com/wdtt/plus/ui/DeployRootAccessTest.kt new file mode 100644 index 0000000..b27517f --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/DeployRootAccessTest.kt @@ -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")) + } + } +} diff --git a/app/src/test/java/com/wdtt/plus/ui/ExternalProxyDiagnosticsTest.kt b/app/src/test/java/com/wdtt/plus/ui/ExternalProxyDiagnosticsTest.kt new file mode 100644 index 0000000..ebfce0e --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/ExternalProxyDiagnosticsTest.kt @@ -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 { + 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 'error'; 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")) + } +} diff --git a/app/src/test/java/com/wdtt/plus/ui/FirstServerSetupTest.kt b/app/src/test/java/com/wdtt/plus/ui/FirstServerSetupTest.kt new file mode 100644 index 0000000..0602651 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/FirstServerSetupTest.kt @@ -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) + } + } +} diff --git a/app/src/test/java/com/wdtt/plus/ui/FloatingToolbarPositionTest.kt b/app/src/test/java/com/wdtt/plus/ui/FloatingToolbarPositionTest.kt index 84fee06..5eb0a9c 100644 --- a/app/src/test/java/com/wdtt/plus/ui/FloatingToolbarPositionTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/FloatingToolbarPositionTest.kt @@ -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, + ), + ) + } } diff --git a/app/src/test/java/com/wdtt/plus/ui/OutboundTunInterfaceTest.kt b/app/src/test/java/com/wdtt/plus/ui/OutboundTunInterfaceTest.kt index c60c8cb..52d6d2c 100644 --- a/app/src/test/java/com/wdtt/plus/ui/OutboundTunInterfaceTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/OutboundTunInterfaceTest.kt @@ -129,7 +129,7 @@ class OutboundTunInterfaceTest { ) assertFalse("block() {\n cleanup" in script) assertTrue("${'$'}ROUTE_HELPER\" block" in script) - assertTrue("curl -4fsS --interface \"${'$'}TEST_SOURCE\"" in script) + assertTrue("wdtt_routed_public_ip \"${'$'}TEST_SOURCE\" \"${'$'}TUN_IFACE\"" in script) assertTrue("wdtt_write_mode \"tun_interface\"" in script) assertTrue("tun_interface_is_primary" in script) assertTrue("WDTT_TUN_EXIT_V1" in script) @@ -181,7 +181,7 @@ class OutboundTunInterfaceTest { assertTrue("WDTT_ERROR=tun_exit_not_owned" in script) assertTrue("WDTT_ERROR=tun_interface_mismatch" in script) assertTrue("tun-exit-route status" in script) - assertTrue("curl -4fsS --interface \"${'$'}TEST_SOURCE\"" in script) + assertTrue("wdtt_routed_public_ip \"${'$'}TEST_SOURCE\" \"${'$'}TUN_IFACE\"" in script) assertShellSyntax(script) } diff --git a/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt b/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt index 7c67295..f841669 100644 --- a/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt @@ -740,7 +740,7 @@ class OutboundWireGuardTest { assertTrue("chmod 0600 /etc/wdtt/outbound.json" in script) assertTrue("WDTT_PROXY_TEST_SOURCE=\"${'$'}test_source\"" in script) assertTrue("iptables -t nat -I OUTPUT -s \"${'$'}test_source\" -p tcp -j WDTT_PROXY_TEST" in script) - assertTrue("curl --interface \"${'$'}test_source\"" in script) + assertTrue("--interface \"${'$'}test_source\"" in script) assertFalse("iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST" in script) assertShellSyntax(script) } diff --git a/app/src/test/java/com/wdtt/plus/ui/ServerClientsAccessTest.kt b/app/src/test/java/com/wdtt/plus/ui/ServerClientsAccessTest.kt index 4a84cd6..4935793 100644 --- a/app/src/test/java/com/wdtt/plus/ui/ServerClientsAccessTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/ServerClientsAccessTest.kt @@ -11,7 +11,7 @@ class ServerClientsAccessTest { fun primaryServerAccessExplainsEveryLocalBlocker() { val key = "-----BEGIN OPENSSH PRIVATE KEY-----\ndGVzdA==\n-----END OPENSSH PRIVATE KEY-----" assertEquals( - "Укажите IP-адрес или домен сервера в верхнем блоке «Деплой».", + "Укажите IP-адрес или домен сервера в настройках SSH.", primaryServerSshAccessIssue("", false, "password", "", "", 22) ) assertEquals( @@ -23,7 +23,7 @@ class ServerClientsAccessTest { primaryServerSshAccessIssue("vpn.example.org", true, "key", "sudo", "", 22) ) assertEquals( - "Откройте «Секреты» и укажите корректный SSH-порт от 1 до 65535.", + "Откройте настройки SSH и укажите корректный SSH-порт от 1 до 65535.", primaryServerSshAccessIssue("vpn.example.org", true, "key", "", key, 0) ) assertNull(primaryServerSshAccessIssue("vpn.example.org", true, "key", "", key, 22)) @@ -32,11 +32,11 @@ class ServerClientsAccessTest { @Test fun accessRequiresDeployHostSshAndAdminPassword() { assertEquals( - "Укажите IP-адрес или домен сервера в верхнем блоке «Деплой».", + "Укажите IP-адрес или домен сервера в настройках SSH.", serverClientsAccessIssue("", false, "", 22, "") ) assertEquals( - "Проверьте IP-адрес или домен сервера в верхнем блоке «Деплой».", + "Проверьте IP-адрес или домен сервера в настройках SSH.", serverClientsAccessIssue("https://bad host", false, "ssh", 22, "owner") ) assertEquals( @@ -60,7 +60,7 @@ class ServerClientsAccessTest { serverClientsAccessIssue("vpn.example.org", true, "ssh", 0, "owner") ) assertEquals( - "Откройте «Секреты» и укажите главный пароль администратора.", + "Откройте параметры сервера и укажите главный пароль администратора.", serverClientsAccessIssue("vpn.example.org", true, "ssh", 22, "") ) assertNull(serverClientsAccessIssue("vpn.example.org", true, "ssh", 22, "owner")) diff --git a/app/src/test/java/com/wdtt/plus/ui/ServerDiagnosticPortTest.kt b/app/src/test/java/com/wdtt/plus/ui/ServerDiagnosticPortTest.kt new file mode 100644 index 0000000..4cd3ad6 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/ServerDiagnosticPortTest.kt @@ -0,0 +1,73 @@ +package com.wdtt.plus.ui + +import com.wdtt.plus.DeviceCheckSeverity +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ServerDiagnosticPortTest { + private fun probe(socket: String, port: Int, ssStatus: Int = 0): Int { + val function = serverDiagnosticsScript().substringAfter("wdtt_diag_udp_listen_port() {") + .substringBefore("wdtt_diag_tcp_listen_port() {") + val process = ProcessBuilder("sh", "-c", """ + wdtt_diag_cmd() { return 0; } + ss() { printf '%s\n' "${'$'}FAKE_SOCKETS"; return $ssStatus; } + wdtt_diag_udp_listen_port() {$function + wdtt_diag_udp_listen_port $port + """.trimIndent()).apply { environment()["FAKE_SOCKETS"] = socket }.start() + return process.waitFor() + } + + @Test + fun matchesOnlyExactLocalPortForIpv4AndIpv6() { + assertEquals(0, probe("UNCONN 0 0 0.0.0.0:56000 0.0.0.0:*", 56000)) + assertEquals(0, probe("UNCONN 0 0 [::]:56000 [::]:*", 56000)) + assertEquals(1, probe("UNCONN 0 0 0.0.0.0:56000 0.0.0.0:*", 5600)) + assertEquals(1, probe("UNCONN 0 0 0.0.0.0:12345 1.2.3.4:56000", 56000)) + } + + @Test + fun failedInspectionIsNotReportedAsMissingPort() { + assertEquals(2, probe("", 56000, ssStatus = 1)) + } + + @Test + fun incompleteSshResponseIsNotReportedAsServerCommandFailure() { + val incomplete = "WDTT_SERVER_DIAG|OK|ОС|найдена|Linux|\nerror: SSH channel closed before exit status" + val issue = serverDiagnosticsOutputIssue(incomplete) + + assertTrue(issue?.contains("SSH-канал закрылся") == true) + assertTrue(serverDiagnosticsSshInterrupted(incomplete)) + assertFalse(issue.orEmpty().contains("root", ignoreCase = true)) + assertTrue(serverDiagnosticsSshInterrupted("error: remote command exited with code -1")) + assertTrue(serverDiagnosticsSshInterrupted("error: timeout")) + } + + @Test + fun completeResponseHasExplicitEndMarkerAndNoTransportError() { + val script = serverDiagnosticsScript() + assertTrue(script.contains("WDTT_SERVER_DIAG_COMPLETE=1")) + val complete = "WDTT_SERVER_DIAG|OK|ОС|найдена|Linux|\nWDTT_SERVER_DIAG_COMPLETE=1" + assertNull(serverDiagnosticsOutputIssue(complete)) + assertFalse(serverDiagnosticsSshInterrupted(complete)) + assertFalse(serverDiagnosticsSshInterrupted("error: remote command exited with code 1")) + } + + @Test + fun shortDirectResponseIsIncompleteButRelayResponseIsExplicitlyReduced() { + val partial = "WDTT_SERVER_DIAG|OK|ОС|найдена|Linux|" + assertEquals(DeviceCheckSeverity.Warning, serverDiagnosticsCompletionItem(partial, true)?.severity) + assertEquals("сокращённая проверка", serverDiagnosticsCompletionItem(partial, false)?.status) + assertNull(serverDiagnosticsCompletionItem("$partial\nWDTT_SERVER_DIAG_COMPLETE=1", true)) + assertEquals(DeviceCheckSeverity.Warning, serverDiagnosticsCompletionItem("$partial\nerror: timeout", false)?.severity) + } + + @Test + fun coreServerChecksAreCollectedBeforeOptionalExternalSites() { + val script = serverDiagnosticsScript() + assertTrue(script.indexOf("\"WDTT сервер\"") < script.indexOf("PUBLIC_IP=")) + assertTrue(script.contains("timeout 3 getent ahostsv4")) + } +} diff --git a/app/src/test/java/com/wdtt/plus/ui/VkHashBulkPasteTest.kt b/app/src/test/java/com/wdtt/plus/ui/VkHashBulkPasteTest.kt index c44dd8f..1bf6fa0 100644 --- a/app/src/test/java/com/wdtt/plus/ui/VkHashBulkPasteTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/VkHashBulkPasteTest.kt @@ -71,4 +71,32 @@ class VkHashBulkPasteTest { assertEquals(4, result.insertedCount) assertEquals(0, result.skippedCount) } + + @Test + fun acquisitionUsesOneDynamicEntryPoint() { + assertEquals( + "Получить ВК-хеши", + hashAcquisitionButtonLabel(false, canRestore = false, canAcquire = true, busy = false) + ) + assertEquals( + "Получить новые ВК-хеши", + hashAcquisitionButtonLabel(true, canRestore = false, canAcquire = true, busy = false) + ) + assertEquals( + "Получить или вернуть ВК-хеши", + hashAcquisitionButtonLabel(true, canRestore = true, canAcquire = true, busy = false) + ) + assertEquals( + "Вернуть ВК-хеши", + hashAcquisitionButtonLabel(false, canRestore = true, canAcquire = false, busy = false) + ) + } + + @Test + fun uiTextUsesRussianVkNameWithoutChangingUrls() { + assertEquals( + "ВК-хеши из ВК · https://id.vk.ru", + localizeVkUiText("VK-хеши из ВКонтакте · https://id.vk.ru") + ) + } } diff --git a/bot.go b/bot.go index ac43e5d..80bb2fd 100644 --- a/bot.go +++ b/bot.go @@ -350,7 +350,19 @@ func databaseTrafficTotals(days int) trafficTotals { } func formatTrafficTotals(total trafficTotals) string { - return fmt.Sprintf("↓%.2f MB / ↑%.2f MB", float64(total.Down)/(1024*1024), float64(total.Up)/(1024*1024)) + return fmt.Sprintf("↓%s / ↑%s", formatBotTrafficBytes(total.Down), formatBotTrafficBytes(total.Up)) +} + +// Telegram traffic counters use decimal units: 1000 MB = 1 GB, 1000 GB = 1 TB. +func formatBotTrafficBytes(bytes int64) string { + divisor := int64(1_000_000) + unit := "МБ" + if bytes >= 1_000_000_000_000 { + divisor, unit = 1_000_000_000_000, "ТБ" + } else if bytes >= 1_000_000_000 { + divisor, unit = 1_000_000_000, "ГБ" + } + return fmt.Sprintf("%.2f %s", float64(bytes)/float64(divisor), unit) } func trafficPeriodReport(today, week, month, all trafficTotals) string { @@ -1476,7 +1488,7 @@ func sendMainMenu(token string, adminID int64, messageID int) int { } dbMutex.Unlock() text := fmt.Sprintf( - "🤖 *WDTT Manager*\n\nКлиенты: `%d/%d`\nУстройства: `%d`\nОтключены: `%d`\nИстекли: `%d`\n\nВыберите раздел.", + "🤖 *WDTT Plus Менеджер*\n\nКлиенты: `%d/%d`\nУстройства: `%d`\nОтключены: `%d`\nИстекли: `%d`\n\nВыберите раздел.", passwords, maxGeneratedPasswords, devices, deactivated, expired, ) return sendOrEditTelegram(token, adminID, messageID, text, inlineKeyboard( diff --git a/bot_external_proxy_test.go b/bot_external_proxy_test.go index 32ef257..0ba6652 100644 --- a/bot_external_proxy_test.go +++ b/bot_external_proxy_test.go @@ -7,6 +7,42 @@ import ( "testing" ) +func TestFormatBotTrafficBytes(t *testing.T) { + for _, tc := range []struct { + bytes int64 + want string + }{ + {0, "0.00 МБ"}, + {1_000_000, "1.00 МБ"}, + {999_000_000, "999.00 МБ"}, + {999_990_000, "999.99 МБ"}, + {1_000_000_000, "1.00 ГБ"}, + {1_250_000_000, "1.25 ГБ"}, + {999_990_000_000, "999.99 ГБ"}, + {1_000_000_000_000, "1.00 ТБ"}, + {1_250_000_000_000, "1.25 ТБ"}, + {9_223_372_036_854_775_807, "9223372.04 ТБ"}, + } { + if got := formatBotTrafficBytes(tc.bytes); got != tc.want { + t.Errorf("formatBotTrafficBytes(%d) = %q, want %q", tc.bytes, got, tc.want) + } + } +} + +func TestBotTrafficReportScalesEveryPeriodAndDirection(t *testing.T) { + want := "↓1.25 ГБ / ↑2.50 ТБ" + total := trafficTotals{Down: 1_250_000_000, Up: 2_500_000_000_000} + if got := formatTrafficTotals(total); got != want { + t.Fatalf("totals = %q, want %q", got, want) + } + if got := trafficPeriodReport(total, total, total, total); strings.Count(got, want) != 4 { + t.Fatalf("not every period uses adaptive units: %s", got) + } + if got := formatTrafficTotals(trafficTotals{Down: 1_000_000, Up: 1_000_000_000}); got != "↓1.00 МБ / ↑1.00 ГБ" { + t.Fatalf("directions must scale independently: %s", got) + } +} + func TestExternalProxyTransparentCheckDoesNotCaptureRootXrayTraffic(t *testing.T) { script := outboundBotPrelude() diff --git a/go.mod b/go.mod index 13b85e5..b12d60a 100644 --- a/go.mod +++ b/go.mod @@ -8,10 +8,14 @@ require ( golang.org/x/crypto v0.55.0 golang.org/x/net v0.58.0 golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 + wdtt.local/pathprobe v0.0.0 ) + require ( github.com/pion/logging v0.2.4 // indirect golang.org/x/sys v0.47.0 // indirect golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect ) + +replace wdtt.local/pathprobe => ./pathprobe diff --git a/go_client/connection_policy.go b/go_client/connection_policy.go new file mode 100644 index 0000000..bc4cf17 --- /dev/null +++ b/go_client/connection_policy.go @@ -0,0 +1,466 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "net" + "strings" + "sync" + "time" +) + +// Connection selection is independent of the server's packet framing. A +// candidate is accepted only after authenticated GETCONF and a relay reply. +// There is one discovery attempt for the entire client, not one per worker. +const connectionAttemptBudget = 12 +const connectionVerifiedStartLimit = 3 + +type connectionPath struct { + endpoint turnEndpoint + masque warpMasqueProtocol + front string +} + +func (p connectionPath) kind() string { + if p.masque == warpMasqueHTTP2 { + return "h2" + } + if p.masque == warpMasqueHTTP3 { + return "h3" + } + if p.front != "" { + return "tls-front" + } + return string(p.endpoint.Transport) +} +func (p connectionPath) key() string { return p.endpoint.key() + "|" + p.kind() } + +type connectionPolicy struct { + mu sync.Mutex + preferred string + noUDP bool + active, pending, failures int + blocked, sleeping, paused bool + epoch uint64 + next time.Time + udpRetryAfter time.Time + excluded map[string]time.Time + changed chan struct{} + probes map[*connectionLease]struct{} + readyPaths map[string]int + readyKinds map[string]int +} + +func newConnectionPolicy(preferred string, noUDP bool) *connectionPolicy { + return &connectionPolicy{preferred: preferred, noUDP: noUDP, excluded: make(map[string]time.Time), changed: make(chan struct{}), probes: make(map[*connectionLease]struct{}), readyPaths: make(map[string]int), readyKinds: make(map[string]int)} +} + +func (a *connectionPolicy) configure(preferred string, noUDP bool) { + a.mu.Lock() + defer a.mu.Unlock() + // Android may report a handover while flags/startup secrets are loading. + // The command-line hint belongs exclusively to the original network. + if a.epoch == 0 { + a.preferred = preferred + } + a.noUDP = noUDP +} +func (a *connectionPolicy) deferUDP(delay time.Duration) { + a.mu.Lock() + defer a.mu.Unlock() + if delay > 0 { + a.udpRetryAfter = time.Now().Add(delay) + } +} + +func (a *connectionPolicy) pathAllowed(p connectionPath, now time.Time) bool { + datagram := p.kind() == "udp" || p.kind() == "h3" + return !datagram || (!a.noUDP && !now.Before(a.udpRetryAfter)) +} + +func (a *connectionPolicy) notifyLocked() { close(a.changed); a.changed = make(chan struct{}) } + +func (a *connectionPolicy) waitAvailable(ctx context.Context) error { + for { + if err := ctx.Err(); err != nil { + return err + } + a.mu.Lock() + available, changed := !a.blocked && !a.sleeping && !a.paused, a.changed + a.mu.Unlock() + if available { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-changed: + } + } +} +func (a *connectionPolicy) command(command string) { + a.mu.Lock() + defer a.mu.Unlock() + switch command { + case "CONNECTION_NETWORK": + a.epoch++ + a.failures = 0 + a.paused = false + a.preferred = "" + a.excluded = make(map[string]time.Time) + a.readyPaths = make(map[string]int) + a.readyKinds = make(map[string]int) + case "CONNECTION_OFFLINE": + a.blocked = true + case "CONNECTION_ONLINE": + a.blocked = false + case "DEVICE_SLEEP", "PAUSE": + a.sleeping = true + case "DEVICE_WAKE", "RESUME": + a.sleeping = false + default: + return + } + if a.sleeping || a.blocked || command == "CONNECTION_NETWORK" { + for lease := range a.probes { + lease.interrupted = true + if lease.cancel != nil { + lease.cancel() + } + } + } + a.notifyLocked() +} + +func connectionPaths(endpoints []turnEndpoint, tp *TurnParams, noUDP bool) []connectionPath { + paths := make([]connectionPath, 0, len(endpoints)*3) + for _, e := range endpoints { + if e.Transport == turnTransportUDP { + continue + } + paths = append(paths, connectionPath{endpoint: e}) + if e.Transport == turnTransportTLS && tp.TLSFrontSNI != "" { + paths = append(paths, connectionPath{endpoint: e, front: tp.TLSFrontSNI}) + } + } + if tp.Masque != nil { + for _, protocol := range []warpMasqueProtocol{warpMasqueHTTP2, warpMasqueHTTP3} { + if noUDP && protocol == warpMasqueHTTP3 { + continue + } + for _, e := range endpoints { + if e.Transport != turnTransportUDP { + paths = append(paths, connectionPath{endpoint: e, masque: protocol}) + } + } + } + } + if !noUDP { + for _, e := range endpoints { + if e.Transport == turnTransportUDP { + paths = append(paths, connectionPath{endpoint: e}) + } + } + } + // Interleave transport classes, so many dead addresses of one class do + // not consume the complete budget before another transport gets a chance. + var result []connectionPath + for round := 0; ; round++ { + added := false + for _, kind := range []string{"udp", "tls", "tls-front", "tcp", "h2", "h3"} { + n := 0 + for _, p := range paths { + if p.kind() != kind { + continue + } + if n == round { + result = append(result, p) + added = true + break + } + n++ + } + } + if !added { + return result + } + } +} + +type connectionLease struct { + a *connectionPolicy + path connectionPath + epoch uint64 + ready bool + cancel context.CancelFunc + interrupted bool + finished bool + stage string + started time.Time +} + +func (l *connectionLease) bind(cancel context.CancelFunc) { + l.a.mu.Lock() + defer l.a.mu.Unlock() + l.cancel = cancel + if l.interrupted { + cancel() + } +} + +func (l *connectionLease) setStage(stage string) { + l.a.mu.Lock() + defer l.a.mu.Unlock() + l.stage = stage +} + +func (a *connectionPolicy) acquire(ctx context.Context, paths []connectionPath) (*connectionLease, error) { + if len(paths) == 0 { + return nil, fmt.Errorf("нет разрешённых путей подключения") + } + for { + if err := ctx.Err(); err != nil { + return nil, err + } + a.mu.Lock() + now := time.Now() + index := -1 + for i, p := range paths { + if !a.pathAllowed(p, now) || now.Before(a.excluded[p.key()]) { + continue + } + if index < 0 { + index = i + } + if p.kind() == a.preferred { + index = i + break + } + } + // A new transport still has one discovery probe. Once a worker on + // this network has confirmed it, match the existing DTLS limit of 3. + limit := 1 + if index >= 0 && a.readyKinds[paths[index].kind()] > 0 { + limit = connectionVerifiedStartLimit + } + if a.failures >= connectionAttemptBudget && a.active == 0 && !a.paused { + a.paused = true + log.Print("[CONNECTION] PAUSED Лимит попыток исчерпан. Смените сеть или подключитесь заново.") + } + if !a.blocked && !a.sleeping && !a.paused && a.pending < limit && !now.Before(a.next) { + if index >= 0 { + a.pending++ + a.next = now.Add(250 * time.Millisecond) + lease := &connectionLease{a: a, path: paths[index], epoch: a.epoch, stage: "turn", started: now} + a.probes[lease] = struct{}{} + a.mu.Unlock() + log.Printf("[CONNECTION] TRY %s", lease.path.kind()) + return lease, nil + } + } + // Paused workers sleep on a notification, not repeating timers. + var wakeAt time.Time + if !a.blocked && !a.sleeping && !a.paused && a.pending < limit { + if now.Before(a.next) { + wakeAt = a.next + } else { + for _, path := range paths { + if a.noUDP && (path.kind() == "udp" || path.kind() == "h3") { + continue + } + expiry := a.excluded[path.key()] + if (path.kind() == "udp" || path.kind() == "h3") && a.udpRetryAfter.After(expiry) { + expiry = a.udpRetryAfter + } + if wakeAt.IsZero() || expiry.Before(wakeAt) { + wakeAt = expiry + } + } + } + } + changed := a.changed + a.mu.Unlock() + var timer *time.Timer + var tick <-chan time.Time + if !wakeAt.IsZero() { + timer = time.NewTimer(time.Until(wakeAt)) + tick = timer.C + } + select { + case <-ctx.Done(): + if timer != nil { + timer.Stop() + } + return nil, ctx.Err() + case <-changed: + if timer != nil { + timer.Stop() + } + case <-tick: + } + } +} + +func (l *connectionLease) accept() bool { + a := l.a + a.mu.Lock() + defer a.mu.Unlock() + if l.interrupted || l.ready || l.finished || l.epoch != a.epoch { + return false + } + delete(a.probes, l) + l.ready = true + a.pending-- + a.active++ + if l.epoch == a.epoch { + a.readyPaths[l.path.key()]++ + a.readyKinds[l.path.kind()]++ + // A reserve worker does not disprove already working UDP workers. + if a.readyKinds["udp"] > 0 { + a.preferred = "udp" + } else { + a.preferred = l.path.kind() + } + if l.path.kind() == "udp" { + a.udpRetryAfter = time.Time{} + } + l.stage = "active" + a.failures = 0 + a.paused = false + delete(a.excluded, l.path.key()) + log.Printf("[CONNECTION] READY %d %s", a.epoch, l.path.kind()) + } + a.notifyLocked() + return true +} + +func connectionPathFailure(err error) bool { + if errors.Is(err, errUplinkPathReplacement) { + return false + } + if _, limited := workerPolicyLimit(err); limited { + return false + } + if isCredentialTURNError(err) || isTURNCapacityError(err) { + return false + } + if err != nil { + s := strings.ToUpper(err.Error()) + for _, marker := range []string{"FATAL_AUTH", "FATAL_TRANSPORT", "CAPTCHA", "FLOOD", "CALL_FULL", "INVALID_JOIN_LINK"} { + if strings.Contains(s, marker) { + return false + } + } + } + return true +} + +func (l *connectionLease) finish(err error, cancelled bool) { + a := l.a + a.mu.Lock() + defer a.mu.Unlock() + if l.finished { + return + } + l.finished = true + delete(a.probes, l) + if l.ready { + a.active-- + if l.epoch == a.epoch { + a.readyPaths[l.path.key()]-- + a.readyKinds[l.path.kind()]-- + if a.readyKinds[a.preferred] == 0 { + for _, kind := range []string{"udp", "tls", "tls-front", "tcp", "h2", "h3"} { + if a.readyKinds[kind] > 0 { + a.preferred = kind + break + } + } + } + } + } else { + a.pending-- + } + if l.epoch == a.epoch && !cancelled && !l.interrupted && !a.sleeping && !a.blocked { + if errors.Is(err, errUplinkPathReplacement) { + a.notifyLocked() + return + } + log.Printf("[CONNECTION] FAILED %d %s %s %s %d", a.epoch, l.path.kind(), l.stage, connectionFailureReason(err), time.Since(l.started).Milliseconds()) + if connectionPathFailure(err) { + if l.path.kind() == "udp" || l.path.kind() == "h3" { + if a.readyKinds["udp"]+a.readyKinds["h3"] == 0 { + if !time.Now().Before(a.udpRetryAfter) { + a.udpRetryAfter = time.Now().Add(5 * time.Minute) + log.Printf("[CONNECTION] UDP_BACKOFF %d", a.epoch) + } + } else { + log.Printf("[CONNECTION] UDP_PARTIAL %d", a.epoch) + } + } + a.failures++ + if a.readyPaths[l.path.key()] == 0 { + a.excluded[l.path.key()] = time.Now().Add(90 * time.Second) + } + if a.failures >= connectionAttemptBudget { + a.next = time.Now().Add(90 * time.Second) + } + } else { + a.failures++ + // Authentication and admission control are not network evidence. + a.next = time.Now().Add(20 * time.Second) + } + } + a.notifyLocked() +} + +func connectionFailureReason(err error) string { + if !connectionPathFailure(err) { + if _, limited := workerPolicyLimit(err); limited { + return "limit" + } + if isTURNCapacityError(err) { + return "capacity" + } + if err != nil && strings.Contains(err.Error(), "FATAL_TRANSPORT") { + return "protocol" + } + return "auth" + } + if err == nil { + return "closed" + } + lower := strings.ToLower(err.Error()) + if errors.Is(err, context.DeadlineExceeded) || strings.Contains(lower, "timeout") || strings.Contains(lower, "deadline") { + return "timeout" + } + if errors.Is(err, context.Canceled) { + return "interrupted" + } + return "network" +} + +// The established relay must carry traffic in both directions. This also +// works with old servers: keepalive is part of the original DTLS protocol. +func confirmConnectionPath(ctx context.Context, conn net.Conn) error { + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + stop := context.AfterFunc(ctx, func() { _ = conn.SetDeadline(time.Now()) }) + defer stop() + defer conn.SetDeadline(time.Time{}) + if _, err := conn.Write([]byte{keepaliveByte}); err != nil { + return err + } + buf := make([]byte, readBufSize) + for { + n, err := conn.Read(buf) + if err != nil { + return fmt.Errorf("проверка рабочего пути: %w", err) + } + if n == 1 && buf[0] == keepaliveByte { + return nil + } + // Data from already active workers may arrive before our ping reply. + } +} diff --git a/go_client/creds_test.go b/go_client/creds_test.go index cff10da..d24046a 100644 --- a/go_client/creds_test.go +++ b/go_client/creds_test.go @@ -63,6 +63,7 @@ func TestClassifyHashCheckErrorKeepsTerminalAndTransientStatusesSeparate(t *test status string }{ {errText: "INVALID_JOIN_LINK: VK API error_code:9008", status: "dead"}, + {errText: "VK API error_code:9005 Call requires auth", status: "auth_required"}, {errText: "ANON_BLOCKED: anonymous join is disabled", status: "blocked"}, {errText: "CALL_FULL: call is full", status: "full"}, {errText: "vchat.joinConversationByLink: participant.check.flood", status: "limited"}, diff --git a/go_client/dispatcher.go b/go_client/dispatcher.go index 7ae94ae..66e2901 100644 --- a/go_client/dispatcher.go +++ b/go_client/dispatcher.go @@ -42,8 +42,10 @@ func putPktBuf(b []byte) { } const ( - returnChBuf = 384 - deviceWakeHealthGrace = 60 * time.Second + returnChBuf = 384 + deviceWakeHealthGrace = 60 * time.Second + uplinkBulkQueueCapacity = 512 + uplinkBulkQueueMaxAge = 50 * time.Millisecond // chunkSize — количество последовательных пакетов, отправляемых в один worker // перед переключением на следующий. @@ -56,8 +58,8 @@ const ( // С chunk=16 пакеты реже перескакивают между путями с разной задержкой. Это // уменьшает reorder на активной многоканальной сессии, сохраняя равномерную // загрузку всех workers. - // Reorder возможен только между chunk-границами, что покрывается WG replay - // window (2048 пакетов). + // Chunk не гарантирует порядок доставки: очереди и задержки путей различаются. + // Replay window отбрасывает старые повторы, но не восстанавливает порядок TCP. // // Все workers по-прежнему получают одинаковую долю трафика за полный цикл; // фактический выигрыш зависит от различия задержек между TURN-путями. @@ -65,6 +67,8 @@ const ( ) type WorkerSlot struct { + uplink *uplinkQuality + queue *transportQueue ID int SendCh chan []byte WakeCh chan uint64 @@ -77,6 +81,15 @@ type WorkerSlot struct { } type Dispatcher struct { + workerAttempt atomic.Uint64 + negotiatedTransport atomic.Uint32 + uplinkBulk chan timedDatagram + uplinkIngress uplinkIngressMetrics + dispatchMu sync.Mutex + uplinkRecovery uplinkRecovery + uplinkPacing *uplinkPacer + downlinkOrder transportOrder + experiment string localConn net.PacketConn clientAddr atomic.Pointer[net.Addr] workers atomic.Pointer[[]*WorkerSlot] @@ -106,9 +119,14 @@ type Dispatcher struct { wakeHealthGraceUntil atomic.Int64 } -func NewDispatcher(ctx context.Context, localConn net.PacketConn, stats *Stats) *Dispatcher { +func NewDispatcher(ctx context.Context, localConn net.PacketConn, stats *Stats, experiment ...string) *Dispatcher { dctx, dcancel := context.WithCancel(ctx) + mode := experimentStandard + if len(experiment) != 0 { + mode = experiment[0] + } d := &Dispatcher{ + experiment: mode, localConn: localConn, ReturnCh: make(chan []byte, returnChBuf), ctx: dctx, @@ -117,18 +135,44 @@ func NewDispatcher(ctx context.Context, localConn net.PacketConn, stats *Stats) updateMetadataWaiters: make(map[string]*updateMetadataAssembly), } + if mode == experimentUplink || mode == experimentAuto { + d.uplinkPacing = newUplinkPacer() + d.uplinkBulk = make(chan timedDatagram, uplinkBulkQueueCapacity) + d.wg.Add(2) + go func() { defer d.wg.Done(); d.uplinkPacing.run(dctx) }() + go d.runUplinkBulk() + } + empty := make([]*WorkerSlot, 0) d.workers.Store(&empty) d.wg.Add(2) go d.readLoop() go d.writeLoop() + if transportMetricsEnabled { + d.wg.Add(1) + go func() { + defer d.wg.Done() + t := time.NewTicker(5 * time.Second) + defer t.Stop() + for { + select { + case <-d.ctx.Done(): + return + case <-t.C: + d.downlinkOrder.report("client_downlink") + d.uplinkIngress.report(d.uplinkBulk) + } + } + }() + } return d } func (d *Dispatcher) Shutdown() { d.cancel() d.wg.Wait() + d.downlinkOrder.report("client_downlink") } func (d *Dispatcher) Register(w *WorkerSlot) { @@ -138,6 +182,9 @@ func (d *Dispatcher) Register(w *WorkerSlot) { copy(newWorkers, *oldWorkers) newWorkers[len(*oldWorkers)] = w d.workers.Store(&newWorkers) + if w.uplink != nil && d.uplinkPacing != nil { + d.uplinkPacing.registerPath(w.uplink) + } d.mu.Unlock() log.Printf("[ДИСП] Воркер #%d зарегистрирован (всего: %d)", w.ID, len(newWorkers)) @@ -160,6 +207,9 @@ func (d *Dispatcher) Unregister(slot *WorkerSlot) { } } d.workers.Store(&newWorkers) + if slot.uplink != nil && d.uplinkPacing != nil { + d.uplinkPacing.unregisterPath(slot.uplink) + } d.mu.Unlock() log.Printf("[ДИСП] Воркер #%d отключён (осталось: %d)", slot.ID, len(newWorkers)) if generation := d.wakeGeneration.Load(); generation > 0 && !d.deviceSleeping.Load() { @@ -324,12 +374,13 @@ func (d *Dispatcher) claimStalledUserTraffic(now time.Time, timeout time.Duratio // // Логика: отправляем chunkSize подряд пакетов в один worker, потом переходим // к следующему. Если текущий worker перегружен (канал полный) — немедленно -// ищем свободный worker и начинаем новый chunk на нём. Это гарантирует: -// - В рамках chunk пакеты идут через один TURN relay → in-order delivery -// - Между chunks — разные relay → максимальная агрегатная скорость -// - Нет блокировки, нет буферизации, нет дополнительного latency +// ищем свободный worker и начинаем новый chunk на нём. Порядок и пропускная +// способность зависят от потерь, очередей и задержек отдельных путей. func (d *Dispatcher) readLoop() { defer d.wg.Done() + if d.uplinkBulk != nil { + defer close(d.uplinkBulk) + } for { if err := d.ctx.Err(); err != nil { @@ -352,57 +403,122 @@ func (d *Dispatcher) readLoop() { d.clientAddr.Store(&addr) d.stats.TotalBytesUp.Add(int64(n)) - workersPtr := d.workers.Load() - if workersPtr == nil || len(*workersPtr) == 0 { + if d.usesUplink() && d.uplinkBulk != nil && n > 160 { + // Read and dispatch ACKs even while bulk pacing is waiting. Blocking + // this UDP reader would trap ACKs behind data in the socket buffer. + select { + case d.uplinkBulk <- timedDatagram{data: pkt, queued: time.Now()}: + if transportMetricsEnabled { + d.uplinkIngress.accepted.Add(1) + } + default: + if transportMetricsEnabled { + d.uplinkIngress.dropped.Add(1) + } + putPktBuf(pkt) + } + } else { + d.dispatchPacket(pkt) + } + } +} + +func (d *Dispatcher) runUplinkBulk() { + defer d.wg.Done() + for queued := range d.uplinkBulk { + pkt := queued.data + // Absorb short local bursts without keeping a slow path's old bulk + // traffic queued indefinitely. ACKs still bypass this queue entirely. + if d.expireUplinkBulk(queued) { + continue + } + var started time.Time + if transportMetricsEnabled { + started = time.Now() + } + if d.uplinkPacing.wait(d.ctx, len(pkt)) != nil { putPktBuf(pkt) continue } + if d.expireUplinkBulk(queued) { + continue + } + if transportMetricsEnabled { + d.uplinkIngress.pacingWait.observe(time.Since(started)) + d.uplinkIngress.dispatched.Add(1) + } + d.dispatchPacket(pkt) + } +} - ws := *workersPtr - nw := len(ws) - wakeGeneration := d.wakeGeneration.Load() - deviceSleeping := d.deviceSleeping.Load() +func (d *Dispatcher) expireUplinkBulk(queued timedDatagram) bool { + if time.Since(queued.queued) <= uplinkBulkQueueMaxAge { + return false + } + if transportMetricsEnabled { + d.uplinkIngress.expired.Add(1) + } + putPktBuf(queued.data) + return true +} - sent := false - idx := d.rrIndex % nw +func (d *Dispatcher) dispatchPacket(pkt []byte) { + d.dispatchMu.Lock() + defer d.dispatchMu.Unlock() + n := len(pkt) + workersPtr := d.workers.Load() + if workersPtr == nil || len(*workersPtr) == 0 { + putPktBuf(pkt) + return + } - // After wake, a registered worker is only a candidate after its own - // current-generation keepalive has returned. This keeps stale sockets - // out of the user-data round robin while healthy workers keep carrying - // traffic and the remaining sessions reconnect independently. - for offset := 0; offset < nw; offset++ { - candidateIdx := (idx + offset) % nw - candidate := ws[candidateIdx] - if !workerEligibleForWakeGeneration(candidate, wakeGeneration, deviceSleeping) { - continue + ws := *workersPtr + nw := len(ws) + wakeGeneration := d.wakeGeneration.Load() + deviceSleeping := d.deviceSleeping.Load() + + if d.usesUplink() { + ensureUplinkServiceFloor(ws, wakeGeneration, deviceSleeping) + } + + sent := false + idx := d.rrIndex % nw + + // After wake, a registered worker is only a candidate after its own + // current-generation keepalive has returned. This keeps stale sockets + // out of the user-data round robin while healthy workers keep carrying + // traffic and the remaining sessions reconnect independently. + for offset := 0; offset < nw; offset++ { + candidateIdx := (idx + offset) % nw + candidate := ws[candidateIdx] + if !workerEligibleForWakeGeneration(candidate, wakeGeneration, deviceSleeping) || (n > 160 && candidate.uplink != nil && candidate.uplink.muted.Load()) { + continue + } + if candidate.offerData(pkt) { + sent = true + if offset == 0 { + d.rrCount++ + } else { + d.rrIndex = candidateIdx + d.rrCount = 1 } - select { - case candidate.SendCh <- pkt: - sent = true - if offset == 0 { - d.rrCount++ - } else { - d.rrIndex = candidateIdx - d.rrCount = 1 - } - if d.rrCount >= chunkSize { - d.rrIndex = (candidateIdx + 1) % nw - d.rrCount = 0 - } - default: - } - if sent { - break + rotate := d.rrCount >= chunkSize + if rotate { + d.rrIndex = (candidateIdx + 1) % nw + d.rrCount = 0 } } - - if !sent { - // Все workers перегружены — сдвигаем указатель, пакет дропается - d.rrIndex = (idx + 1) % nw - d.rrCount = 0 - putPktBuf(pkt) + if sent { + break } } + + if !sent { + // Все workers перегружены — сдвигаем указатель, пакет дропается + d.rrIndex = (idx + 1) % nw + d.rrCount = 0 + putPktBuf(pkt) + } } func (d *Dispatcher) writeLoop() { @@ -413,6 +529,7 @@ func (d *Dispatcher) writeLoop() { case <-d.ctx.Done(): return case pkt := <-d.ReturnCh: + d.downlinkOrder.observe(pkt) addrPtr := d.clientAddr.Load() if addrPtr == nil { putPktBuf(pkt) diff --git a/go_client/go.mod b/go_client/go.mod index 9948fa8..faf86f8 100644 --- a/go_client/go.mod +++ b/go_client/go.mod @@ -3,6 +3,7 @@ module wg-turn-client go 1.26 require ( + wdtt.local/pathprobe v0.0.0 github.com/Diniboy1123/connect-ip-go v0.0.0-20260613064811-66cba32d7d33 github.com/bogdanfinn/fhttp v0.6.8 github.com/bogdanfinn/tls-client v1.15.1 @@ -18,6 +19,7 @@ require ( golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 ) + require ( github.com/andybalholm/brotli v1.2.0 // indirect github.com/bdandy/go-errors v1.2.2 // indirect @@ -40,3 +42,5 @@ require ( golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c // indirect ) + +replace wdtt.local/pathprobe => ../pathprobe diff --git a/go_client/group.go b/go_client/group.go index 40e07f4..7db72a8 100644 --- a/go_client/group.go +++ b/go_client/group.go @@ -474,6 +474,11 @@ func WorkerGroup( } } + if tp.Auto != nil { + if err := configStartGate.wait(ctx, getConfig); err != nil { + return + } + } hashCandidates := workerHashCandidates(tp.Hashes, hashIndex, requestedWorkers, hashFallback) selectedHash := 0 hash := hashCandidates[selectedHash] @@ -481,6 +486,11 @@ func WorkerGroup( credStreamID := groupID * 100 fetchCredentials := func(candidateHash string) credentialFetchResult { + if tp.Auto != nil { + if err := tp.Auto.waitAvailable(ctx); err != nil { + return credentialFetchResult{err: err} + } + } return credentialRequests.fetch(ctx, func() (string, string, []string, error) { return GetCreds(ctx, candidateHash, credStreamID) }) @@ -688,6 +698,12 @@ func WorkerGroup( if ctx.Err() != nil { return } + if errors.Is(sessErr, errUplinkPathReplacement) { + // Local delivery failure does not invalidate VK credentials. + // The dispatcher has already granted a bounded recovery permit. + turnCandidateRetry++ + continue + } relayHandshakeFailed := shouldRotateTurnCandidateAfterSessionError(sessErr) if relayHandshakeFailed { turnCandidateRetry++ @@ -729,8 +745,14 @@ func WorkerGroup( } if strings.Contains(errStr, "хеш мёртв") || - strings.Contains(errStr, "FATAL_AUTH") { + strings.Contains(errStr, "FATAL_AUTH") || strings.Contains(errStr, "FATAL_TRANSPORT") { log.Printf("[ВОРКЕР #%d] Фатальная ошибка: %s", wid, errStr) + if strings.Contains(errStr, "FATAL_TRANSPORT") { + // Other groups may still be waiting for this group's + // configuration. An unsupported mode cannot recover by + // retrying workers, even without an Android log reader. + cancel() + } return } @@ -742,6 +764,7 @@ func WorkerGroup( log.Printf("[ВОРКЕР #%d] [TURN] Ошибка allocation/кредов, обновляем TURN-креды и повторяем (попытка %d): %s", wid, attempt, errStr) refreshResult = refreshCreds("TURN allocation error", credsRevision) } else if turnCapacityLimited { + d.uplinkRecovery.capacityLimited(time.Now()) startedRound, round, waitErr := turnCapacityGate.wait(ctx, wid) if startedRound { log.Printf("[ВОРКЕР #%d] [TURN] Узел временно ограничил новые allocation; снижаем темп повторов (раунд %d), креды сохранены: %s", wid, round, errStr) @@ -750,7 +773,7 @@ func WorkerGroup( return } continue - } else if relayHandshakeFailed && + } else if tp.Auto == nil && relayHandshakeFailed && hashFallback && len(credsSnapshot.TurnURLs) > 0 && turnCandidateRetry%len(credsSnapshot.TurnURLs) == 0 { @@ -894,6 +917,9 @@ func normalizeVKJoinHash(input string) string { // TurnParams — конфигурация TURN type TurnParams struct { + Auto *connectionPolicy + NoUDP bool + Experiment string Host string Port string Hashes []string diff --git a/go_client/main.go b/go_client/main.go index 1210433..40f62d1 100644 --- a/go_client/main.go +++ b/go_client/main.go @@ -142,6 +142,8 @@ func classifyHashCheckError(err error) (string, string) { } text := strings.ToLower(err.Error()) switch { + case strings.Contains(text, "error_code:9005") || strings.Contains(text, "call requires auth"): + return "auth_required", "Звонок требует входа в ВК и не подходит для подключения" case strings.Contains(text, "captcha_required") || strings.Contains(text, "captcha_wait_required"): return "captcha", "VK просит капчу" case strings.Contains(text, "invalid_join_link") || @@ -267,21 +269,7 @@ func main() { // Сигналы sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT) - go func() { - select { - case s := <-sig: - log.Printf("[КЛИЕНТ] Сигнал %v, завершаю...", s) - cancel() - case <-ctx.Done(): - return - } - select { - case s := <-sig: - log.Printf("[КЛИЕНТ] Повторный %v, принудительный выход", s) - os.Exit(1) - case <-ctx.Done(): - } - }() + go runNativeShutdownGuard(ctx, cancel, sig, os.Exit, 1250*time.Millisecond) var pauseFlag int32 var activeDispatcher atomic.Pointer[Dispatcher] @@ -289,6 +277,8 @@ func main() { deviceSleeping := false startupConfigCh := make(chan nativeStartupConfigResult, 1) + var connectionController atomic.Pointer[connectionPolicy] + connectionController.Store(newConnectionPolicy("", false)) // STDIN для конфигурации запуска, PAUSE/RESUME/STOP и CAPTCHA_RESULT. // Секреты запуска не передаются через argv/environment, где их может // прочитать системная диагностика Android. @@ -297,7 +287,11 @@ func main() { scanner.Buffer(make([]byte, 4096), 48*1024) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) + if controller := connectionController.Load(); controller != nil { + controller.command(line) + } switch { + case line == "CONNECTION_NETWORK" || line == "CONNECTION_OFFLINE" || line == "CONNECTION_ONLINE": case strings.HasPrefix(line, startupConfigPrefix): secrets, err := decodeNativeStartupSecrets(strings.TrimPrefix(line, startupConfigPrefix)) select { @@ -428,16 +422,19 @@ func main() { "использовать остальные VK-хеши как резерв групп", ) + experiment := flag.String("transport-experiment", experimentAuto, "transport compatibility: auto|standard|uplink") + metrics := flag.Bool("transport-metrics", false, "обезличенные метрики очередей и порядка пакетов") deviceID := flag.String("device-id", "unknown", "уникальный ID устройства") deviceInfo := flag.String("device-info", "", "JSON с безопасной информацией об устройстве") transportSessionFlag := flag.String("transport-session", "", "поколение текущего запуска транспорта") connPassword := flag.String("password", "", "пароль подключения") captchaMode := flag.String("captcha-mode", "auto", "режим обхода капчи (auto/wv/rjs)") vkCallsPreflight := flag.Bool("vkcalls-preflight", true, "пробовать VKCalls до captcha-цепочки") + connectionUDPBackoff := flag.Int("connection-udp-backoff", 0, "пауза после недавнего отказа UDP, секунды") turnStreamFirst := flag.Bool( "turn-stream-first", false, - "сначала пробовать TURN/TLS и TURN/TCP, сохраняя UDP как резерв", + "использовать только TURN/TLS, TURN/TCP и MASQUE HTTP/2", ) turnSNI := flag.String( "turn-sni", @@ -447,7 +444,7 @@ func main() { rtMasque := flag.Bool( "rt-masque", false, - "после прямых путей Сети РТ пробовать WARP CONNECT-IP по HTTP/2 и HTTP/3", + "резерв WARP CONNECT-IP по разрешённым протоколам HTTP/2 и HTTP/3", ) rtMasqueConfig := flag.String( "rt-masque-config", @@ -483,6 +480,7 @@ func main() { proxyAllowedCIDR := flag.String("proxy-allow-cidr", "", "разрешённая подсеть клиента для LAN-прокси") flag.Parse() + transportMetricsEnabled = *metrics var startupSecrets nativeStartupSecrets if *startupConfigStdin { select { @@ -530,21 +528,17 @@ func main() { } activeCaptchaMode := setCaptchaMode(*captchaMode) setVKCallsPreflight(*vkCallsPreflight) - var normalizedTurnSNI string - if *turnStreamFirst { - var turnSNIErr error - normalizedTurnSNI, turnSNIErr = normalizeTURNFrontSNI(*turnSNI) - if turnSNIErr != nil { - log.Fatalf("[КЛИЕНТ] Некорректный TURN SNI: %v", turnSNIErr) - } - if normalizedTurnSNI != "" { - log.Printf("[TURN] Режим «Сеть РТ»: TURN/TLS, затем TCP ко всем адресам VK с разделением первого STUN-запроса; UDP остаётся резервом; внешний TLS SNI=%s", normalizedTurnSNI) - } else { - log.Printf("[TURN] Режим «Сеть РТ»: TURN/TLS, затем TCP ко всем адресам VK с разделением первого STUN-запроса; UDP остаётся резервом") - } + normalizedTurnSNI, turnSNIErr := normalizeTURNFrontSNI(*turnSNI) + if turnSNIErr != nil { + log.Fatalf("[КЛИЕНТ] Некорректный TURN SNI: %v", turnSNIErr) } - if *rtMasque && !*turnStreamFirst { - log.Printf("[MASQUE] Проигнорирован: механизм доступен только вместе с режимом «Сеть РТ»") + mode := "UDP: сначала UDP, при недоступности — TCP/TLS" + if *turnStreamFirst { + mode = "TCP/TLS: внешний UDP и HTTP/3 запрещены" + } + log.Printf("[ПОДКЛЮЧЕНИЕ] %s", mode) + if normalizedTurnSNI != "" { + log.Printf("[TURN] Внешний TLS SNI=%s", normalizedTurnSNI) } if *vkHash == "" { @@ -618,26 +612,35 @@ func main() { *numW = workersPerGroup } *numW = (*numW / workersPerGroup) * workersPerGroup - useConfigFirstStart := *configFirstStart + useConfigFirstStart := true // Both connection modes verify the server before adding workers. + _ = configFirstStart // Retained CLI option for callers using the existing startup contract. useHashFallback := *hashFallback var masqueManager *warpMasqueManager - if *turnStreamFirst && *rtMasque { + if *rtMasque { if err := configureWarpAPIRelay(*warpAPIRelay); err != nil { log.Printf("[MASQUE] Локальный выход для регистрации WARP отклонён: %v; продолжаем прямые попытки", err) } masqueManager, err = newWarpMasqueManager(ctx, *rtMasqueConfig, normalizedTurnSNI, *rtMasqueAcceptTOS) if err != nil { - log.Printf("[MASQUE] Не удалось включить новый механизм: %v; прямые пути «Сети РТ» остаются доступны", err) + log.Printf("[MASQUE] Не удалось подготовить резерв: %v; подключение без MASQUE остаётся доступно", err) masqueManager = nil } else { defer masqueManager.Close() - log.Printf("[MASQUE] Включён резерв после прямых путей: HTTP/2 (TCP/443), затем HTTP/3 (QUIC/443)") - go masqueManager.prewarmConfig() + masqueManager.singleEnrollment = true + if *turnStreamFirst { + log.Print("[MASQUE] Включён резерв: только HTTP/2 (TCP/443); HTTP/3 запрещён режимом TCP/TLS") + } else { + log.Print("[MASQUE] Включён резерв: доступны HTTP/2 (TCP/443) и HTTP/3 (QUIC/443)") + } } } + if err := validateTransportExperiment(*experiment); err != nil { + log.Fatal(err) + } tp := &TurnParams{ + Experiment: *experiment, Host: *host, Port: *port, Hashes: hashes, @@ -646,10 +649,25 @@ func main() { WrapKey: wrapKey, } + tp.NoUDP = *turnStreamFirst + { + tp.Auto = connectionController.Load() + tp.Auto.configure("", *turnStreamFirst) + tp.Auto.deferUDP(time.Duration(max(0, min(300, *connectionUDPBackoff))) * time.Second) + transportLifecycleMu.Lock() + if deviceSleeping { + tp.Auto.command("DEVICE_SLEEP") + } + if atomic.LoadInt32(&pauseFlag) != 0 { + tp.Auto.command("PAUSE") + } + connectionController.Store(tp.Auto) + transportLifecycleMu.Unlock() + } // Слушаем локально с ожиданием (если старый процесс еще не убит Parent Watcher'ом) var localConn net.PacketConn actualListenAddr := *listen - for i := 0; i < 5; i++ { + for i := 0; localConn == nil && i < 5; i++ { localConn, err = net.ListenPacket("udp", actualListenAddr) if err == nil { break @@ -714,7 +732,7 @@ func main() { }() go stats.RunLoop(shutdownCh) - disp := NewDispatcher(ctx, localConn, stats) + disp := NewDispatcher(ctx, localConn, stats, *experiment) disp.setUnansweredUserTrafficHealthEnabled(normalizedClientMode == "vpn") transportLifecycleMu.Lock() activeDispatcher.Store(disp) @@ -787,7 +805,12 @@ func main() { }, ) if err != nil && ctx.Err() == nil { - log.Printf("PROXY_ERROR|%v", err) + if address, portInUse := proxyPortInUseAddress(err); portInUse { + log.Printf("[ПРОКСИ] Порт занят: %s", address) + log.Printf("PROXY_ERROR|port_in_use|%s", address) + } else { + log.Printf("PROXY_ERROR|startup|%v", err) + } cancel() } return diff --git a/go_client/masque_warp.go b/go_client/masque_warp.go index faf679c..d6aa2d7 100644 --- a/go_client/masque_warp.go +++ b/go_client/masque_warp.go @@ -2,7 +2,7 @@ package main // The Cloudflare WARP MASQUE interoperability in this file is adapted from // Diniboy1123/usque (MIT, commit 6aa03fc97d12848dce34eedbd187fb1077b5d1ea). -// It is intentionally isolated behind the explicit Android «Сеть РТ» + +// It is intentionally isolated behind the explicit Android «Авто»/«TCP/TLS» + // «MASQUE» opt-in. The ordinary WDTT transport never constructs this manager. import ( @@ -70,7 +70,7 @@ var ( // warpAPIFragmentConn divides only the first TLS ClientHello write. It leaves // DNS, addresses, certificate validation and all later HTTPS bytes untouched. // The wrapper is used only after a normal WARP API TLS handshake times out and -// only while the explicit Android «Сеть РТ» + «MASQUE» mode is enrolling. +// only while the explicit Android «Авто»/«TCP/TLS» + «MASQUE» mode is enrolling. type warpAPIFragmentConn struct { net.Conn mu sync.Mutex @@ -1224,10 +1224,12 @@ func (transport *warpMasqueTransport) DialContext(ctx context.Context, target st } type warpMasqueManager struct { - ctx context.Context - path string - sni string - acceptTOS bool + singleEnrollment bool + enrollmentAttempted bool + ctx context.Context + path string + sni string + acceptTOS bool mu sync.Mutex config *warpMasqueConfig @@ -1284,6 +1286,10 @@ func (manager *warpMasqueManager) ensureConfigLocked() (*warpMasqueConfig, error if !manager.acceptTOS { return nil, errors.New("для первой регистрации WARP требуется согласие с условиями Cloudflare") } + if manager.singleEnrollment && manager.enrollmentAttempted { + return nil, errors.New("регистрация WARP уже запрашивалась; повтор только после нового подключения") + } + manager.enrollmentAttempted = true logMasque("регистрация начата: этап 1/4 — создаём отдельное устройство WARP в Cloudflare") enrollCtx, cancel := context.WithTimeout(manager.ctx, 40*time.Second) defer cancel() diff --git a/go_client/obfs.go b/go_client/obfs.go index 46804a8..628c417 100644 --- a/go_client/obfs.go +++ b/go_client/obfs.go @@ -102,6 +102,10 @@ func obfsBuildNonce(ssrc uint32, seq uint16, ts uint32) []byte { // // [V=2,P=1,X=0,CC=0 | PT | SeqNum | Timestamp | SSRC | encrypted_payload | padding | padLen] func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]byte, error) { + return obfsWrapPacketInto(nil, key, payload, cfg, state) +} + +func obfsWrapPacketInto(dst, key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]byte, error) { if len(key) != wrapKeyLen { return nil, fmt.Errorf("obfs: key must be %d bytes (got %d)", wrapKeyLen, len(key)) } @@ -131,7 +135,12 @@ func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]b // Allocate output: 12 (header) + payload + AEAD tag + padTotal outLen := 12 + len(payload) + chacha20poly1305.Overhead + padTotal - out := make([]byte, outLen) + var out []byte + if cap(dst) >= outLen { + out = dst[:outLen] + } else { + out = make([]byte, outLen) + } // RTP Header (12 bytes) out[0] = 0x80 | 0x20 // V=2, P=1 (padding present) diff --git a/go_client/protocol.go b/go_client/protocol.go index b34cb8c..2139023 100644 --- a/go_client/protocol.go +++ b/go_client/protocol.go @@ -8,6 +8,7 @@ import ( "strconv" "strings" "time" + "wdtt.local/pathprobe" ) type workerPolicyLimitError struct { @@ -65,6 +66,7 @@ func RequestConfig( ctx context.Context, conn net.Conn, localPort, deviceID, password, deviceInfo, transportSession string, + worker ...pathprobe.Worker, ) (string, error) { payload := fmt.Sprintf("GETCONF:%s|%s|%s", localPort, deviceID, password) safeDeviceInfo := strings.ReplaceAll(strings.TrimSpace(deviceInfo), "|", " ") @@ -74,6 +76,9 @@ func RequestConfig( } if safeTransportSession != "" { payload += "|" + safeTransportSession + if len(worker) > 0 && worker[0].Valid() { + payload += "|" + worker[0].String() + } } if _, err := conn.Write([]byte(payload)); err != nil { return "", fmt.Errorf("отправка GETCONF: %w", err) diff --git a/go_client/proxy_server.go b/go_client/proxy_server.go index 01048f5..e162625 100644 --- a/go_client/proxy_server.go +++ b/go_client/proxy_server.go @@ -10,6 +10,7 @@ import ( "net/netip" "strings" "sync" + "syscall" "time" ) @@ -20,6 +21,30 @@ type proxyListener struct { access proxyAccessPolicy } +type proxyListenError struct { + Address string + Err error +} + +func (err *proxyListenError) Error() string { + return fmt.Sprintf("прокси не смог занять %s: %v", err.Address, err.Err) +} + +func (err *proxyListenError) Unwrap() error { + return err.Err +} + +func proxyPortInUseAddress(err error) (string, bool) { + if !errors.Is(err, syscall.EADDRINUSE) { + return "", false + } + var listenErr *proxyListenError + if !errors.As(err, &listenErr) || listenErr.Address == "" { + return "", false + } + return listenErr.Address, true +} + type bufferedProxyConn struct { net.Conn reader io.Reader @@ -106,7 +131,7 @@ func runUnifiedProxyServer( for _, opened := range listeners { _ = opened.listener.Close() } - return fmt.Errorf("прокси не смог занять %s: %w", address, listenErr) + return &proxyListenError{Address: address, Err: listenErr} } listeners = append(listeners, proxyListener{listener: listener, access: policies[index]}) } diff --git a/go_client/proxy_server_test.go b/go_client/proxy_server_test.go index 2071540..036f432 100644 --- a/go_client/proxy_server_test.go +++ b/go_client/proxy_server_test.go @@ -60,6 +60,123 @@ func TestValidateProxyListenAddressesRejectsUnsafeCombinations(t *testing.T) { } } +func TestUnifiedProxyReportsFirstListenerPortInUse(t *testing.T) { + occupied, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer occupied.Close() + + err = runUnifiedProxyServer( + context.Background(), + "auto", + []string{occupied.Addr().String()}, + systemSocksDialer{}, + false, + "", + "", + true, + "", + nil, + ) + address, portInUse := proxyPortInUseAddress(err) + if !portInUse || address != occupied.Addr().String() { + t.Fatalf("port conflict = %q, %t; error=%v", address, portInUse, err) + } +} + +func TestUnifiedProxyClosesFirstListenerWhenSecondPortIsInUse(t *testing.T) { + portSource, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + _, port, err := net.SplitHostPort(portSource.Addr().String()) + if err != nil { + t.Fatal(err) + } + _ = portSource.Close() + + firstAddress := net.JoinHostPort("127.0.0.1", port) + secondAddress := net.JoinHostPort("127.0.0.2", port) + occupiedSecond, err := net.Listen("tcp4", secondAddress) + if err != nil { + t.Skipf("second loopback address is unavailable: %v", err) + } + defer occupiedSecond.Close() + + err = runUnifiedProxyServer( + context.Background(), + "socks5", + []string{firstAddress, secondAddress}, + systemSocksDialer{}, + false, + "", + "", + true, + "", + nil, + ) + address, portInUse := proxyPortInUseAddress(err) + if !portInUse || address != secondAddress { + t.Fatalf("second conflict = %q, %t; error=%v", address, portInUse, err) + } + + reopenedFirst, err := net.Listen("tcp4", firstAddress) + if err != nil { + t.Fatalf("first listener remained open after transactional failure: %v", err) + } + _ = reopenedFirst.Close() +} + +func TestUnifiedProxyReadyForEveryMode(t *testing.T) { + for _, mode := range []string{"socks5", "http", "auto"} { + t.Run(mode, func(t *testing.T) { + reserved, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + listenAddress := reserved.Addr().String() + _ = reserved.Close() + ctx, cancel := context.WithCancel(context.Background()) + ready := make(chan []string, 1) + done := make(chan error, 1) + go func() { + done <- runUnifiedProxyServer( + ctx, + mode, + []string{listenAddress}, + systemSocksDialer{}, + false, + "", + "", + true, + "", + func(addresses []string) { ready <- addresses }, + ) + }() + select { + case addresses := <-ready: + if len(addresses) != 1 || addresses[0] != listenAddress { + t.Fatalf("ready addresses=%v", addresses) + } + case err := <-done: + t.Fatalf("proxy failed before ready: %v", err) + case <-time.After(2 * time.Second): + t.Fatal("proxy did not become ready") + } + cancel() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("proxy did not stop") + } + }) + } +} + func TestAutoProxyDetectsSOCKSAndHTTPWithoutWaitingForMoreData(t *testing.T) { for name, greeting := range map[string][]byte{ "SOCKS5": {socksVersion5}, diff --git a/go_client/session.go b/go_client/session.go index d93390f..809bf04 100644 --- a/go_client/session.go +++ b/go_client/session.go @@ -14,6 +14,8 @@ import ( "sync/atomic" "time" + "wdtt.local/pathprobe" + "github.com/cbeuw/connutil" "github.com/pion/dtls/v3" "github.com/pion/dtls/v3/pkg/crypto/selfsign" @@ -199,7 +201,7 @@ func (c *connectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) { return c // splitFirstWriteConn fragments the first STUN request so its magic cookie // crosses TCP segment boundaries. Some shallow DPI rules classify plain TURN // by looking only at the first segment. This wrapper is enabled exclusively by -// the explicit «Сеть РТ» mode; ordinary operators keep the original writes. +// stream-first connection modes; ordinary mode keeps the original writes. type splitFirstWriteConn struct { net.Conn splitAt int @@ -264,7 +266,7 @@ func normalizeTURNFrontSNI(value string) (string, error) { return host, nil } -func verifyTURNCertificateChainWithoutHostname(state tls.ConnectionState) error { +func verifyTURNPeerCertificate(state tls.ConnectionState, hostname string, roots *x509.CertPool) error { if len(state.PeerCertificates) == 0 { return fmt.Errorf("TURN TLS не прислал сертификат") } @@ -274,6 +276,8 @@ func verifyTURNCertificateChainWithoutHostname(state tls.ConnectionState) error } _, err := state.PeerCertificates[0].Verify(x509.VerifyOptions{ Intermediates: intermediates, + Roots: roots, + DNSName: hostname, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, }) if err != nil { @@ -293,11 +297,13 @@ func turnTLSConfig(endpoint turnEndpoint, frontSNI string) *tls.Config { } // При подмене SNI имя сертификата ожидаемо относится к TURN-узлу, а не к - // домену белого списка. Отключаем только сопоставление имени: публичная CA- - // цепочка всё равно проверяется в VerifyConnection. + // домену белого списка. VerifyConnection проверяет цепочку И настоящее + // имя TURN-узла из реквизитов; frontSNI не является доверенной личностью. if frontSNI != "" && !strings.EqualFold(frontSNI, endpoint.Host) { config.InsecureSkipVerify = true // проверка перенесена в VerifyConnection - config.VerifyConnection = verifyTURNCertificateChainWithoutHostname + config.VerifyConnection = func(state tls.ConnectionState) error { + return verifyTURNPeerCertificate(state, endpoint.Host, nil) + } } return config } @@ -332,14 +338,12 @@ func openTURNAllocation( var turnConn net.PacketConn switch endpoint.Transport { case turnTransportUDP: - resolved, err := net.ResolveUDPAddr("udp", turnAddr) - if err != nil { - return nil, nil, fmt.Errorf("TURN UDP резолв %s: %w", turnAddr, err) - } - c, err := net.DialUDP("udp", nil, resolved) + dialer := &net.Dialer{Timeout: 6 * time.Second} + raw, err := dialer.DialContext(ctx, "udp", turnAddr) if err != nil { return nil, nil, fmt.Errorf("TURN UDP подключение %s: %w", turnAddr, err) } + c := raw.(*net.UDPConn) _ = c.SetReadBuffer(socketBufSize) _ = c.SetWriteBuffer(socketBufSize) turnConn = &connectedUDPConn{c} @@ -372,6 +376,8 @@ func openTURNAllocation( return nil, nil, fmt.Errorf("неподдерживаемый TURN transport: %s", endpoint.Transport) } + stop := context.AfterFunc(ctx, func() { _ = turnConn.Close() }) + defer stop() return allocateTURNOnConn(endpoint, peer, creds, turnConn) } @@ -381,6 +387,14 @@ func allocateTURNOnConn( creds *Credentials, turnConn net.PacketConn, ) (*turn.Client, net.PacketConn, error) { + deletion := &turnDeletionTransport{PacketConn: turnConn, ack: make(chan struct{})} + turnConn = deletion + owned := false + defer func() { + if !owned { + _ = turnConn.Close() + } + }() turnAddr := endpoint.address() // RequestedAddressFamily @@ -401,7 +415,6 @@ func allocateTURNOnConn( LoggerFactory: &NullLoggerFactory{}, }) if err != nil { - _ = turnConn.Close() return nil, nil, fmt.Errorf("TURN %s клиент %s: %w", endpoint.label(), turnAddr, err) } @@ -424,7 +437,8 @@ func allocateTURNOnConn( return nil, nil, fmt.Errorf("TURN %s Allocate %s: %w", endpoint.label(), turnAddr, err) } - return tc, relay, nil + owned = true + return tc, &ownedTURNAllocation{PacketConn: relay, transport: turnConn, closeClient: tc.Close, deletion: deletion}, nil } func openTURNAllocationOverMasque( @@ -456,6 +470,8 @@ func openTURNAllocationOverMasque( conn = tlsConn } + stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) + defer stop() return allocateTURNOnConn(endpoint, peer, creds, turn.NewSTUNConn(conn)) } @@ -516,8 +532,11 @@ func RunSession( preferTURNStream bool, turnCandidateRetry int, onTURNAllocated func(), -) (bool, error) { +) (delivered bool, sessionErr error) { + replacingUplink, recoveryComplete := d.uplinkRecovery.completion(sessionID) + defer recoveryComplete() configDelivered := false + useWrap := len(tp.WrapKey) == wrapKeyLen if len(creds.TurnURLs) == 0 { return false, fmt.Errorf("нет TURN URL в учетных данных") @@ -532,6 +551,45 @@ func RunSession( if len(candidates) == 0 { return false, fmt.Errorf("нет пригодных TURN URL в учетных данных") } + var autoLease *connectionLease + var startupTimer *time.Timer + if tp.Auto != nil { + outerCtx := ctx + var acquireErr error + autoLease, acquireErr = tp.Auto.acquire(ctx, connectionPaths(candidates, tp, tp.NoUDP)) + if acquireErr != nil { + return false, acquireErr + } + defer func() { + failure := sessionErr + if errors.Is(context.Cause(ctx), context.DeadlineExceeded) { + failure = context.DeadlineExceeded + } + autoLease.finish(failure, outerCtx.Err() != nil) + }() + var cancelCause context.CancelCauseFunc + ctx, cancelCause = context.WithCancelCause(ctx) + attemptCancel := func() { cancelCause(context.Canceled) } + autoLease.bind(attemptCancel) + defer attemptCancel() + // Includes Allocate, relay handshake and authenticated registration. + budget := 30 * time.Second + if autoLease.path.masque != "" { + budget = 60 * time.Second + } + startupTimer = time.AfterFunc(budget, func() { cancelCause(context.DeadlineExceeded) }) + defer startupTimer.Stop() + candidates = []turnEndpoint{autoLease.path.endpoint} + } + if tp.NoUDP { + filtered := candidates[:0] + for _, c := range candidates { + if c.Transport != turnTransportUDP { + filtered = append(filtered, c) + } + } + candidates = filtered + } directCandidates, masqueCandidates, finalUDPCandidates := turnCandidateStages(candidates, tp.Masque != nil) var tc *turn.Client @@ -540,51 +598,29 @@ func RunSession( var selectedMasqueProtocol warpMasqueProtocol var lastTURNErr error var err error - for idx, candidate := range directCandidates { - if !preferTURNStream && idx == 0 { - log.Printf("[СЕССИЯ #%d] TURN %s (%s)", sessionID, candidate.label(), candidate.address()) - } else if !preferTURNStream { - log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s) после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr) - } else if idx == 0 { - log.Printf("[СЕССИЯ #%d] [TURN] Путь %s (%s), %s", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream)) + if autoLease != nil { + p := autoLease.path + if p.masque != "" { + tc, relay, err = openTURNAllocationOverMasque(ctx, p.endpoint, peer, creds, tp.Masque, p.masque) } else { - log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s), %s, после ошибки: %v", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream), lastTURNErr) + tc, relay, err = openTURNAllocation(ctx, p.endpoint, peer, creds, sessionID, p.front, true) } - - tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream) - if err == nil { - selectedEndpoint = candidate - break - } - lastTURNErr = err - if isCredentialTURNError(err) { + if err != nil { return false, err } - } - if relay == nil && tp.Masque != nil { - log.Printf("[СЕССИЯ #%d] [MASQUE] Прямые TCP/TLS-пути «Сети РТ» не сработали; до UDP пробуем WARP CONNECT-IP: %v", sessionID, lastTURNErr) - masqueProtocols: - for _, protocol := range tp.Masque.protocolOrder() { - for _, candidate := range masqueCandidates { - log.Printf("[СЕССИЯ #%d] [MASQUE] Пробуем TURN %s (%s) внутри CONNECT-IP %s", sessionID, candidate.label(), candidate.address(), protocol) - tc, relay, err = openTURNAllocationOverMasque(ctx, candidate, peer, creds, tp.Masque, protocol) - if err == nil { - selectedEndpoint = candidate - selectedMasqueProtocol = protocol - tp.Masque.markPreferred(protocol) - break masqueProtocols - } - lastTURNErr = err - log.Printf("[СЕССИЯ #%d] [MASQUE] %s через %s не сработал: %v", sessionID, candidate.label(), protocol, err) - if isCredentialTURNError(err) { - return false, err - } + selectedEndpoint, selectedMasqueProtocol = p.endpoint, p.masque + } else { + for idx, candidate := range directCandidates { + if !preferTURNStream && idx == 0 { + log.Printf("[СЕССИЯ #%d] TURN %s (%s)", sessionID, candidate.label(), candidate.address()) + } else if !preferTURNStream { + log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s) после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr) + } else if idx == 0 { + log.Printf("[СЕССИЯ #%d] [TURN] Путь %s (%s), %s", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream)) + } else { + log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s), %s, после ошибки: %v", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream), lastTURNErr) } - } - } - if relay == nil && tp.Masque != nil { - for _, candidate := range finalUDPCandidates { - log.Printf("[СЕССИЯ #%d] [TURN] Последний резерв после MASQUE: %s (%s), после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr) + tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream) if err == nil { selectedEndpoint = candidate @@ -595,11 +631,51 @@ func RunSession( return false, err } } + if relay == nil && tp.Masque != nil { + log.Printf("[СЕССИЯ #%d] [MASQUE] Прямые TCP/TLS-пути не сработали; пробуем резерв MASQUE: %v", sessionID, lastTURNErr) + masqueProtocols: + for _, protocol := range tp.Masque.protocolOrder() { + if tp.NoUDP && protocol == warpMasqueHTTP3 { + continue + } + for _, candidate := range masqueCandidates { + log.Printf("[СЕССИЯ #%d] [MASQUE] Пробуем TURN %s (%s) внутри CONNECT-IP %s", sessionID, candidate.label(), candidate.address(), protocol) + tc, relay, err = openTURNAllocationOverMasque(ctx, candidate, peer, creds, tp.Masque, protocol) + if err == nil { + selectedEndpoint = candidate + selectedMasqueProtocol = protocol + tp.Masque.markPreferred(protocol) + break masqueProtocols + } + lastTURNErr = err + log.Printf("[СЕССИЯ #%d] [MASQUE] %s через %s не сработал: %v", sessionID, candidate.label(), protocol, err) + if isCredentialTURNError(err) { + return false, err + } + } + } + } + if relay == nil && tp.Masque != nil { + for _, candidate := range finalUDPCandidates { + log.Printf("[СЕССИЯ #%d] [TURN] Последний резерв после MASQUE: %s (%s), после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr) + tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream) + if err == nil { + selectedEndpoint = candidate + break + } + lastTURNErr = err + if isCredentialTURNError(err) { + return false, err + } + } + } + } + if relay == nil && lastTURNErr == nil { + return false, fmt.Errorf("нет разрешённых путей подключения") } if lastTURNErr != nil && relay == nil { return false, lastTURNErr } - defer tc.Close() defer relay.Close() // Reset error count on successful allocation @@ -640,8 +716,6 @@ func RunSession( var relayWg sync.WaitGroup relayWg.Add(2) - useWrap := len(tp.WrapKey) == wrapKeyLen - // Initialize obfs config per session var obfsCfg *ObfsConfig var obfsWriteState *ObfsState @@ -693,6 +767,7 @@ func RunSession( defer relayWg.Done() defer sessCancel() b := make([]byte, readBufSize) + var reusableWrap []byte for { n, _, readErr := pipeA.ReadFrom(b) if readErr != nil { @@ -701,7 +776,7 @@ func RunSession( out := b[:n] if useWrap { if obfsCfg != nil && obfsWriteState != nil { - wrapped, wrapErr := obfsWrapPacket(tp.WrapKey, out, obfsCfg, obfsWriteState) + wrapped, wrapErr := obfsWrapPacketInto(reusableWrap, tp.WrapKey, out, obfsCfg, obfsWriteState) if wrapErr != nil { log.Printf("[СЕССИЯ #%d] OBFS wrap: %v", sessionID, wrapErr) return @@ -715,6 +790,18 @@ func RunSession( } }() + // Handshake, admission and experiment negotiation can all return early. + // Close both directions before joining so a failed path cannot leave a + // blocked pipe writer or TURN reader alive until process shutdown. + defer func() { + sessCancel() + _ = relay.Close() + _ = pipeA.Close() + _ = pipeB.Close() + relayWg.Wait() + sessionWg.Wait() + }() + // DTLS с поддержкой Connection ID (без SNI) cert, err := selfsign.GenerateSelfSigned() if err != nil { @@ -722,6 +809,9 @@ func RunSession( } // Acquire handshake semaphore + if autoLease != nil { + autoLease.setStage("dtls") + } select { case handshakeSem <- struct{}{}: case <-sessCtx.Done(): @@ -769,15 +859,12 @@ func RunSession( }) defer stopDTLS() - stats.ActiveConnections.Add(1) - globalActiveConnections.Add(1) - defer func() { - stats.ActiveConnections.Add(-1) - globalActiveConnections.Add(-1) - }() - + transportMode := tp.Experiment // Запрос конфига - if getConfig && configCh != nil { + { // Every worker must authenticate its device before joining the relay. + if autoLease != nil { + autoLease.setStage("registration") + } conf, confErr := RequestConfig( sessCtx, dtlsConn, @@ -786,6 +873,7 @@ func RunSession( password, deviceInfo, transportSession, + pathprobe.Worker{Slot: uint32(sessionID), Attempt: d.workerAttempt.Add(1)}, ) if confErr != nil { if _, limited := workerPolicyLimit(confErr); limited { @@ -795,11 +883,34 @@ func RunSession( if strings.Contains(errStr, "FATAL_AUTH") { return false, confErr } - if requireConfig { - return false, fmt.Errorf("регистрация нового подключения: %w", confErr) + return false, fmt.Errorf("регистрация нового подключения: %w", confErr) + } + if conf == "" { + return false, fmt.Errorf("сервер ещё не выдал конфигурацию") + } + transportMode = d.resolveTransport(conf) + if autoLease != nil { + autoLease.setStage("protocol") + } + if err := negotiateTransportExperiment(sessCtx, dtlsConn, conf, transportMode); err != nil { + return false, err + } + if autoLease != nil { + autoLease.setStage("confirmation") + if err := confirmConnectionPath(sessCtx, dtlsConn); err != nil { + return false, err } - log.Printf("[ВОРКЕР #%d] Ошибка конфига: %v", sessionID, confErr) - } else if conf != "" { + if !startupTimer.Stop() || ctx.Err() != nil { + return false, context.DeadlineExceeded + } + if !autoLease.accept() { + return false, context.Canceled + } + if selectedMasqueProtocol != "" { + tp.Masque.markPreferred(selectedMasqueProtocol) + } + } + if getConfig && configCh != nil { select { case configCh <- conf: configDelivered = true @@ -811,22 +922,17 @@ func RunSession( if onConfigDelivered != nil { onConfigDelivered() } - } else { - if requireConfig { - return false, fmt.Errorf("сервер ещё не выдал WireGuard-конфиг") - } - log.Printf("[ВОРКЕР #%d] Сервер ещё не выдал WireGuard-конфиг, повторим позже", sessionID) } } - log.Printf("[ВОРКЕР #%d] [READY] Туннель готов к работе ✓", sessionID) + stats.ActiveConnections.Add(1) + globalActiveConnections.Add(1) + defer func() { + stats.ActiveConnections.Add(-1) + globalActiveConnections.Add(-1) + }() - // New servers use this one-shot capability marker to bind every worker of - // a device to one stable WireGuard-side UDP source. An older server treats - // it as an invalid WireGuard datagram, then continues with the next packet. - if _, err := dtlsConn.Write([]byte(multipathRelayHello)); err != nil { - return false, fmt.Errorf("запуск multipath-реле: %w", err) - } + log.Printf("[ВОРКЕР #%d] [READY] Туннель готов к работе ✓", sessionID) // Регистрация в диспетчере slot := &WorkerSlot{ @@ -836,7 +942,32 @@ func RunSession( SleepCh: make(chan struct{}, 1), WakeAckCh: make(chan uint64, 1), } + var uplinkReplacement atomic.Bool + if transportMode == experimentUplink { + slot.uplink = &uplinkQuality{id: sessionID, pacer: d.uplinkPacing} + slot.uplink.sleeping = d.deviceSleeping.Load + slot.uplink.probeWait = d.uplinkPacing.probes.Wait + slot.uplink.replace = func() bool { + if !d.canReplaceUplink(sessionID) { + return false + } + uplinkReplacement.Store(true) + return true + } + if replacingUplink { + slot.uplink.muted.Store(true) + slot.uplink.probation.Store(true) + } + } + var measuredPackets <-chan timedDatagram + if transportMetricsEnabled { + slot.queue = newTransportQueue(workerSendBuf) + measuredPackets = slot.queue.items + go slot.queue.run(sessCtx, "client_uplink", transportMode) + } d.Register(slot) + d.uplinkRecovery.registered(sessionID) + recoveryComplete() defer d.Unregister(slot) var lastServerRxAt atomic.Int64 @@ -858,6 +989,20 @@ func RunSession( return err == nil } + if slot.uplink != nil { + proxyWg.Add(1) + go func() { + defer proxyWg.Done() + slot.uplink.run(sessCtx, func(p []byte) error { + dtlsWriteMu.Lock() + defer dtlsWriteMu.Unlock() + _ = dtlsConn.SetWriteDeadline(time.Now().Add(5 * time.Second)) + _, err := dtlsConn.Write(p) + return err + }, sessCancel) + }() + } + // DTLS Keepalive: prevents TURN allocation timeout and DTLS idle disconnect go func() { defer proxyWg.Done() @@ -945,27 +1090,42 @@ func RunSession( go func() { defer proxyWg.Done() defer sessCancel() + var framedPacket []byte for { + var pkt []byte select { case <-sessCtx.Done(): return - case pkt, ok := <-slot.SendCh: + case queued := <-measuredPackets: + slot.queue.noteDequeue(queued) + pkt = queued.data + case p, ok := <-slot.SendCh: if !ok { return } - userTraffic := isWireGuardUserDataPacket(pkt) - dtlsWriteMu.Lock() - _ = dtlsConn.SetWriteDeadline(time.Now().Add(sessionReadTimeout)) - _, writeErr := dtlsConn.Write(pkt) - dtlsWriteMu.Unlock() - putPktBuf(pkt) - if writeErr != nil { - log.Printf("[ВОРКЕР #%d] Ошибка Writer: %v", sessionID, writeErr) - return - } - if userTraffic { - d.noteUserTrafficSent(time.Now()) - } + pkt = p + } + userTraffic := d.isUserPacket(pkt) + writeStarted := time.Now() + dtlsWriteMu.Lock() + _ = dtlsConn.SetWriteDeadline(time.Now().Add(sessionReadTimeout)) + outgoing := pkt + if slot.uplink != nil && len(pkt) >= 4 && pkt[0] >= 1 && pkt[0] <= 4 && pkt[1] == 0 && pkt[2] == 0 && pkt[3] == 0 { + outgoing = slot.uplink.frame(framedPacket, pkt, pathprobe.Data) + framedPacket = outgoing[:0] + } + _, writeErr := dtlsConn.Write(outgoing) + dtlsWriteMu.Unlock() + if slot.queue != nil { + slot.queue.noteWrite(writeStarted, len(pkt), writeErr) + } + putPktBuf(pkt) + if writeErr != nil { + log.Printf("[ВОРКЕР #%d] Ошибка Writer: %v", sessionID, writeErr) + return + } + if userTraffic { + d.noteUserTrafficSent(time.Now()) } } }() @@ -1005,6 +1165,9 @@ func RunSession( } lastServerRxAt.Store(time.Now().UnixNano()) + if slot.queue != nil { + slot.queue.received.Add(uint64(n)) + } if _, policyErr := parseConfigResponse(string(pkt[:n])); policyErr != nil { if maxWorkers, limited := workerPolicyLimit(policyErr); limited { @@ -1023,11 +1186,15 @@ func RunSession( putPktBuf(pkt) continue } + if slot.uplink != nil && slot.uplink.ack(pkt[:n], time.Now()) { + putPktBuf(pkt) + continue + } if d.handleUpdateMetadataResponse(pkt[:n]) { putPktBuf(pkt) continue } - if isWireGuardUserDataPacket(pkt[:n]) { + if d.isUserPacket(pkt[:n]) { if d.noteUserTrafficResponse() { log.Printf("[HEALTH] пользовательский трафик снова получает ответы") } @@ -1055,5 +1222,8 @@ func RunSession( return configDelivered, &workerPolicyLimitError{maxWorkers: maxWorkers} default: } + if uplinkReplacement.Load() { + return configDelivered, errUplinkPathReplacement + } return configDelivered, nil } diff --git a/go_client/shutdown.go b/go_client/shutdown.go new file mode 100644 index 0000000..6901b26 --- /dev/null +++ b/go_client/shutdown.go @@ -0,0 +1,32 @@ +package main + +import ( + "context" + "os" + "time" +) + +// STOP and EOF cancel ctx just like SIGTERM. Keep handling termination after +// cancellation: some Android Process implementations send SIGTERM even from +// destroyForcibly. A stuck provider read must not prevent the next generation +// from starting. Normal deferred cleanup has time to release TURN allocations; +// the deadline stays within the Android parent's graceful shutdown budget. +func runNativeShutdownGuard(ctx context.Context, cancel context.CancelFunc, signals <-chan os.Signal, exit func(int), grace time.Duration) { + select { + case <-signals: + if ctx.Err() != nil { + exit(1) + return + } + cancel() + case <-ctx.Done(): + } + timer := time.NewTimer(grace) + defer timer.Stop() + select { + case <-signals: + exit(1) + case <-timer.C: + exit(0) + } +} diff --git a/go_client/transport_metrics.go b/go_client/transport_metrics.go new file mode 100644 index 0000000..ab4e686 --- /dev/null +++ b/go_client/transport_metrics.go @@ -0,0 +1,171 @@ +package main + +import ( + "context" + "encoding/binary" + "encoding/json" + "fmt" + "sync" + "sync/atomic" + "time" +) + +// No addresses, payloads, keys or credentials enter these opt-in measurements. +// Histograms and counters are cumulative for one process-local path ID. +var transportMetricsEnabled bool +var transportMetricIDs atomic.Uint64 + +// These optional counters observe admission before the individual path queues. +// A locally dropped datagram cannot appear in the remote delivery receipts. +type uplinkIngressMetrics struct { + accepted, dropped, expired, dispatched atomic.Uint64 + pacingWait transportHistogram +} + +func (m *uplinkIngressMetrics) report(bulk chan timedDatagram) { + if !transportMetricsEnabled || bulk == nil { + return + } + b, _ := json.Marshal(map[string]any{ + "side": "client_uplink_ingress", "at": time.Now().UTC().Format(time.RFC3339Nano), + "depth": len(bulk), "capacity": cap(bulk), "accepted": m.accepted.Load(), + "dropped": m.dropped.Load(), "dispatched": m.dispatched.Load(), + "expired": m.expired.Load(), + "pacing_wait_bins": m.pacingWait.snapshot(), + }) + fmt.Printf("TRANSPORT_METRIC|%s\n", b) +} + +func (w *WorkerSlot) offerData(p []byte) bool { + if w.queue != nil { + return w.queue.offer(p) + } + select { + case w.SendCh <- p: + return true + default: + return false + } +} + +type timedDatagram struct { + data []byte + queued time.Time +} +type transportHistogram struct{ buckets [8]atomic.Uint64 } + +func (h *transportHistogram) observe(d time.Duration) { + limits := [...]time.Duration{time.Millisecond, 3 * time.Millisecond, 10 * time.Millisecond, 30 * time.Millisecond, 100 * time.Millisecond, 300 * time.Millisecond, time.Second} + i := 0 + for i < len(limits) && d > limits[i] { + i++ + } + h.buckets[i].Add(1) +} +func (h *transportHistogram) snapshot() [8]uint64 { + var v [8]uint64 + for i := range v { + v[i] = h.buckets[i].Load() + } + return v +} + +type transportQueue struct { + items chan timedDatagram + id uint64 + enqueued, bytes, full, written, received, writeErrors atomic.Uint64 + wait, write transportHistogram +} + +func newTransportQueue(capacity int) *transportQueue { + return &transportQueue{items: make(chan timedDatagram, capacity), id: transportMetricIDs.Add(1)} +} +func (q *transportQueue) offer(p []byte) bool { + select { + case q.items <- timedDatagram{p, time.Now()}: + q.enqueued.Add(1) + q.bytes.Add(uint64(len(p))) + return true + default: + q.full.Add(1) + return false + } +} +func (q *transportQueue) noteDequeue(p timedDatagram) { q.wait.observe(time.Since(p.queued)) } +func (q *transportQueue) noteWrite(start time.Time, n int, err error) { + q.write.observe(time.Since(start)) + if err != nil { + q.writeErrors.Add(1) + } else { + q.written.Add(uint64(n)) + } +} +func (q *transportQueue) report(side, mode string, final bool) { + if !transportMetricsEnabled { + return + } + v := map[string]any{"side": side, "mode": mode, "id": q.id, "at": time.Now().UTC().Format(time.RFC3339Nano), "final": final, + "depth": len(q.items), "capacity": cap(q.items), "enqueued": q.enqueued.Load(), "bytes": q.bytes.Load(), "full": q.full.Load(), "written_bytes": q.written.Load(), "received_bytes": q.received.Load(), "write_errors": q.writeErrors.Load(), "wait_bins": q.wait.snapshot(), "write_bins": q.write.snapshot()} + b, _ := json.Marshal(v) + fmt.Printf("TRANSPORT_METRIC|%s\n", b) +} +func (q *transportQueue) run(ctx context.Context, side, mode string) { + if !transportMetricsEnabled { + return + } + t := time.NewTicker(5 * time.Second) + defer t.Stop() + for { + select { + case <-ctx.Done(): + q.report(side, mode, true) + return + case <-t.C: + q.report(side, mode, false) + } + } +} + +// Observe only visible WireGuard transport headers. A lower counter proves +// reordering/duplication, not packet loss. Key rotation uses a bounded map. +type transportOrder struct { + mu sync.Mutex + highest map[uint32]uint64 + packets, late, maxBehind uint64 +} + +func (o *transportOrder) observe(p []byte) { + if !transportMetricsEnabled || len(p) < 32 || binary.LittleEndian.Uint32(p[:4]) != 4 { + return + } + key := binary.LittleEndian.Uint32(p[4:8]) + seq := binary.LittleEndian.Uint64(p[8:16]) + o.mu.Lock() + defer o.mu.Unlock() + if o.highest == nil { + o.highest = make(map[uint32]uint64) + } + high, ok := o.highest[key] + o.packets++ + if ok && seq < high { + o.late++ + if high-seq > o.maxBehind { + o.maxBehind = high - seq + } + } + if !ok || seq > high { + if !ok && len(o.highest) >= 8 { + clear(o.highest) + } + o.highest[key] = seq + } +} +func (o *transportOrder) report(side string) { + if !transportMetricsEnabled { + return + } + o.mu.Lock() + defer o.mu.Unlock() + b, _ := json.Marshal(map[string]any{"side": side, "packets": o.packets, "late_or_duplicate": o.late, "max_behind": o.maxBehind, "at": time.Now().UTC().Format(time.RFC3339Nano)}) + fmt.Printf("TRANSPORT_ORDER|%s\n", b) +} diff --git a/go_client/transport_modes.go b/go_client/transport_modes.go new file mode 100644 index 0000000..1bf9832 --- /dev/null +++ b/go_client/transport_modes.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "errors" + "fmt" + "net" + "strings" + "time" +) + +const experimentAuto = "auto" +const experimentStandard = "standard" +const experimentUplink = "uplink" + +func validateTransportExperiment(value string) error { + switch value { + case experimentAuto, experimentStandard, experimentUplink: + return nil + } + return errors.New("unknown transport mode") +} + +func negotiateTransportExperiment(ctx context.Context, connection net.Conn, config, mode string) error { + capability, marker := "", multipathRelayHello + switch mode { + case experimentUplink: + capability, marker = "uplink2", "WDTT_UPLINK2" + } + if capability != "" { + supported := supportsAdaptiveTransport(config) + if !supported { + return errors.New("FATAL_TRANSPORT: сервер изменил возможности транспорта; переподключите туннель") + } + } + if _, err := connection.Write([]byte(marker)); err != nil { + return err + } + if capability == "" { + return nil + } + _ = connection.SetReadDeadline(time.Now().Add(5 * time.Second)) + stop := context.AfterFunc(ctx, func() { _ = connection.SetReadDeadline(time.Now()) }) + defer stop() + defer connection.SetReadDeadline(time.Time{}) + b := make([]byte, readBufSize) + for { + n, err := connection.Read(b) + if err != nil { + // A lost acknowledgement or a changing network is recoverable. + // Never stop every worker because one new path timed out. + return fmt.Errorf("согласование транспорта: %w", err) + } + if string(b[:n]) == "WDTT_TRANSPORT_OK1" { + return nil + } + // DTLS datagrams can arrive out of order. An already active device + // can receive traffic on this path before its ACK arrives. Drop these + // early data packets under the same fixed deadline, then await ACK. + if (mode == experimentUplink && n >= 4 && b[0] >= 1 && b[0] <= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0) || + (n == 1 && b[0] == keepaliveByte) { + continue + } + return fmt.Errorf("FATAL_TRANSPORT: сервер прислал неверное подтверждение транспорта") + } +} + +func (d *Dispatcher) isUserPacket(p []byte) bool { return isWireGuardUserDataPacket(p) } + +// Resolve once per connection generation: all workers must agree on framing. +// Capabilities come from the authenticated GETCONF, never from an unauthenticated probe. +func (d *Dispatcher) resolveTransport(config string) string { + if d.experiment != experimentAuto { + return d.experiment + } + selected := uint32(1) + if supportsAdaptiveTransport(config) { + selected = 2 + } + d.negotiatedTransport.CompareAndSwap(0, selected) + if d.negotiatedTransport.Load() == 2 { + return experimentUplink + } + return experimentStandard +} + +func (d *Dispatcher) usesUplink() bool { + return d.experiment == experimentUplink || (d.experiment == experimentAuto && d.negotiatedTransport.Load() == 2) +} + +func supportsAdaptiveTransport(config string) bool { + for _, line := range strings.Split(config, "\n") { + if values, ok := strings.CutPrefix(strings.TrimSpace(line), "# WDTT_TRANSPORTS="); ok { + for _, value := range strings.Split(values, ",") { + if strings.TrimSpace(value) == "uplink2" { + return true + } + } + } + } + return false +} diff --git a/go_client/transport_uplink.go b/go_client/transport_uplink.go new file mode 100644 index 0000000..afaf0c7 --- /dev/null +++ b/go_client/transport_uplink.go @@ -0,0 +1,329 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "log" + "sync" + "sync/atomic" + "time" + "wdtt.local/pathprobe" +) + +// Uplink selection uses delivery evidence, not RTT rankings. A path with poor +// upload remains registered for download. After cooldown, full-size probes +// verify recovery without sacrificing user packets to a known failing path. +type uplinkQuality struct { + replace func() bool + probeWait func(context.Context) error + sleeping func() bool + failedProbes int + pacer *uplinkPacer + mu sync.Mutex + muted atomic.Bool + probation atomic.Bool + id int + next, expected, received uint64 + baseExpected, baseReceived uint64 + badSince time.Time + checkAt time.Time + probeEnd, probeReceived uint64 + probeDeadline time.Time + pendingSince time.Time + silenceProbes int + silenceProbeAt time.Time + loss uint64 + pacingEpoch uint64 +} + +func (q *uplinkQuality) frame(dst, payload []byte, kind byte) []byte { + q.mu.Lock() + defer q.mu.Unlock() + if kind == pathprobe.Data && len(payload) <= 160 { + return pathprobe.Frame(dst, payload, pathprobe.Bypass, 0) + } + p := pathprobe.Frame(dst, payload, kind, q.next) + if p != nil { + if q.next == q.expected { + q.pendingSince = time.Now() + } + q.next++ + } + return p +} +func (q *uplinkQuality) ack(p []byte, now time.Time) bool { + expected, received, ok := pathprobe.ParseAck(p) + if !ok { + return false + } + q.mu.Lock() + defer q.mu.Unlock() + // Stale/forged counters must not alter scheduling or overflow subtraction. + if expected > q.next || expected < q.expected || received < q.received { + return true + } + deltaExpected, deltaReceived := expected-q.expected, received-q.received + sharedCongestion := false + if q.pacer != nil { + sharedCongestion = q.pacer.notePath(q, deltaExpected, deltaReceived, now) + // A persistently defective path is isolated locally. Its losses must + // not repeatedly throttle every other path while quarantine converges. + defer func() { q.pacer.observe(deltaExpected, deltaReceived, !q.muted.Load() && q.badSince.IsZero()) }() + } + if expected > q.expected { + q.silenceProbes = 0 + q.silenceProbeAt = time.Time{} + if expected == q.next { + q.pendingSince = time.Time{} + } else { + q.pendingSince = now + } + } + q.expected = expected + q.received = received + if q.muted.Load() { + return true + } + if q.pacer != nil { + epoch := q.pacer.congestionEpoch.Load() + if epoch != q.pacingEpoch { + // Loss observed before a common backoff describes the old load. + // Re-test this path at the reduced budget before isolating it. + q.pacingEpoch = epoch + q.badSince = time.Time{} + q.baseExpected = expected + q.baseReceived = received + return true + } + } + if sharedCongestion { + q.badSince = time.Time{} + q.baseExpected = expected + q.baseReceived = received + return true + } + if expected < q.baseExpected || received < q.baseReceived { + return true + } + total := expected - q.baseExpected + got := received - q.baseReceived + if total < 64 || got > total { + return true + } + missing := total - got + q.loss = missing * 1000 / total + if missing*8 > total { + if q.badSince.IsZero() { + q.badSince = now + return true + } + if now.Sub(q.badSince) < 100*time.Millisecond { + return true + } + q.muted.Store(true) + q.reportLocked("loss") + q.checkAt = now.Add(10 * time.Second) + q.badSince = time.Time{} + if transportMetricsEnabled { + log.Printf("[ОТДАЧА] Канал #%d временно исключён из отправки: подтверждено %d/%d пакетов; приём сохранён", q.id, got, total) + } + } else { + q.badSince = time.Time{} + if total >= 128 { + q.baseExpected = expected + q.baseReceived = received + } + } + return true +} +func (q *uplinkQuality) forceOpen() uint64 { + q.mu.Lock() + defer q.mu.Unlock() + q.muted.Store(false) + q.pendingSince = time.Now() + q.silenceProbes = 0 + q.silenceProbeAt = time.Time{} + q.reportLocked("fallback") + q.probeEnd = 0 + q.baseExpected = q.expected + q.baseReceived = q.received + q.badSince = time.Time{} + return q.loss +} +func (q *uplinkQuality) lossScore() uint64 { q.mu.Lock(); defer q.mu.Unlock(); return q.loss } + +// run owns probe scheduling. write must serialize with ordinary DTLS writes; +// no sleeps or remote waits occur under the dispatcher's lock. +func (q *uplinkQuality) run(ctx context.Context, write func([]byte) error, cancel context.CancelFunc) { + tick := time.NewTicker(250 * time.Millisecond) + defer tick.Stop() + payload := make([]byte, 1312) + for { + select { + case <-ctx.Done(): + return + case now := <-tick.C: + q.mu.Lock() + if q.sleeping != nil && q.sleeping() { + // Doze is not evidence of a broken path. Keep recovery silent and + // restart its evidence window after wake instead of spending the + // phone's idle network/battery budget on full-size probes. + if !q.pendingSince.IsZero() { + q.pendingSince = now + } + q.silenceProbes = 0 + q.silenceProbeAt = time.Time{} + q.probeEnd = 0 + q.checkAt = now.Add(time.Second) + q.badSince = time.Time{} + q.mu.Unlock() + continue + } + if !q.muted.Load() { + if q.next-q.expected >= 1 && !q.pendingSince.IsZero() && now.Sub(q.pendingSince) >= 2*time.Second { + // A single missing tail packet during an otherwise idle phase + // is not a dead channel. Request delivery evidence twice before + // quarantine, without sacrificing ordinary user traffic. + if now.Before(q.silenceProbeAt) { + q.mu.Unlock() + continue + } + if q.silenceProbes < 2 { + q.silenceProbes++ + q.silenceProbeAt = now.Add(2 * time.Second) + p := pathprobe.Frame(nil, payload, pathprobe.Probe, q.next) + q.next++ + q.mu.Unlock() + if q.probeWait != nil && q.probeWait(ctx) != nil { + return + } + if write(p) != nil { + cancel() + return + } + continue + } + q.muted.Store(true) + q.loss = 1000 + q.checkAt = now.Add(10 * time.Second) + q.reportLocked("no_progress") + if transportMetricsEnabled { + log.Printf("[ОТДАЧА] Канал #%d временно исключён из отправки: нет подтверждения доставки; приём сохранён", q.id) + } + } + q.mu.Unlock() + continue + } + if q.probeEnd != 0 { + if now.Before(q.probeDeadline) { + q.mu.Unlock() + continue + } + good := q.expected >= q.probeEnd && q.received >= q.probeReceived && q.received-q.probeReceived >= 32 + q.probeEnd = 0 + q.checkAt = now.Add(10 * time.Second) + if good { + q.failedProbes = 0 + q.probation.Store(false) + q.muted.Store(false) + q.pendingSince = time.Time{} + q.reportLocked("recovered") + q.baseExpected = q.expected + q.baseReceived = q.received + q.badSince = time.Time{} + if transportMetricsEnabled { + log.Printf("[ОТДАЧА] Канал #%d снова участвует в отправке после проверки доставки", q.id) + } + } else { + q.failedProbes++ + } + shouldReplace := !good && q.failedProbes >= 2 && q.replace != nil + q.mu.Unlock() + if shouldReplace && q.replace() { + q.mu.Lock() + q.reportLocked("replace") + q.mu.Unlock() + if transportMetricsEnabled { + log.Printf("[ОТДАЧА] Канал #%d не восстановил доставку после проверок; заменяем только этот канал", q.id) + } + cancel() + return + } + continue + } + if now.Before(q.checkAt) { + q.mu.Unlock() + continue + } + q.probeReceived = q.received + // Reserve the entire probe sequence under one lock. Ordinary traffic has + // drained during cooldown; an emergency fallback cancels this probation. + frames := make([][]byte, 32) + for i := range frames { + frames[i] = pathprobe.Frame(nil, payload, pathprobe.Probe, q.next) + q.next++ + } + q.probeEnd = q.next + q.probeDeadline = now.Add(time.Second) + q.mu.Unlock() + for _, p := range frames { + if ctx.Err() != nil { + return + } + if q.probeWait != nil && q.probeWait(ctx) != nil { + return + } + if write(p) != nil { + cancel() + return + } + } + q.mu.Lock() + q.probeDeadline = time.Now().Add(time.Second) + q.mu.Unlock() + } + } +} + +// Called under q.mu; diagnostic output contains only local IDs and counters. +func (q *uplinkQuality) reportLocked(event string) { + if !transportMetricsEnabled { + return + } + b, _ := json.Marshal(map[string]any{"side": "uplink_delivery", "mode": "uplink", "id": q.id, "at": time.Now().UTC().Format(time.RFC3339Nano), "event": event, "sent": q.next, "expected": q.expected, "received": q.received, "muted": q.muted.Load()}) + fmt.Printf("TRANSPORT_METRIC|%s\n", b) +} + +func ensureUplinkServiceFloor(ws []*WorkerSlot, wakeGeneration uint64, deviceSleeping bool) { + // Keep a last-resort path only when none is usable. Reopening a fixed + // fraction of the requested workers reintroduced proven losses whenever + // a small hash set supplied many defective paths. Healthy paths determine + // usable capacity; the slider must not force known failures back into it. + healthy := 0 + for _, w := range ws { + if !workerEligibleForWakeGeneration(w, wakeGeneration, deviceSleeping) || (w.uplink != nil && w.uplink.probation.Load()) { + continue + } + if w.uplink == nil || !w.uplink.muted.Load() { + healthy++ + } + } + floor := 1 + for healthy < floor { + var best *WorkerSlot + for _, w := range ws { + if !workerEligibleForWakeGeneration(w, wakeGeneration, deviceSleeping) || w.uplink == nil || w.uplink.probation.Load() || !w.uplink.muted.Load() { + continue + } + if best == nil || w.uplink.lossScore() < best.uplink.lossScore() { + best = w + } + } + if best == nil { + break + } + best.uplink.forceOpen() + healthy++ + } +} diff --git a/go_client/transport_uplink_pacer.go b/go_client/transport_uplink_pacer.go new file mode 100644 index 0000000..56bd023 --- /dev/null +++ b/go_client/transport_uplink_pacer.go @@ -0,0 +1,207 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "golang.org/x/time/rate" + "sync" + "sync/atomic" + "time" +) + +// Limit aggregate bursts before they enter independent TURN queues. TCP ACKs +// and handshakes bypass pacing; bulk delivery reports adjust the shared budget. +// This is confined to the opt-in uplink transport, never a subscription limit. +type uplinkPacer struct { + limiter *rate.Limiter + probes *rate.Limiter + mu sync.Mutex + expected, received uint64 + mbps float64 + offeredBytes atomic.Int64 + lastAdjust time.Time + idleTicks int + previousUsageMbps float64 + paths map[*uplinkQuality]uplinkPathFeedback + sharedSince time.Time + sharedUntil time.Time + lastSharedAdjust time.Time + congestionEpoch atomic.Uint64 +} + +type uplinkPathFeedback struct { + start, latest time.Time + expected, received uint64 +} + +func (p *uplinkPacer) registerPath(q *uplinkQuality) { + p.mu.Lock() + defer p.mu.Unlock() + if p.paths == nil { + p.paths = make(map[*uplinkQuality]uplinkPathFeedback) + } + p.paths[q] = uplinkPathFeedback{} +} + +func (p *uplinkPacer) unregisterPath(q *uplinkQuality) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.paths, q) +} + +// Several paths share one device uplink. Widespread loss first needs a common +// budget reduction, rather than quarantining every path and losing feedback. +// A minority still follows normal isolation; persistent failure can defer it +// for at most two seconds. State is bounded by registered live paths. +func (p *uplinkPacer) notePath(q *uplinkQuality, expected, received uint64, now time.Time) bool { + p.mu.Lock() + defer p.mu.Unlock() + sample, exists := p.paths[q] + if !exists || q.muted.Load() { + return false + } + if sample.start.IsZero() || now.Sub(sample.start) >= time.Second { + sample = uplinkPathFeedback{start: now} + } + sample.latest = now + sample.expected += expected + sample.received += received + p.paths[q] = sample + active, participating, bad := 0, 0, 0 + var totalExpected, totalReceived uint64 + for path, feedback := range p.paths { + if path.muted.Load() { + continue + } + active++ + if feedback.expected < 32 || feedback.latest.IsZero() || now.Sub(feedback.latest) >= time.Second { + continue + } + participating++ + totalExpected += feedback.expected + totalReceived += feedback.received + if feedback.received < feedback.expected && feedback.expected-feedback.received > feedback.expected/50 { + bad++ + } + } + if participating >= max(2, (active+1)/2) && bad >= 2 && bad*2 > participating && totalExpected >= 128 { + if p.sharedSince.IsZero() { + p.sharedSince = now + } + if now.Sub(p.sharedSince) < 2*time.Second { + p.sharedUntil = now.Add(500 * time.Millisecond) + deadline := p.sharedSince.Add(2 * time.Second) + if p.sharedUntil.After(deadline) { + p.sharedUntil = deadline + } + if now.Sub(p.sharedSince) >= 100*time.Millisecond && (p.lastSharedAdjust.IsZero() || now.Sub(p.lastSharedAdjust) >= 250*time.Millisecond) { + previousBudget := p.mbps + p.mbps = max(8, p.mbps*.8) + if p.mbps < previousBudget { + p.congestionEpoch.Add(1) + } + p.limiter.SetLimitAt(now, rate.Limit(p.mbps*1e6/8)) + p.lastSharedAdjust = now + if transportMetricsEnabled { + b, _ := json.Marshal(map[string]any{"side": "uplink_shared_congestion", "at": now.UTC().Format(time.RFC3339Nano), "mbps": p.mbps, "active": active, "participating": participating, "bad": bad, "expected": totalExpected, "received": totalReceived}) + fmt.Printf("TRANSPORT_METRIC|%s\n", b) + } + } + } + } else if !now.Before(p.sharedUntil) { + // A recovered majority ends the episode. Continuing widespread failure + // never renews the bounded grace period. + p.sharedSince = time.Time{} + } + return now.Before(p.sharedUntil) +} + +func newUplinkPacer() *uplinkPacer { + return &uplinkPacer{limiter: rate.NewLimiter(rate.Limit(64e6/8), 8*1500), probes: rate.NewLimiter(256, 4), mbps: 64} +} +func (p *uplinkPacer) wait(ctx context.Context, n int) error { + if n <= 160 { + return nil + } + // Include framing, DTLS, wrapping, TURN and the outer IP/UDP header. + if err := p.limiter.WaitN(ctx, n+128); err != nil { + return err + } + p.offeredBytes.Add(int64(n + 128)) + return nil +} +func (p *uplinkPacer) observe(expected, received uint64, eligible bool) { + if !eligible { + return + } + p.mu.Lock() + p.expected += expected + p.received += received + p.mu.Unlock() +} +func (p *uplinkPacer) adjust(now time.Time) { + p.mu.Lock() + defer p.mu.Unlock() + seconds := 1.0 + if !p.lastAdjust.IsZero() { + seconds = max(.1, now.Sub(p.lastAdjust).Seconds()) + } + p.lastAdjust = now + offered := p.offeredBytes.Swap(0) + expected, received := p.expected, p.received + p.expected = 0 + p.received = 0 + if offered == 0 { + p.idleTicks++ + } else { + p.idleTicks = 0 + } + if p.idleTicks >= 5 { + p.mbps = min(64, p.mbps) + p.limiter.SetLimitAt(now, rate.Limit(p.mbps*1e6/8)) + } + usageMbps := float64(offered) * 8 / 1e6 / seconds + recentUsageMbps := max(usageMbps, p.previousUsageMbps) + p.previousUsageMbps = usageMbps + if expected < 128 { + return + } + missing := uint64(0) + if expected > received { + missing = expected - received + } + loss := float64(missing) / float64(expected) + sharedAdjustment := !p.lastSharedAdjust.IsZero() && now.Sub(p.lastSharedAdjust) < time.Second + if sharedAdjustment { + // The fast common response already reduced this budget. Do not apply + // another reduction using receipts from before that adjustment. + } else if loss > .02 { + // Back off relative to traffic actually carried, not a stale ceiling + // learned when application demand was much lower than that ceiling. + previousBudget := p.mbps + p.mbps = max(8, min(p.mbps*.8, recentUsageMbps*.85)) + if p.mbps < previousBudget { + p.congestionEpoch.Add(1) + } + } else if loss < .005 && usageMbps >= p.mbps*.7 { + p.mbps = min(512, p.mbps*1.15) + } + p.limiter.SetLimitAt(now, rate.Limit(p.mbps*1e6/8)) + if transportMetricsEnabled { + b, _ := json.Marshal(map[string]any{"side": "uplink_pacing", "mode": "uplink", "id": 0, "at": now.UTC().Format(time.RFC3339Nano), "mbps": p.mbps, "offered_mbps": usageMbps, "expected": expected, "received": received}) + fmt.Printf("TRANSPORT_METRIC|%s\n", b) + } +} +func (p *uplinkPacer) run(ctx context.Context) { + t := time.NewTicker(time.Second) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case now := <-t.C: + p.adjust(now) + } + } +} diff --git a/go_client/transport_uplink_recovery.go b/go_client/transport_uplink_recovery.go new file mode 100644 index 0000000..aef98ac --- /dev/null +++ b/go_client/transport_uplink_recovery.go @@ -0,0 +1,91 @@ +package main + +import ( + "errors" + "sync" + "time" +) + +var errUplinkPathReplacement = errors.New("uplink delivery path replacement") + +// One dispatcher owns the budget, so separate credential groups cannot each +// start their own replacement storm. Credentials are reused by WorkerGroup. +type uplinkRecovery struct { + mu sync.Mutex + active map[int]bool + pending map[int]bool + next map[int]time.Time + attempts map[int]int + nextGlobal time.Time + capacityUntil time.Time +} + +func (r *uplinkRecovery) acquire(id int, now time.Time) bool { + r.mu.Lock() + defer r.mu.Unlock() + if len(r.active) >= 2 || r.active[id] || now.Before(r.nextGlobal) || now.Before(r.next[id]) || now.Before(r.capacityUntil) { + return false + } + if r.active == nil { + r.active = make(map[int]bool) + r.pending = make(map[int]bool) + r.next = make(map[int]time.Time) + r.attempts = make(map[int]int) + } + r.active[id] = true + r.pending[id] = true + r.attempts[id] = min(4, r.attempts[id]+1) + r.next[id] = now.Add(30 * time.Second * time.Duration(1<<(r.attempts[id]-1))) + r.nextGlobal = now.Add(5 * time.Second) + return true +} + +func (r *uplinkRecovery) capacityLimited(now time.Time) { + r.mu.Lock() + r.capacityUntil = now.Add(30 * time.Second) + r.mu.Unlock() +} + +// Capture the previous attempt's permit before entering RunSession. A permit +// acquired later by this session must survive its teardown until the following +// handshake finishes or fails. The returned release is idempotent. +func (r *uplinkRecovery) completion(id int) (bool, func()) { + r.mu.Lock() + held := r.active[id] + needsProbe := r.pending[id] + r.mu.Unlock() + var once sync.Once + return needsProbe, func() { + if held { + once.Do(func() { r.mu.Lock(); delete(r.active, id); r.mu.Unlock() }) + } + } +} + +// A failed handshake releases the concurrency permit, but must not turn the +// following retry into an unverified ordinary path. Clear probation only once +// a registered successor owns its own full-size delivery check. +func (r *uplinkRecovery) registered(id int) { + r.mu.Lock() + delete(r.pending, id) + r.mu.Unlock() +} + +func (d *Dispatcher) canReplaceUplink(id int) bool { + if d.ctx.Err() != nil || d.deviceSleeping.Load() { + return false + } + ws := d.workers.Load() + if ws == nil { + return false + } + healthy := 0 + for _, w := range *ws { + if w.ID != id && workerEligibleForWakeGeneration(w, d.wakeGeneration.Load(), false) && + (w.uplink == nil || !w.uplink.muted.Load()) { + healthy++ + } + } + // Never tear down the remaining usable service to improve a sick path. + return healthy >= 1 && d.uplinkRecovery.acquire(id, time.Now()) +} diff --git a/go_client/turn_allocation.go b/go_client/turn_allocation.go new file mode 100644 index 0000000..598a71e --- /dev/null +++ b/go_client/turn_allocation.go @@ -0,0 +1,117 @@ +package main + +import ( + "encoding/binary" + "net" + "sync" + "sync/atomic" + "time" +) + +// Pion owns allocation transactions, but Client.Close does not close the +// caller-supplied network socket. Keep the two lifetimes together, including +// TCP/TLS and MASQUE streams, so retrying a worker cannot leak a reader/socket. +type ownedTURNAllocation struct { + net.PacketConn + transport net.PacketConn + closeClient func() + deletion *turnDeletionTransport + once sync.Once + err error +} + +func (c *ownedTURNAllocation) Close() error { + c.once.Do(func() { + // Send allocation deletion while its transport is still available. + if c.deletion != nil { + c.deletion.closing.Store(true) + } + c.err = c.PacketConn.Close() + if c.deletion != nil && c.err == nil { + c.deletion.wait(750 * time.Millisecond) + } + c.closeClient() + if err := c.transport.Close(); c.err == nil { + c.err = err + } + }) + return c.err +} + +// Keep the socket and Pion retransmission timer alive for the zero-lifetime +// Refresh response. Closing them immediately after sending one UDP datagram +// can leave the remote allocation occupied until its ordinary expiry. +// Only teardown inspects STUN; normal traffic takes a single atomic branch. +type turnDeletionTransport struct { + net.PacketConn + closing atomic.Bool + mu sync.Mutex + transaction [12]byte + pending bool + ack chan struct{} + once sync.Once +} + +func deletionTransaction(p []byte, kind uint16) ([12]byte, bool) { + var id [12]byte + if len(p) < 20 || binary.BigEndian.Uint16(p[:2]) != kind || binary.BigEndian.Uint32(p[4:8]) != 0x2112a442 { + return id, false + } + n := 20 + int(binary.BigEndian.Uint16(p[2:4])) + if n != len(p) { + return id, false + } + for at := 20; at+4 <= n; { + attr, size := binary.BigEndian.Uint16(p[at:at+2]), int(binary.BigEndian.Uint16(p[at+2:at+4])) + at += 4 + if at+size > n { + return id, false + } + if attr == 0x000d && size == 4 && binary.BigEndian.Uint32(p[at:at+4]) == 0 { + copy(id[:], p[8:20]) + return id, true + } + at += (size + 3) &^ 3 + } + return id, false +} + +func (c *turnDeletionTransport) WriteTo(p []byte, addr net.Addr) (int, error) { + if c.closing.Load() { + if id, ok := deletionTransaction(p, 0x0004); ok { + c.mu.Lock() + c.transaction = id + c.pending = true + c.mu.Unlock() + } + } + return c.PacketConn.WriteTo(p, addr) +} +func (c *turnDeletionTransport) ReadFrom(p []byte) (int, net.Addr, error) { + n, addr, err := c.PacketConn.ReadFrom(p) + if c.closing.Load() && n > 0 { + if id, ok := deletionTransaction(p[:n], 0x0104); ok { + c.mu.Lock() + match := c.pending && c.transaction == id + c.mu.Unlock() + if match { + c.once.Do(func() { close(c.ack) }) + } + } + } + return n, addr, err +} +func (c *turnDeletionTransport) wait(timeout time.Duration) { + c.mu.Lock() + pending := c.pending + c.mu.Unlock() + if !pending { + return + } + t := time.NewTimer(timeout) + defer t.Stop() + select { + case <-c.ack: + case <-t.C: + } +} diff --git a/go_client/turn_endpoint.go b/go_client/turn_endpoint.go index 928966b..6b1d3c0 100644 --- a/go_client/turn_endpoint.go +++ b/go_client/turn_endpoint.go @@ -257,7 +257,9 @@ func sessionTURNCandidatesForAttempt( } } - if preferStream { + // The shared policy sets the order and needs every fallback candidate, + // including TCP at an address advertised by the provider as UDP-only. + if preferStream || (tp != nil && tp.Auto != nil) { addStreamCandidates(true) addLegacyUDP() } else { diff --git a/pathprobe/go.mod b/pathprobe/go.mod new file mode 100644 index 0000000..d8994a8 --- /dev/null +++ b/pathprobe/go.mod @@ -0,0 +1,3 @@ +module wdtt.local/pathprobe + +go 1.25.0 diff --git a/pathprobe/protocol.go b/pathprobe/protocol.go new file mode 100644 index 0000000..810cb27 --- /dev/null +++ b/pathprobe/protocol.go @@ -0,0 +1,81 @@ +// Package pathprobe describes an opt-in, authenticated per-path delivery report. +// It must only be used inside an admitted DTLS session. It neither authenticates +// traffic nor replaces WireGuard replay protection. +package pathprobe + +import "encoding/binary" + +const ( + Header = 16 + MaxPayload = 1440 + Data byte = 1 + Probe byte = 2 + Bypass byte = 4 +) + +func Frame(dst, payload []byte, kind byte, seq uint64) []byte { + if (kind != Data && kind != Probe && kind != Bypass) || len(payload) > MaxPayload || seq == ^uint64(0) { + return nil + } + n := Header + len(payload) + if cap(dst) < n { + dst = make([]byte, n) + } else { + dst = dst[:n] + clear(dst[:Header]) + } + copy(dst, "WDU2") + dst[4] = kind + binary.BigEndian.PutUint64(dst[8:16], seq) + copy(dst[Header:], payload) + return dst +} +func Parse(p []byte) (kind byte, seq uint64, payload []byte, ok bool) { + if len(p) < Header || len(p) > Header+MaxPayload || string(p[:4]) != "WDU2" || (p[4] != Data && p[4] != Probe && p[4] != Bypass) || p[5] != 0 || p[6] != 0 || p[7] != 0 { + return + } + seq = binary.BigEndian.Uint64(p[8:16]) + if seq == ^uint64(0) { + return + } + return p[4], seq, p[Header:], true +} +func Ack(expected, received uint64) []byte { + p := make([]byte, 24) + copy(p, "WDA2") + binary.BigEndian.PutUint64(p[8:16], expected) + binary.BigEndian.PutUint64(p[16:24], received) + return p +} +func ParseAck(p []byte) (expected, received uint64, ok bool) { + if len(p) != 24 || string(p[:4]) != "WDA2" || binary.BigEndian.Uint32(p[4:8]) != 0 { + return + } + expected = binary.BigEndian.Uint64(p[8:16]) + received = binary.BigEndian.Uint64(p[16:24]) + return expected, received, received <= expected +} + +// Receipt is a bounded deduplicator, owned by one caller or protected by a lock. +// Reports are cumulative so losing a report cannot masquerade as data loss. +// Gaps count only within a path, never between unrelated paths. +type Receipt struct { + Expected, Received uint64 + seen [256]uint64 +} + +func (r *Receipt) Observe(seq uint64) bool { + if seq == ^uint64(0) || (seq < r.Expected && r.Expected-seq > uint64(len(r.seen))) { + return false + } + slot := seq % uint64(len(r.seen)) + if r.seen[slot] == seq+1 { + return false + } + r.seen[slot] = seq + 1 + r.Received++ + if seq >= r.Expected { + r.Expected = seq + 1 + } + return true +} diff --git a/pathprobe/worker.go b/pathprobe/worker.go new file mode 100644 index 0000000..6922ea9 --- /dev/null +++ b/pathprobe/worker.go @@ -0,0 +1,28 @@ +package pathprobe + +import ( + "fmt" + "strconv" + "strings" +) + +// Worker identifies a replaceable path within an authenticated transport session. +// It is not an account or credential identifier. The bound keeps server state +// finite even when the client supplies arbitrary path numbers. +type Worker struct { + Slot uint32 + Attempt uint64 +} + +func (w Worker) Valid() bool { return w.Slot > 0 && w.Slot <= 4096 && w.Attempt > 0 } +func (w Worker) String() string { return fmt.Sprintf("W1:%d:%d", w.Slot, w.Attempt) } +func ParseWorker(s string) (Worker, bool) { + p := strings.Split(s, ":") + if len(p) != 3 || p[0] != "W1" { + return Worker{}, false + } + slot, e1 := strconv.ParseUint(p[1], 10, 32) + attempt, e2 := strconv.ParseUint(p[2], 10, 64) + w := Worker{Slot: uint32(slot), Attempt: attempt} + return w, e1 == nil && e2 == nil && w.Valid() +} diff --git a/server-installer/README.md b/server-installer/README.md index 75b4b13..3c791ef 100644 --- a/server-installer/README.md +++ b/server-installer/README.md @@ -4,9 +4,11 @@ из Linux-терминала, без передачи SSH-логина, root-пароля или приватного ключа Android-приложению. -Текущая версия автономного установщика — `0.20.0`. Она совместима только с -`wdtt-server` версии `17` и контрактом Android-деплоя `1`. Номера версий у -скрипта и сервера разные по замыслу: важна именно эта совместимая комбинация. +Комплект для выпуска **WDTT Plus 19** содержит `wdtt-server` версии `19` и +автономный установщик `0.20.2`, совместимый с контрактом Android-деплоя `1`. +Версии приложения и сервера совпадают; версия скрипта учитывается отдельно, +поскольку он может обновляться без изменения сервера. Используйте файлы из +одного выпуска. ```bash bash server-installer/install.sh --version @@ -23,7 +25,7 @@ VK-хеш. Для установки нужен совместимый комплект: - `install.sh`; -- исполняемый бинарник `wdtt-server` версии `17` для Linux `amd64` +- исполняемый бинарник `wdtt-server` версии `19` для Linux `amd64` (`x86_64`); - `SHA256SUMS` для проверки скрипта и бинарника. @@ -41,8 +43,8 @@ VK-хеш. На странице выпуска WDTT Plus в разделе **Assets**, рядом с APK, публикуются: ```text -WDTT-Plus-server-v17-installer-0.20.0-linux-amd64.tar.gz -WDTT-Plus-server-v17-installer-0.20.0-linux-amd64.tar.gz.sha256 +WDTT-Plus-server-v19-installer-0.20.2-linux-amd64.tar.gz +WDTT-Plus-server-v19-installer-0.20.2-linux-amd64.tar.gz.sha256 ``` При канонической предрелизной подготовке эти файлы создаются вместе с четырьмя @@ -57,9 +59,9 @@ app/build/outputs/release-ready/ архив: ```bash -sha256sum -c WDTT-Plus-server-v17-installer-0.20.0-linux-amd64.tar.gz.sha256 -tar -xzf WDTT-Plus-server-v17-installer-0.20.0-linux-amd64.tar.gz -cd WDTT-Plus-server-v17-installer-0.20.0-linux-amd64 +sha256sum -c WDTT-Plus-server-v19-installer-0.20.2-linux-amd64.tar.gz.sha256 +tar -xzf WDTT-Plus-server-v19-installer-0.20.2-linux-amd64.tar.gz +cd WDTT-Plus-server-v19-installer-0.20.2-linux-amd64 ``` После распаковки внутри находятся три согласованных файла: @@ -70,7 +72,7 @@ wdtt-server SHA256SUMS ``` -Это статический Linux `amd64`-файл `wdtt-server` версии `17`; внешние +Это статический Linux `amd64`-файл `wdtt-server` версии `19`; внешние динамические библиотеки ему не нужны. Проверьте внутренние файлы и их версии: ```bash @@ -80,7 +82,7 @@ bash install.sh --version ``` Проверка должна сообщить `install.sh: OK`, `wdtt-server: OK`, версию -установщика `0.20.0` и версию сервера `17`. +установщика `0.20.2` и версию сервера `19`. Готовые бинарник и контрольные суммы публикуются как файлы конкретного выпуска, но не хранятся в истории Git. Так пользователь получает проверенный @@ -386,7 +388,7 @@ VPS. Пока сервер принадлежит ручному установ ### Резервные копии после ручной установки -Совместимый `wdtt-server` v17 поддерживает тот же менеджер резервных копий и +Совместимый `wdtt-server` v19 поддерживает тот же менеджер резервных копий и после установки через этот скрипт. Управление находится в Android-приложении: **«Деплой» → «Резервные копии и перенос»**. Для административных действий нужны SSH-доступ к VPS и главный пароль WDTT; обычное VPN-подключение по-прежнему @@ -679,8 +681,12 @@ kernel или userspace. - маркеры Android-деплоя, сохранённых Android-данных и ручной установки. Проверка [compatibility_test.sh](tests/compatibility_test.sh) сверяет контракт, -`install.sh`, Android `deploy.sh` и `server.go`. Если один путь изменён, а -другой не обновлён, Gradle-сборка должна остановиться до создания APK. +`install.sh`, Android `deploy.sh` и `server.go`. Отдельная проверка +[version_sync_test.sh](tests/version_sync_test.sh) сверяет номер выпуска у +Android-приложения, `wdtt-server` и верхней записи `CHANGELOG.md`, а также +целевую версию сервера в обоих установщиках, контракте и инструкции. Версия +самого скрипта остаётся отдельной. Если один путь изменён, а другой не обновлён, +Gradle-сборка останавливается до создания серверного бинарника и APK. При изменении серверного протокола или цепочки Android-деплоя обновляйте одновременно: @@ -698,6 +704,7 @@ kernel или userspace. ```bash bash -n server-installer/install.sh server-installer/tests/install_test.sh bash -n server-installer/release_bundle.sh +bash server-installer/tests/version_sync_test.sh bash server-installer/tests/compatibility_test.sh bash server-installer/tests/install_test.sh go test ./... @@ -705,6 +712,13 @@ go test ./... git diff --check -- server-installer/install.sh server-installer/README.md ``` +Если серверный бинарник уже собран, локальный standalone-комплект без сборки +APK синхронизируется канонической командой: + +```bash +server-installer/release_bundle.sh sync-local +``` + ### Предрелизная подготовка Каноническая команда подготовки файлов для GitHub: @@ -846,6 +860,10 @@ SSH нужен только для ручной установки, админи ## Версии ручного установщика +- `0.20.2` — добавлена совместимость с `wdtt-server` v19 и Android-деплоем + выпуска 19; обновление сохраняет данные, ключи, настройки и резервные копии. +- `0.20.1` — добавлена совместимость с `wdtt-server` v18; обновление сохраняет + существующие данные, ключи, настройки и резервные копии. - `0.20.0` — ручной установщик распознаёт данные, оставленные командой Android «Удалить сервер, сохранить данные», и может явно принять их через `adopt-android`. Перед восстановлением создаётся полная проверенная копия; diff --git a/server-installer/compatibility-contract.env b/server-installer/compatibility-contract.env index 5c60f1d..a712ef6 100644 --- a/server-installer/compatibility-contract.env +++ b/server-installer/compatibility-contract.env @@ -1,7 +1,7 @@ # Canonical compatibility contract for Android deploy and standalone installer. # Changing any value requires updating both paths; the build guard enforces it. WDTT_DEPLOY_CONTRACT_VERSION="1" -WDTT_SERVER_VERSION="17" +WDTT_SERVER_VERSION="19" WDTT_SERVER_BINARY_PATH="/usr/local/bin/wdtt-server" WDTT_SYSTEMD_UNIT_PATH="/etc/systemd/system/wdtt.service" WDTT_CONFIG_DIRECTORY="/etc/wdtt" diff --git a/server-installer/install.sh b/server-installer/install.sh index 7e84820..daae136 100755 --- a/server-installer/install.sh +++ b/server-installer/install.sh @@ -23,8 +23,8 @@ ensure_utf8_locale() { ensure_utf8_locale -readonly INSTALLER_VERSION="0.20.0" -readonly SUPPORTED_SERVER_VERSION="17" +readonly INSTALLER_VERSION="0.20.2" +readonly SUPPORTED_SERVER_VERSION="19" readonly DEPLOY_COMPATIBILITY_VERSION="1" readonly MANAGED_MARKER="Managed by WDTT Plus standalone server installer" readonly ANDROID_DEPLOY_MARKER="Managed by WDTT Plus Android deploy" diff --git a/server-installer/release_bundle.sh b/server-installer/release_bundle.sh index 42c9bf5..7c32a4a 100755 --- a/server-installer/release_bundle.sh +++ b/server-installer/release_bundle.sh @@ -37,6 +37,9 @@ usage() { Подготовка релизного комплекта WDTT Plus Использование: + release_bundle.sh sync-local + Синхронизировать локальный standalone-бинарник и + SHA256SUMS с текущим серверным asset без сборки APK. release_bundle.sh prepare Пересобрать локальный standalone-комплект, создать единый каталог готовых файлов релиза и сразу проверить его вместе со всеми APK. @@ -97,6 +100,8 @@ validate_versions() { APP_VERSION="$(read_single_assignment "$REPOSITORY_ROOT/app/build.gradle.kts" appVersionName)" [[ "$APP_VERSION" =~ ^[0-9]+$ ]] || die "версия Android-приложения должна быть целым числом" + [[ "$APP_VERSION" == "$WDTT_SERVER_VERSION" ]] || + die "версии приложения ($APP_VERSION) и сервера ($WDTT_SERVER_VERSION) расходятся" BUNDLE_NAME="WDTT-Plus-server-v${WDTT_SERVER_VERSION}-installer-${INSTALLER_VERSION}-linux-amd64" ARCHIVE_NAME="$BUNDLE_NAME.tar.gz" ARCHIVE_SUM_NAME="$ARCHIVE_NAME.sha256" @@ -358,7 +363,7 @@ main() { local mode="${1:-}" [[ $# -eq 1 ]] || { usage; exit 2; } case "$mode" in - prepare|verify|invalidate) ;; + sync-local|prepare|verify|invalidate) ;; -h|--help|help) usage; exit 0 ;; *) usage; exit 2 ;; esac @@ -366,7 +371,7 @@ main() { validate_versions install -d -m 0755 "$OUTPUTS_ROOT" exec 9>"$LOCK_PATH" - if [[ "$mode" == "prepare" || "$mode" == "invalidate" ]]; then + if [[ "$mode" == "sync-local" || "$mode" == "prepare" || "$mode" == "invalidate" ]]; then flock -n 9 || die "другая подготовка релиза уже выполняется" else flock -s -n 9 || die "комплект сейчас изменяется другой подготовкой релиза" @@ -374,6 +379,14 @@ main() { TEMP_ROOT="$(mktemp -d /tmp/wdtt-server-release.XXXXXX)" chmod 0700 "$TEMP_ROOT" case "$mode" in + sync-local) + require_regular_file "$SERVER_ASSET" + validate_linux_server "$SERVER_ASSET" + write_local_standalone_files + verify_source_and_local_files + printf 'Локальный standalone-комплект синхронизирован с wdtt-server v%s.\n' \ + "$WDTT_SERVER_VERSION" + ;; prepare) prepare_release ;; diff --git a/server-installer/tests/compatibility_test.sh b/server-installer/tests/compatibility_test.sh index 92fd9e1..f923fed 100644 --- a/server-installer/tests/compatibility_test.sh +++ b/server-installer/tests/compatibility_test.sh @@ -103,6 +103,8 @@ grep -Fq '[ "$server_version" = "$WDTT_SERVER_VERSION" ]' "$DEPLOY" || grep -Eq "wdttServerVersion[[:space:]]*=[[:space:]]*\"$WDTT_SERVER_VERSION\"" "$SERVER" || fail "Go-сервер не соответствует версии из контракта" +bash "$TEST_DIR/version_sync_test.sh" >/dev/null || + fail "версии приложения, сервера и установщиков не синхронизированы" # Готовый standalone-комплект должен соответствовать текущему корневому Go-коду, # а не только сообщать тот же номер версии. diff --git a/server-installer/tests/install_test.sh b/server-installer/tests/install_test.sh index a01c3af..792306c 100755 --- a/server-installer/tests/install_test.sh +++ b/server-installer/tests/install_test.sh @@ -38,7 +38,7 @@ new_sandbox() { make_fake_binary() { local target="$1" local build_id="$2" - local reported_version="${3:-17}" + local reported_version="${3:-19}" cat >"$target" <"$output" - [[ "$("$INSTALLER" --version)" == "0.20.0" ]] || + [[ "$("$INSTALLER" --version)" == "0.20.2" ]] || fail "команда --version вернула неожиданный результат" ! grep -Fq "install.sh start" "$output" || fail "справка показывает alias start как отдельный основной сценарий" @@ -383,7 +383,7 @@ test_wizard_on_android_deploy_is_guidance_not_failure() { tr -d '\r' <"$output" >"$clean" grep -Fq "На сервере уже обнаружен совместимый Android-деплой." "$clean" || fail "мастер не объяснил найденный Android-деплой" - grep -Fq "✓ Совместимость подтверждена: контракт 1, wdtt-server 17." "$clean" || + grep -Fq "✓ Совместимость подтверждена: контракт 1, wdtt-server 19." "$clean" || fail "мастер не показал краткую совместимость" grep -Fq "Сейчас изменений на сервере не выполнено." "$clean" || fail "мастер не подтвердил отсутствие изменений" @@ -1829,20 +1829,20 @@ test_installer_version_difference_triggers_update() { run_installer "$root" install --binary "$binary" --yes >"$output" - grep -Fq "установщик: 0.20.0" "$output" || + grep -Fq "установщик: 0.20.2" "$output" || fail "план не показал версию запущенного установщика" grep -Fq "установлен: 0.2.0" "$output" || fail "план не показал прежнюю установленную версию" - grep -Fxq "installer_version=0.20.0" "$ownership" || + grep -Fxq "installer_version=0.20.2" "$ownership" || fail "повтор не обновил версию в метке владения" find "$root/var/lib/wdtt-server-installer/backups" -mindepth 1 -maxdepth 1 \ -type d | grep -q . || fail "различие версий ошибочно обработано как no-op" run_installer "$root" status >"$output" - grep -Fq "Версия этого установщика: 0.20.0" "$output" || + grep -Fq "Версия этого установщика: 0.20.2" "$output" || fail "status не показывает версию файла" - grep -Fq "Установлено версией: 0.20.0" "$output" || + grep -Fq "Установлено версией: 0.20.2" "$output" || fail "status не показывает установленную версию" grep -Fq "Версии установщика: совпадают" "$output" || fail "status не сравнивает версии" @@ -1862,7 +1862,7 @@ test_rejects_incompatible_server_version() { make_config "$config" "SafeOwnerPassword42" expect_failure "$output" run_installer "$root" check --binary "$binary" --config "$config" - grep -Fq "Поддерживается wdtt-server версии 17" "$output" || + grep -Fq "Поддерживается wdtt-server версии 19" "$output" || fail "несовместимая версия сервера отклонена без понятной ошибки" pass "несовместимая версия wdtt-server отклоняется" } diff --git a/server-installer/tests/version_sync_test.sh b/server-installer/tests/version_sync_test.sh new file mode 100644 index 0000000..482b74a --- /dev/null +++ b/server-installer/tests/version_sync_test.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash + +set -euo pipefail + +readonly TEST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +readonly REPOSITORY_ROOT="$(cd "$TEST_DIR/../.." && pwd)" +readonly CONTRACT="$REPOSITORY_ROOT/server-installer/compatibility-contract.env" +readonly ANDROID_BUILD="$REPOSITORY_ROOT/app/build.gradle.kts" +readonly SERVER="$REPOSITORY_ROOT/server.go" +readonly DEPLOY="$REPOSITORY_ROOT/app/src/main/assets/deploy.sh" +readonly INSTALLER="$REPOSITORY_ROOT/server-installer/install.sh" +readonly INSTALLER_README="$REPOSITORY_ROOT/server-installer/README.md" +readonly CHANGELOG="$REPOSITORY_ROOT/CHANGELOG.md" + +fail() { + printf 'FAIL: синхронизация версий: %s\n' "$*" >&2 + exit 1 +} + +read_kotlin_string() { + local name="$1" value + value="$(sed -n "s/^[[:space:]]*val[[:space:]]\+$name[[:space:]]*=[[:space:]]*\"\([0-9][0-9]*\)\"[[:space:]]*$/\1/p" "$ANDROID_BUILD")" + [[ -n "$value" && "$value" != *$'\n'* ]] || fail "не удалось прочитать $name" + printf '%s' "$value" +} + +read_kotlin_integer() { + local name="$1" value + value="$(sed -n "s/^[[:space:]]*val[[:space:]]\+$name[[:space:]]*=[[:space:]]*\([0-9][0-9]*\)[[:space:]]*$/\1/p" "$ANDROID_BUILD")" + [[ -n "$value" && "$value" != *$'\n'* ]] || fail "не удалось прочитать $name" + printf '%s' "$value" +} + +read_android_version_code() { + local value + value="$(sed -n 's/^[[:space:]]*versionCode[[:space:]]*=[[:space:]]*\([0-9][0-9]*\)[[:space:]]*$/\1/p' "$ANDROID_BUILD")" + [[ -n "$value" && "$value" != *$'\n'* ]] || fail "не удалось прочитать Android versionCode" + printf '%s' "$value" +} + +[[ -f "$CONTRACT" && ! -L "$CONTRACT" ]] || fail "нет канонического контракта" +# shellcheck source=/dev/null +source "$CONTRACT" +[[ "${WDTT_SERVER_VERSION:-}" =~ ^[0-9]+$ ]] || fail "в контракте некорректна версия сервера" + +app_name="$(read_kotlin_string appVersionName)" +app_code="$(read_kotlin_integer appVersionCode)" +android_code="$(read_android_version_code)" +[[ "$app_name" == "$WDTT_SERVER_VERSION" ]] || + fail "appVersionName=$app_name, сервер=$WDTT_SERVER_VERSION" +[[ "$app_code" == "$WDTT_SERVER_VERSION" ]] || + fail "appVersionCode=$app_code, сервер=$WDTT_SERVER_VERSION" +[[ "$android_code" == "$app_code" ]] || + fail "Android versionCode=$android_code, appVersionCode=$app_code" + +grep -Eq "wdttServerVersion[[:space:]]*=[[:space:]]*\"$WDTT_SERVER_VERSION\"" "$SERVER" || + fail "server.go не соответствует версии $WDTT_SERVER_VERSION" +grep -Fxq "readonly WDTT_SERVER_VERSION=\"$WDTT_SERVER_VERSION\"" "$DEPLOY" || + fail "Android-установщик не соответствует версии $WDTT_SERVER_VERSION" +grep -Fxq "readonly SUPPORTED_SERVER_VERSION=\"$WDTT_SERVER_VERSION\"" "$INSTALLER" || + fail "ручной установщик не соответствует версии $WDTT_SERVER_VERSION" + +installer_version="$(sed -n 's/^readonly INSTALLER_VERSION="\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)"$/\1/p' "$INSTALLER")" +[[ -n "$installer_version" && "$installer_version" != *$'\n'* ]] || + fail "не удалось прочитать отдельную версию ручного установщика" +installer_intro="$(sed -n '1,16p' "$INSTALLER_README")" +grep -Fq "\`wdtt-server\` версии \`$WDTT_SERVER_VERSION\`" <<<"$installer_intro" || + fail "инструкция ручной установки указывает другую версию сервера" +grep -Fq "автономный установщик \`$installer_version\`" <<<"$installer_intro" || + fail "инструкция ручной установки указывает другую версию скрипта" +bundle_name="WDTT-Plus-server-v${WDTT_SERVER_VERSION}-installer-${installer_version}-linux-amd64.tar.gz" +grep -Fxq "$bundle_name" "$INSTALLER_README" || + fail "имя серверного архива в инструкции не соответствует выпуску" +grep -Fxq "$bundle_name.sha256" "$INSTALLER_README" || + fail "имя контрольной суммы в инструкции не соответствует выпуску" + +first_changelog_version="$(sed -n 's/^## v\([0-9][0-9]*\).*/\1/p' "$CHANGELOG" | head -n 1)" +[[ "$first_changelog_version" == "$WDTT_SERVER_VERSION" ]] || + fail "верхняя версия CHANGELOG=$first_changelog_version, ожидается $WDTT_SERVER_VERSION" + +printf 'Совместимость версий подтверждена: приложение и сервер v%s, ручной установщик %s.\n' \ + "$WDTT_SERVER_VERSION" "$installer_version" diff --git a/server.go b/server.go index 5276584..5800006 100644 --- a/server.go +++ b/server.go @@ -31,6 +31,8 @@ import ( "syscall" "time" + "wdtt.local/pathprobe" + "crypto/cipher" "github.com/pion/dtls/v3" @@ -48,7 +50,7 @@ import ( ) const ( - wdttServerVersion = "17" + wdttServerVersion = "19" wgIfaceName = "wdtt0" wgServerAddr = "10.66.66.1" wgServerCIDR = wgServerAddr + "/24" @@ -68,18 +70,22 @@ const ( // A deviceWGRelay gives all workers of one device one stable source socket and // only multiplexes the already-encrypted WireGuard datagrams around it. type deviceWGAttachment struct { + lease atomic.Pointer[accessWorkerLease] + queue *transportQueue downstream chan []byte } type deviceWGRelay struct { - key string - conn *net.UDPConn - mu sync.Mutex - attachments map[*deviceWGAttachment]struct{} - order []*deviceWGAttachment - rrIndex int - rrCount int - closed bool + lastOrderReport time.Time + uplinkOrder transportOrder + key string + conn *net.UDPConn + mu sync.Mutex + attachments map[*deviceWGAttachment]struct{} + order []*deviceWGAttachment + rrIndex int + rrCount int + closed bool } var deviceWGRelays = struct { @@ -113,8 +119,15 @@ func acquireDeviceWGRelay(deviceID, wgEndpoint string) (*deviceWGRelay, *deviceW go relay.readLoop() } attachment := &deviceWGAttachment{downstream: make(chan []byte, 384)} + if transportMetricsEnabled { + attachment.queue = newTransportQueue(384) + } + // The registry lock protects lookup/lifetime, not the readers of this + // relay. Publication must use the same lock as dispatch and release. + relay.mu.Lock() relay.attachments[attachment] = struct{}{} relay.order = append(relay.order, attachment) + relay.mu.Unlock() return relay, attachment, nil } @@ -126,6 +139,7 @@ func (relay *deviceWGRelay) release(attachment *deviceWGAttachment) { defer deviceWGRelays.Unlock() relay.mu.Lock() delete(relay.attachments, attachment) + attachment.drainMeasured() for i, candidate := range relay.order { if candidate == attachment { relay.order = append(relay.order[:i], relay.order[i+1:]...) @@ -140,6 +154,7 @@ func (relay *deviceWGRelay) release(attachment *deviceWGAttachment) { } empty := len(relay.attachments) == 0 if empty && !relay.closed { + relay.uplinkOrder.report("server_uplink") relay.closed = true _ = relay.conn.Close() } @@ -155,9 +170,14 @@ func (relay *deviceWGRelay) writeFrom(attachment *deviceWGAttachment, packet []b if relay.closed { return net.ErrClosed } - if _, ok := relay.attachments[attachment]; !ok { + if _, ok := relay.attachments[attachment]; !ok || attachment.isRetired() { return net.ErrClosed } + relay.uplinkOrder.observe(packet) + if transportMetricsEnabled && time.Since(relay.lastOrderReport) >= 5*time.Second { + relay.uplinkOrder.report("server_uplink") + relay.lastOrderReport = time.Now() + } _, err := relay.conn.Write(packet) return err } @@ -165,13 +185,17 @@ func (relay *deviceWGRelay) writeFrom(attachment *deviceWGAttachment, packet []b func (relay *deviceWGRelay) nextAttachment() *deviceWGAttachment { relay.mu.Lock() defer relay.mu.Unlock() + return relay.nextAttachmentLocked() +} + +func (relay *deviceWGRelay) nextAttachmentLocked() *deviceWGAttachment { if relay.closed || len(relay.order) == 0 { return nil } for attempts := 0; attempts < len(relay.order); attempts++ { index := relay.rrIndex % len(relay.order) attachment := relay.order[index] - if _, attached := relay.attachments[attachment]; attached { + if _, attached := relay.attachments[attachment]; attached && !attachment.isRetired() { relay.rrCount++ if relay.rrCount >= multipathRelayChunk { relay.rrIndex = (index + 1) % len(relay.order) @@ -192,16 +216,7 @@ func (relay *deviceWGRelay) readLoop() { if err != nil { return } - packet := append([]byte(nil), buf[:n]...) - attachment := relay.nextAttachment() - if attachment == nil { - continue - } - select { - case attachment.downstream <- packet: - default: - // A blocked DTLS path must not stall the shared WireGuard reader. - } + relay.dispatchPacket(buf[:n]) } } @@ -1809,6 +1824,7 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD password := "" deviceInfo := deviceInfoPayload{} transportSession := "" + var workerRef []pathprobe.Worker if len(parts) > 0 { clientPort = parts[0] } @@ -1824,6 +1840,13 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD if len(parts) > 4 { transportSession = strings.TrimSpace(parts[4]) } + if len(parts) > 5 { + ref, valid := pathprobe.ParseWorker(parts[5]) + if !valid || transportSession == "" { + return + } + workerRef = append(workerRef, ref) + } if password != identity.password { atomic.AddInt64(&handshakeFailures, 1) _, _ = clientConn.Write([]byte("DENIED:wrong_password")) @@ -1945,9 +1968,10 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } } if dev != nil { - connDevice = dev authorized = true - configResponse = buildClientConfig(keys.serverPublic, dev.PrivKey, dev.IP, clientPort) + snapshot := *dev + connDevice = &snapshot + configResponse = transportCapabilities() + buildClientConfig(keys.serverPublic, dev.PrivKey, dev.IP, clientPort) } else { configResponse = "NOCONF" } @@ -1973,6 +1997,12 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD return } + if workerAdmitted && len(workerRef) != 0 { + // Re-enter the authenticated slot-aware admission path. The early + // compatibility lease has no relay attachment and releases once. + releaseWorker() + workerAdmitted = false + } if workerAdmitted { if transportSession != "" && !activateAccessSession(workerLease, deviceID, transportSession) { @@ -1984,6 +2014,7 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD clientConn, deviceID, transportSession, + workerRef..., ) } else { runtimeLease, workerLease, releaseWorker, ok = @@ -2047,7 +2078,8 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD // WDTT_MUX1 is sent by current clients before their first WireGuard packet. // Older clients retain the independent-socket path unchanged. - useMultipathRelay := firstStr == multipathRelayHello && connDevice != nil + useUplink := firstStr == adaptiveTransportHello && connDevice != nil + useMultipathRelay := (firstStr == multipathRelayHello || useUplink) && connDevice != nil var relay *deviceWGRelay var relayAttachment *deviceWGAttachment var wgConn net.Conn @@ -2075,10 +2107,18 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD if !accessIdentityIsActive(identity) { return } + if relayAttachment != nil && workerLease != nil { + relayAttachment.lease.Store(workerLease) + } if connDevice != nil { upsertPeerInWG(wgDev, connDevice) } + if useUplink { + if _, err := clientConn.Write([]byte(transportAck)); err != nil { + return + } + } writeToWG := func(packet []byte) error { if relay != nil { return relay.writeFrom(relayAttachment, packet) @@ -2099,6 +2139,13 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD pctx, pcancel := context.WithCancel(ctx) defer pcancel() + if relayAttachment != nil && relayAttachment.queue != nil { + mode := "standard" + if useUplink { + mode = "uplink" + } + go relayAttachment.queue.run(pctx, "server_downlink", mode) + } var clientWriteMu sync.Mutex writeClientPacket := func(packet []byte) error { clientWriteMu.Lock() @@ -2149,6 +2196,11 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD var proxyWg sync.WaitGroup proxyWg.Add(2) + var delivery uplinkReceipt + if useUplink { + proxyWg.Add(1) + go func() { defer proxyWg.Done(); delivery.run(pctx, writeClientPacket, pcancel) }() + } // Клиент → WG go func() { @@ -2168,6 +2220,9 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD if err != nil { return } + if relayAttachment != nil && relayAttachment.queue != nil { + relayAttachment.queue.received.Add(uint64(nn)) + } // Reply to DTLS keepalive packets so clients can detect silent UDP stalls. if nn == 1 && (*b)[0] == dtlsKeepaliveByte { if err := writeClientPacket([]byte{dtlsKeepaliveByte}); err != nil { @@ -2175,6 +2230,29 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } continue } + framed := false + if useUplink { + kind, seq, payload, ok := pathprobe.Parse((*b)[:nn]) + if ok { + if time.Since(lastAccessCheck) >= 5*time.Second { + if !accessIdentityIsActive(identity) { + return + } + lastAccessCheck = time.Now() + } + if runtimeLease.upload.wait(pctx, nn) != nil { + return + } + if !delivery.forward(kind, seq) { + continue + } + if len(payload) < 4 || payload[0] < 1 || payload[0] > 4 || payload[1] != 0 || payload[2] != 0 || payload[3] != 0 { + return + } + nn = copy(*b, payload) + framed = true + } + } if requestID, ok := parseUpdateMetadataRequest((*b)[:nn]); ok { if err := writeClientPacket([]byte(updateMetadataResponsePrefix + requestID + "|ACK|")); err != nil { return @@ -2357,9 +2435,14 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } lastAccessCheck = time.Now() } - if err := runtimeLease.upload.wait(pctx, nn); err != nil { + if useUplink && !framed { return } + if !framed { + if err := runtimeLease.upload.wait(pctx, nn); err != nil { + return + } + } if err := writeToWG((*b)[:nn]); err != nil { return } @@ -2382,15 +2465,12 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD default: } var packet []byte - if relay != nil { - select { - case packet = <-relayAttachment.downstream: - case <-pctx.Done(): + if relayAttachment != nil { + var ok bool + packet, ok = relayAttachment.takeData(pctx) + if !ok { return } - nn := len(packet) - copy(*b, packet) - _ = nn } else { wgConn.SetReadDeadline(time.Now().Add(30 * time.Minute)) nn, err := wgConn.Read(*b) @@ -2405,21 +2485,32 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } packet = append(packet, (*b)[:nn]...) } - nn := len(packet) - if time.Since(lastAccessCheck) >= 5*time.Second { - if !accessIdentityIsActive(identity) { - return + ok := func() bool { + nn := len(packet) + if time.Since(lastAccessCheck) >= 5*time.Second { + if !accessIdentityIsActive(identity) { + return false + } + lastAccessCheck = time.Now() } - lastAccessCheck = time.Now() - } - if err := runtimeLease.download.wait(pctx, nn); err != nil { + if err := runtimeLease.download.wait(pctx, nn); err != nil { + return false + } + writeStarted := time.Now() + err := writeClientPacket(packet) + if relayAttachment != nil && relayAttachment.queue != nil { + relayAttachment.queue.noteWrite(writeStarted, len(packet), err) + } + if err != nil { + return false + } + atomic.AddInt64(&totalBytesToClient, int64(nn)) + recordAccessTraffic(runtimeLease, int64(nn), 0) + return true + }() + if !ok { return } - if err := writeClientPacket(packet); err != nil { - return - } - atomic.AddInt64(&totalBytesToClient, int64(nn)) - recordAccessTraffic(runtimeLease, int64(nn), 0) } }() @@ -3986,17 +4077,55 @@ func deploySafeWDTTSource(ctx context.Context) string { return "" } -func deploySafePublicIP(ctx context.Context, source string) string { - args := []string{"-4fsS", "--connect-timeout", "4", "--max-time", "10"} - if source != "" { - args = append(args, "--interface", source) +// The route and HTTPS probe must use the same destination, without user curl configuration. +func deploySafeRouteUsesInterface(route, expected string) bool { + fields := strings.Fields(route) + for i := 0; i+1 < len(fields); i++ { + if fields[i] == "dev" { + return fields[i+1] == expected && expected != "" + } } - args = append(args, "https://api.ipify.org") - output, err := deploySafeCommandOK(ctx, "curl", args...) - if err != nil || net.ParseIP(output) == nil { + return false +} + +func deploySafeRoutedPublicIP(ctx context.Context, source, iface string) string { + if net.ParseIP(source) == nil || iface == "" { return "" } - return output + return deploySafeProbeIP(ctx, source, iface) +} + +func deploySafePublicIP(ctx context.Context, source string) string { + // A source-bound call alone cannot establish that policy routing was applied. + if source != "" { + return "" + } + return deploySafeProbeIP(ctx, "", "") +} + +func deploySafeProbeIP(ctx context.Context, source, iface string) string { + for _, host := range []string{"api.ipify.org", "checkip.amazonaws.com"} { + args := []string{"-q", "--proxy", "", "--noproxy", "*", "-4fsS", "--connect-timeout", "4", "--max-time", "10"} + if source != "" { + resolved, err := deploySafeCommandOK(ctx, "getent", "ahostsv4", host) + fields := strings.Fields(resolved) + if err != nil || len(fields) == 0 || net.ParseIP(fields[0]).To4() == nil { + continue + } + destination := fields[0] + route, err := deploySafeCommandOK(ctx, "ip", "-4", "route", "get", destination, "from", source) + if err != nil || !deploySafeRouteUsesInterface(route, iface) { + continue + } + args = append(args, "--interface", source, "--resolve", host+":443:"+destination) + } + args = append(args, "https://"+host) + output, err := deploySafeCommandOK(ctx, "curl", args...) + if err == nil && net.ParseIP(output).To4() != nil { + return output + } + } + return "" } func deploySafeOutboundStatus(ctx context.Context, configDir string) string { @@ -4008,7 +4137,11 @@ func deploySafeOutboundStatus(ctx context.Context, configDir string) string { source := deploySafeWDTTSource(ctx) exitIP := serverIP if mode != "direct" && mode != "external_proxy" { - exitIP = deploySafePublicIP(ctx, source) + iface := "wg-wdtt-exit" + if mode == "tun_interface" { + iface = deploySafeFileFirstLine("/etc/wdtt-plus/tun-exit/interface") + } + exitIP = deploySafeRoutedPublicIP(ctx, source, iface) if exitIP == "" { exitIP = "не удалось проверить" } @@ -4060,11 +4193,11 @@ func deploySafeCheckWireGuard(ctx context.Context, configDir, expectedMode strin if source == "" { return "", errors.New("WDTT_ERROR=wdtt_test_source_missing") } - ip := deploySafePublicIP(ctx, source) + ip := deploySafeRoutedPublicIP(ctx, source, "wg-wdtt-exit") if ip == "" { return "", errors.New("WDTT_ERROR=wireguard_exit_check_failed") } - message := fmt.Sprintf("Проверка успешна: WDTT-пользователи выходят через WireGuard. Проверочный IP: %s", ip) + message := fmt.Sprintf("Проверка маршрута сервера через WireGuard успешна. Проверочный IP: %s", ip) if mode != expectedMode { message = fmt.Sprintf("Предупреждение: активен режим %s, ожидался %s.\n%s", deploySafeModeLabel(mode), deploySafeModeLabel(expectedMode), message) } @@ -4083,11 +4216,11 @@ func deploySafeCheckTun(ctx context.Context, interfaceName string) (string, erro if source == "" { return "", errors.New("WDTT_ERROR=wdtt_test_source_missing") } - ip := deploySafePublicIP(ctx, source) + ip := deploySafeRoutedPublicIP(ctx, source, interfaceName) if ip == "" { return "", errors.New("WDTT_ERROR=tun_exit_check_failed") } - return fmt.Sprintf("Проверка успешна: WDTT-пользователи выходят через TUN-интерфейс %s. Проверочный IP: %s", interfaceName, ip), nil + return fmt.Sprintf("Проверка маршрута сервера через TUN-интерфейс %s успешна. Проверочный IP: %s", interfaceName, ip), nil } func deploySafeCheckLocalProxy(ctx context.Context, port, login, password string) (string, error) { @@ -4095,8 +4228,8 @@ func deploySafeCheckLocalProxy(ctx context.Context, port, login, password string return "", errors.New("WDTT_ERROR=local_proxy_service_inactive") } proxy := "127.0.0.1:" + port - ip, commandErr := deploySafeCommandOK(ctx, "curl", "--proxy-user", login+":"+password, "--socks5-hostname", proxy, "-4fsS", "--connect-timeout", "4", "--max-time", "15", "https://api.ipify.org") - if commandErr != nil || net.ParseIP(ip) == nil { + ip, commandErr := deploySafeCommandOK(ctx, "curl", "-q", "--noproxy", "", "--proxy-user", login+":"+password, "--socks5-hostname", proxy, "-4fsS", "--connect-timeout", "4", "--max-time", "15", "https://api.ipify.org") + if commandErr != nil || net.ParseIP(ip).To4() == nil { return "", errors.New("WDTT_ERROR=local_proxy_check_failed") } return fmt.Sprintf("Проверка успешна: SOCKS5 на %s отвечает с указанными логином и паролем. Выходной IP: %s", proxy, ip), nil @@ -4107,13 +4240,13 @@ func deploySafeCheckExternalProxy(ctx context.Context, kind, host, port, login, if kind == "Socks5" { scheme = "socks5h" } - args := []string{"--proxy", scheme + "://" + host + ":" + port} + args := []string{"-q", "--noproxy", "", "--proxy", scheme + "://" + host + ":" + port} if login != "" { args = append(args, "--proxy-user", login+":"+password) } args = append(args, "-4fsS", "--connect-timeout", "5", "--max-time", "18", "https://api.ipify.org") ip, commandErr := deploySafeCommandOK(ctx, "curl", args...) - if commandErr != nil || net.ParseIP(ip) == nil { + if commandErr != nil || net.ParseIP(ip).To4() == nil { return "", errors.New("WDTT_ERROR=external_proxy_check_failed") } return fmt.Sprintf("Проверка успешна: внешний TCP-прокси отвечает. IP через прокси: %s", ip), nil diff --git a/server_runtime.go b/server_runtime.go index 809ad8c..cd78e55 100644 --- a/server_runtime.go +++ b/server_runtime.go @@ -12,6 +12,7 @@ import ( "sync" "sync/atomic" "time" + "wdtt.local/pathprobe" ) const ( @@ -97,11 +98,20 @@ func (b *tokenBucket) allow(amount float64) bool { } func (b *tokenBucket) wait(ctx context.Context, amount int) error { + if err := ctx.Err(); err != nil { + return err + } if b == nil || b.rate <= 0 || amount <= 0 { return nil } need := float64(amount) + if need > b.burst { + return errors.New("packet exceeds rate limiter burst capacity") + } for { + if err := ctx.Err(); err != nil { + return err + } b.mu.Lock() now := time.Now() b.refill(now) @@ -111,8 +121,9 @@ func (b *tokenBucket) wait(ctx context.Context, amount int) error { return nil } missing := need - b.tokens - b.tokens = 0 - b.last = now + // Keep accumulated credit while waiting. Consuming a partial packet + // here makes concurrent workers repeatedly destroy each other's + // allowance and can stall a rate-limited access below its limit. wait := time.Duration(missing / b.rate * float64(time.Second)) b.mu.Unlock() if wait < time.Millisecond { @@ -149,6 +160,7 @@ type accessRuntime struct { disconnectedAt time.Time currentDevice string currentSession string + workerAttempts map[uint32]uint64 workers map[*accessWorkerLease]struct{} upload *tokenBucket download *tokenBucket @@ -157,6 +169,8 @@ type accessRuntime struct { } type accessWorkerLease struct { + worker pathprobe.Worker + retired atomic.Bool runtime *accessRuntime connection net.Conn session string @@ -243,7 +257,7 @@ func acquireAccessWorkerSession( if item.currentSession != "" { activeForCurrentSession = 0 for worker := range item.workers { - if worker.session == item.currentSession { + if worker.session == item.currentSession && !worker.retired.Load() { activeForCurrentSession++ } } @@ -292,6 +306,7 @@ func acquireAccessWorkerForSession( identity accessIdentity, connection net.Conn, deviceID, session string, + workerRef ...pathprobe.Worker, ) (*accessRuntime, *accessWorkerLease, func(), bool) { deviceID = strings.TrimSpace(deviceID) session = strings.TrimSpace(session) @@ -300,10 +315,18 @@ func acquireAccessWorkerForSession( } staleConnections := make([]net.Conn, 0) + var ref pathprobe.Worker + if len(workerRef) > 0 { + ref = workerRef[0] + if !ref.Valid() { + return nil, nil, func() {}, false + } + } accessRuntimes.mu.Lock() item := accessRuntimes.getOrCreateLocked(identity) switch { case item.currentSession == "": + item.workerAttempts = make(map[uint32]uint64) item.currentDevice = deviceID item.currentSession = session for worker := range item.workers { @@ -320,19 +343,30 @@ func acquireAccessWorkerForSession( // has authorized deviceID. item.currentDevice = deviceID item.currentSession = session + item.workerAttempts = make(map[uint32]uint64) for worker := range item.workers { if worker.session == session { continue } + worker.retired.Store(true) if worker.connection != nil { staleConnections = append(staleConnections, worker.connection) } } } + if ref.Valid() && item.workerAttempts[ref.Slot] >= ref.Attempt { + accessRuntimes.mu.Unlock() + return nil, nil, func() {}, false + } activeForSession := 0 + var replaced *accessWorkerLease for worker := range item.workers { - if worker.session == session { + if worker.session == session && !worker.retired.Load() { + if ref.Valid() && worker.worker.Slot == ref.Slot { + replaced = worker + continue + } activeForSession++ } } @@ -341,8 +375,21 @@ func acquireAccessWorkerForSession( atomic.AddInt64(&workerLimitRejections, 1) return nil, nil, func() {}, false } + if replaced != nil { + replaced.retired.Store(true) + if replaced.connection != nil { + staleConnections = append(staleConnections, replaced.connection) + } + } + if ref.Valid() { + if item.workerAttempts == nil { + item.workerAttempts = make(map[uint32]uint64) + } + item.workerAttempts[ref.Slot] = ref.Attempt + } lease := &accessWorkerLease{ + worker: ref, runtime: item, connection: connection, session: session, @@ -358,6 +405,7 @@ func acquireAccessWorkerForSession( for _, staleConnection := range staleConnections { _ = staleConnection.SetDeadline(time.Now()) + _ = staleConnection.Close() } var once sync.Once diff --git a/transport_metrics.go b/transport_metrics.go new file mode 100644 index 0000000..74225f7 --- /dev/null +++ b/transport_metrics.go @@ -0,0 +1,197 @@ +package main + +import ( + "context" + "encoding/binary" + "encoding/json" + "fmt" + "os" + "sync" + "sync/atomic" + "time" +) + +// No addresses, payloads, keys or credentials enter these opt-in measurements. +// Histograms and counters are cumulative for one process-local path ID. +var transportMetricsEnabled = os.Getenv("WDTT_TRANSPORT_METRICS") == "1" +var transportMetricIDs atomic.Uint64 + +func (a *deviceWGAttachment) isRetired() bool { + lease := a.lease.Load() + return lease != nil && lease.retired.Load() +} + +func (a *deviceWGAttachment) offerData(p []byte) bool { + if a.isRetired() { + return false + } + if a.queue != nil { + return a.queue.offer(p) + } + select { + case a.downstream <- p: + return true + default: + return false + } +} +func (a *deviceWGAttachment) takeData(ctx context.Context) ([]byte, bool) { + if a.queue == nil { + select { + case p := <-a.downstream: + return p, true + case <-ctx.Done(): + return nil, false + } + } + p, ok := a.queue.take(ctx) + if ok { + a.queue.noteDequeue(p) + } + return p.data, ok +} +func (a *deviceWGAttachment) drainMeasured() { + if a.queue == nil { + return + } + for { + select { + case <-a.queue.items: + default: + return + } + } +} + +type timedDatagram struct { + data []byte + queued time.Time +} +type transportHistogram struct{ buckets [8]atomic.Uint64 } + +func (h *transportHistogram) observe(d time.Duration) { + limits := [...]time.Duration{time.Millisecond, 3 * time.Millisecond, 10 * time.Millisecond, 30 * time.Millisecond, 100 * time.Millisecond, 300 * time.Millisecond, time.Second} + i := 0 + for i < len(limits) && d > limits[i] { + i++ + } + h.buckets[i].Add(1) +} +func (h *transportHistogram) snapshot() [8]uint64 { + var v [8]uint64 + for i := range v { + v[i] = h.buckets[i].Load() + } + return v +} + +type transportQueue struct { + items chan timedDatagram + id uint64 + enqueued, bytes, full, written, received, writeErrors atomic.Uint64 + wait, write transportHistogram +} + +func newTransportQueue(capacity int) *transportQueue { + return &transportQueue{items: make(chan timedDatagram, capacity), id: transportMetricIDs.Add(1)} +} +func (q *transportQueue) offer(p []byte) bool { + select { + case q.items <- timedDatagram{p, time.Now()}: + q.enqueued.Add(1) + q.bytes.Add(uint64(len(p))) + return true + default: + q.full.Add(1) + return false + } +} +func (q *transportQueue) take(ctx context.Context) (timedDatagram, bool) { + if ctx.Err() != nil { + return timedDatagram{}, false + } + select { + case p := <-q.items: + return p, true + case <-ctx.Done(): + return timedDatagram{}, false + } +} +func (q *transportQueue) noteDequeue(p timedDatagram) { q.wait.observe(time.Since(p.queued)) } +func (q *transportQueue) noteWrite(start time.Time, n int, err error) { + q.write.observe(time.Since(start)) + if err != nil { + q.writeErrors.Add(1) + } else { + q.written.Add(uint64(n)) + } +} +func (q *transportQueue) report(side, mode string, final bool) { + if !transportMetricsEnabled { + return + } + v := map[string]any{"side": side, "mode": mode, "id": q.id, "at": time.Now().UTC().Format(time.RFC3339Nano), "final": final, + "depth": len(q.items), "capacity": cap(q.items), "enqueued": q.enqueued.Load(), "bytes": q.bytes.Load(), "full": q.full.Load(), "written_bytes": q.written.Load(), "received_bytes": q.received.Load(), "write_errors": q.writeErrors.Load(), "wait_bins": q.wait.snapshot(), "write_bins": q.write.snapshot()} + b, _ := json.Marshal(v) + fmt.Printf("TRANSPORT_METRIC|%s\n", b) +} +func (q *transportQueue) run(ctx context.Context, side, mode string) { + if !transportMetricsEnabled { + return + } + t := time.NewTicker(5 * time.Second) + defer t.Stop() + for { + select { + case <-ctx.Done(): + q.report(side, mode, true) + return + case <-t.C: + q.report(side, mode, false) + } + } +} + +// Observe only visible WireGuard transport headers. A lower counter proves +// reordering/duplication, not packet loss. Key rotation uses a bounded map. +type transportOrder struct { + mu sync.Mutex + highest map[uint32]uint64 + packets, late, maxBehind uint64 +} + +func (o *transportOrder) observe(p []byte) { + if !transportMetricsEnabled || len(p) < 32 || binary.LittleEndian.Uint32(p[:4]) != 4 { + return + } + key := binary.LittleEndian.Uint32(p[4:8]) + seq := binary.LittleEndian.Uint64(p[8:16]) + o.mu.Lock() + defer o.mu.Unlock() + if o.highest == nil { + o.highest = make(map[uint32]uint64) + } + high, ok := o.highest[key] + o.packets++ + if ok && seq < high { + o.late++ + if high-seq > o.maxBehind { + o.maxBehind = high - seq + } + } + if !ok || seq > high { + if !ok && len(o.highest) >= 8 { + clear(o.highest) + } + o.highest[key] = seq + } +} +func (o *transportOrder) report(side string) { + if !transportMetricsEnabled { + return + } + o.mu.Lock() + defer o.mu.Unlock() + b, _ := json.Marshal(map[string]any{"side": side, "packets": o.packets, "late_or_duplicate": o.late, "max_behind": o.maxBehind, "at": time.Now().UTC().Format(time.RFC3339Nano)}) + fmt.Printf("TRANSPORT_ORDER|%s\n", b) +} diff --git a/transport_modes.go b/transport_modes.go new file mode 100644 index 0000000..10f8b4c --- /dev/null +++ b/transport_modes.go @@ -0,0 +1,15 @@ +package main + +const adaptiveTransportHello = "WDTT_UPLINK2" +const transportAck = "WDTT_TRANSPORT_OK1" + +func transportCapabilities() string { return "# WDTT_TRANSPORTS=uplink2\n" } + +func (relay *deviceWGRelay) dispatchPacket(packet []byte) { + relay.mu.Lock() + defer relay.mu.Unlock() + chosen := relay.nextAttachmentLocked() + if chosen != nil { + chosen.offerData(append([]byte(nil), packet...)) + } +} diff --git a/transport_uplink.go b/transport_uplink.go new file mode 100644 index 0000000..5beefb8 --- /dev/null +++ b/transport_uplink.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "sync" + "time" + "wdtt.local/pathprobe" +) + +type uplinkReceipt struct { + mu sync.Mutex + receipt pathprobe.Receipt + dirty bool + lastData time.Time + lastReport time.Time +} + +// Receipt is telemetry, not a second replay filter. A datagram may arrive +// outside its small observation window and still be valid to WireGuard. +// Only WireGuard decides whether user data is a replay; probes never enter it. +func (r *uplinkReceipt) forward(kind byte, seq uint64) bool { + if kind != pathprobe.Bypass { + r.observe(seq) + } + return kind != pathprobe.Probe +} + +func (r *uplinkReceipt) observe(seq uint64) bool { + r.mu.Lock() + defer r.mu.Unlock() + ok := r.receipt.Observe(seq) + r.dirty = r.dirty || ok + if ok { + r.lastData = time.Now() + } + return ok +} +func (r *uplinkReceipt) run(ctx context.Context, write func([]byte) error, cancel context.CancelFunc) { + t := time.NewTicker(50 * time.Millisecond) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + r.mu.Lock() + var ack []byte + if r.dirty || (!r.lastData.IsZero() && time.Since(r.lastData) < 2*time.Second && time.Since(r.lastReport) >= 250*time.Millisecond) { + ack = pathprobe.Ack(r.receipt.Expected, r.receipt.Received) + r.dirty = false + r.lastReport = time.Now() + } + r.mu.Unlock() + if ack != nil && write(ack) != nil { + cancel() + return + } + } +}