From cd441e604e12a7b1a57711d57a450880d6499b36 Mon Sep 17 00:00:00 2001 From: Ivan4537 Date: Wed, 29 Jul 2026 15:26:22 +0300 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=8B=D0=BF=D1=83=D1=81=D0=BA=20WDTT=20P?= =?UTF-8?q?lus=20v12?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 16 + CHANGELOG.md | 42 +- README.md | 46 +- admin.go | 638 +++- admin_test.go | 149 + app/build.gradle.kts | 184 +- .../debug/java/com/wdtt/plus/WDTTPreviews.kt | 6 +- app/src/main/AndroidManifest.xml | 26 +- app/src/main/assets/deploy.sh | 59 +- .../java/com/wdtt/plus/AccessLifecycle.kt | 216 ++ .../wdtt/plus/AccessLifecycleCoordinator.kt | 567 +++ .../com/wdtt/plus/AccessLifecycleGateway.kt | 384 ++ app/src/main/java/com/wdtt/plus/AppUpdate.kt | 190 +- .../main/java/com/wdtt/plus/BoundedInput.kt | 19 + .../com/wdtt/plus/CaptchaWebViewManager.kt | 10 +- .../com/wdtt/plus/ClientNetworkDiagnostics.kt | 562 +++ .../java/com/wdtt/plus/ClientTransferCodec.kt | 8 +- .../main/java/com/wdtt/plus/DeployManager.kt | 2 + .../java/com/wdtt/plus/DeviceCompatibility.kt | 10 +- .../main/java/com/wdtt/plus/DeviceIdentity.kt | 29 + .../main/java/com/wdtt/plus/MainActivity.kt | 1117 +++++- .../com/wdtt/plus/QuickToggleTileService.kt | 115 +- .../java/com/wdtt/plus/RemoteActionCatalog.kt | 407 +++ .../wdtt/plus/RemoteContinuationLauncher.kt | 276 ++ .../com/wdtt/plus/RemoteDocumentGateway.kt | 388 ++ .../java/com/wdtt/plus/SecureStringStore.kt | 20 +- .../java/com/wdtt/plus/ServerAdminClient.kt | 19 +- .../java/com/wdtt/plus/ServerMigration.kt | 2 +- .../main/java/com/wdtt/plus/SettingsStore.kt | 1762 ++++++++- .../main/java/com/wdtt/plus/TransferCodec.kt | 15 +- .../main/java/com/wdtt/plus/TrustedWifi.kt | 45 + .../main/java/com/wdtt/plus/TunnelManager.kt | 568 ++- .../wdtt/plus/TunnelProfileRuntimeUpdate.kt | 51 + .../main/java/com/wdtt/plus/TunnelService.kt | 596 +++- .../java/com/wdtt/plus/TunnelStartConfig.kt | 161 +- .../com/wdtt/plus/TunnelStartRequestGate.kt | 20 + .../com/wdtt/plus/TunnelStopCoordinator.kt | 61 + .../java/com/wdtt/plus/TunnelWorkerPolicy.kt | 14 + .../java/com/wdtt/plus/VkClientCredentials.kt | 30 + app/src/main/java/com/wdtt/plus/VkJoinLink.kt | 29 +- .../com/wdtt/plus/VpnCompactWidgetProvider.kt | 26 +- .../java/com/wdtt/plus/VpnWidgetProvider.kt | 115 +- .../java/com/wdtt/plus/WdttApplication.kt | 11 +- .../main/java/com/wdtt/plus/WdttDocument.kt | 28 + .../java/com/wdtt/plus/WireGuardHelper.kt | 63 +- .../wdtt/plus/ui/CollapsingHeaderScroll.kt | 13 + .../main/java/com/wdtt/plus/ui/DeployTab.kt | 2894 ++++++++++++--- .../java/com/wdtt/plus/ui/ExceptionsTab.kt | 133 +- .../java/com/wdtt/plus/ui/FloatingToolbar.kt | 565 ++- app/src/main/java/com/wdtt/plus/ui/InfoTab.kt | 637 +++- .../com/wdtt/plus/ui/OutboundFormsStore.kt | 166 + .../java/com/wdtt/plus/ui/QuickExclusions.kt | 212 ++ .../com/wdtt/plus/ui/ServerClientsSection.kt | 174 +- .../main/java/com/wdtt/plus/ui/SettingsTab.kt | 3134 +++++++++++++++-- .../wdtt/plus/ui/StableSegmentedButtonIcon.kt | 35 + .../java/com/wdtt/plus/ui/TransferCenter.kt | 44 +- .../wdtt/plus/ui/VkClientSettingsDialog.kt | 940 +++++ .../test/java/com/wdtt/plus/AppUpdateTest.kt | 39 + .../java/com/wdtt/plus/BoundedInputTest.kt | 20 + .../wdtt/plus/ClientNetworkDiagnosticsTest.kt | 132 + .../com/wdtt/plus/ClientTransferCodecTest.kt | 14 + .../java/com/wdtt/plus/DeviceIdentityTest.kt | 52 + .../java/com/wdtt/plus/LogSeverityTest.kt | 17 + .../com/wdtt/plus/RemoteActionCatalogTest.kt | 175 + .../java/com/wdtt/plus/TransferCodecTest.kt | 96 + .../java/com/wdtt/plus/TrustedWifiLogTest.kt | 23 + .../java/com/wdtt/plus/TrustedWifiTest.kt | 64 + .../plus/TunnelProfilePresentationTest.kt | 168 + .../plus/TunnelProfileRuntimeUpdateTest.kt | 90 + .../com/wdtt/plus/TunnelRecoveryPolicyTest.kt | 34 + .../com/wdtt/plus/TunnelStartConfigTest.kt | 47 + .../wdtt/plus/TunnelStartRequestGateTest.kt | 27 + .../wdtt/plus/TunnelStopCoordinatorTest.kt | 15 + .../com/wdtt/plus/TunnelWorkerPolicyTest.kt | 20 + .../com/wdtt/plus/VkClientCredentialsTest.kt | 42 + .../test/java/com/wdtt/plus/VkJoinLinkTest.kt | 55 + .../java/com/wdtt/plus/WdttDocumentTest.kt | 32 + .../wdtt/plus/WireGuardRuntimeConfigTest.kt | 72 + .../wdtt/plus/ui/ExceptionsTabBehaviorTest.kt | 96 + .../wdtt/plus/ui/OutboundFormsStoreTest.kt | 35 + .../plus/ui/OutboundProfileComparisonTest.kt | 249 ++ .../com/wdtt/plus/ui/OutboundWireGuardTest.kt | 104 +- .../com/wdtt/plus/ui/ServerMigrationTest.kt | 193 +- .../com/wdtt/plus/ui/VkClientIdProbeTest.kt | 102 + .../com/wdtt/plus/ui/VkHashBulkPasteTest.kt | 74 + bot.go | 286 +- bot_external_proxy_test.go | 110 + docs/icons.md | 17 - docs/outbound-routing.md | 78 - go_client/creds.go | 209 +- go_client/creds_custom_test.go | 80 + go_client/creds_test.go | 28 +- go_client/creds_vkcalls.go | 167 +- go_client/creds_vkcalls_test.go | 81 +- go_client/dns_resolver.go | 161 + go_client/dns_resolver_test.go | 91 + go_client/group.go | 252 +- go_client/group_test.go | 96 + go_client/main.go | 84 +- go_client/protocol.go | 86 +- go_client/protocol_test.go | 126 + go_client/session.go | 241 +- go_client/turn_endpoint.go | 192 + go_client/turn_endpoint_test.go | 70 + server.go | 583 ++- server_runtime.go | 771 ++++ server_runtime_test.go | 407 +++ wg_backend.go | 186 + 108 files changed, 22337 insertions(+), 2201 deletions(-) create mode 100644 app/src/main/java/com/wdtt/plus/AccessLifecycle.kt create mode 100644 app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt create mode 100644 app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt create mode 100644 app/src/main/java/com/wdtt/plus/BoundedInput.kt create mode 100644 app/src/main/java/com/wdtt/plus/ClientNetworkDiagnostics.kt create mode 100644 app/src/main/java/com/wdtt/plus/DeviceIdentity.kt create mode 100644 app/src/main/java/com/wdtt/plus/RemoteActionCatalog.kt create mode 100644 app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt create mode 100644 app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt create mode 100644 app/src/main/java/com/wdtt/plus/TunnelProfileRuntimeUpdate.kt create mode 100644 app/src/main/java/com/wdtt/plus/TunnelStartRequestGate.kt create mode 100644 app/src/main/java/com/wdtt/plus/TunnelStopCoordinator.kt create mode 100644 app/src/main/java/com/wdtt/plus/TunnelWorkerPolicy.kt create mode 100644 app/src/main/java/com/wdtt/plus/VkClientCredentials.kt create mode 100644 app/src/main/java/com/wdtt/plus/WdttDocument.kt create mode 100644 app/src/main/java/com/wdtt/plus/ui/CollapsingHeaderScroll.kt create mode 100644 app/src/main/java/com/wdtt/plus/ui/OutboundFormsStore.kt create mode 100644 app/src/main/java/com/wdtt/plus/ui/QuickExclusions.kt create mode 100644 app/src/main/java/com/wdtt/plus/ui/StableSegmentedButtonIcon.kt create mode 100644 app/src/main/java/com/wdtt/plus/ui/VkClientSettingsDialog.kt create mode 100644 app/src/test/java/com/wdtt/plus/BoundedInputTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/ClientNetworkDiagnosticsTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/DeviceIdentityTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/RemoteActionCatalogTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/TrustedWifiLogTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/TunnelProfilePresentationTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/TunnelProfileRuntimeUpdateTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/TunnelRecoveryPolicyTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/TunnelStartConfigTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/TunnelStartRequestGateTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/TunnelStopCoordinatorTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/TunnelWorkerPolicyTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/VkClientCredentialsTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/VkJoinLinkTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/WdttDocumentTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/WireGuardRuntimeConfigTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/ui/ExceptionsTabBehaviorTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/ui/OutboundFormsStoreTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/ui/OutboundProfileComparisonTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/ui/VkClientIdProbeTest.kt create mode 100644 app/src/test/java/com/wdtt/plus/ui/VkHashBulkPasteTest.kt create mode 100644 bot_external_proxy_test.go delete mode 100644 docs/icons.md delete mode 100644 docs/outbound-routing.md create mode 100644 go_client/creds_custom_test.go create mode 100644 go_client/dns_resolver.go create mode 100644 go_client/dns_resolver_test.go create mode 100644 go_client/protocol_test.go create mode 100644 go_client/turn_endpoint.go create mode 100644 go_client/turn_endpoint_test.go create mode 100644 server_runtime.go create mode 100644 server_runtime_test.go create mode 100644 wg_backend.go diff --git a/.gitignore b/.gitignore index 3d13011..8b3f5d4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ .kotlin/ build/ local.properties +/release-audit .env .env.* !.env.example @@ -44,13 +45,26 @@ server *.p12 *.pfx *.mobileprovision +*.db +*.sqlite +*.sqlite3 +*.kdbx +id_rsa +id_rsa.pub +id_ed25519 +id_ed25519.pub +known_hosts +known_hosts.* google-services.json service-account*.json firebase-service-account*.json credentials*.json secrets*.json +.codex-local .codex-local/ AGENTS.md +docs/*.md +docs/**/*.md # ===== IDE ===== .idea/ @@ -73,3 +87,5 @@ Desktop.ini *.rej msg.txt *.bat +cmd/wdtt-load +cmd/wdtt-load/ diff --git a/CHANGELOG.md b/CHANGELOG.md index ab260c0..f652a0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,46 @@ Здесь фиксируются заметные пользовательские изменения WDTT Plus. +## v12 — 29.07.2026 + +### Туннель и профили + +- Настройки подключения разделены на способы «Ссылка WDTT» и «Вручную». +- Уведомление, плитка и виджеты показывают профиль, с которого действительно запущен VPN. Исправлены повторные подключения и быстрое переключение между профилями. + +### VK и перенос подключения + +- Подключение через VK сначала использует быстрый способ без капчи, а при необходимости автоматически переходит к совместимым резервным вариантам. +- Для отдельного профиля можно добавить собственные резервные `Client ID` и `Client secret`; приложение проверяет их, а секрет хранит в защищённом хранилище устройства. Изменение этих настроек во время работающего VPN блокируется. Этот вариант нужен только старым приложениям с прежними TURN-цепочками VK. +- Окно VK-хешей умеет вставлять сразу несколько ссылок или хешей, заполнять свободные поля, заменять весь набор и очищать отдельные значения. +- Добавлена пошаговая справка по получению VK-хешей через ссылки `vk.ru` и `vk.com`. +- Подключение клиента можно передать ссылкой, QR-кодом или файлом без VK-хеша: получатель добавит собственный перед первым запуском. +- Файлы `.wdtt` можно открыть через Android или выбрать в настройках профилей. + +### Сеть и исключения + +- Подключение стало устойчивее: приложение перебирает доступные TURN-адреса и при необходимости использует резервные TCP/TLS-пути. +- DNS автоматически подстраивается под сеть устройства, в том числе при проблемах подключения в мобильной сети Ростелекома. +- Улучшено восстановление VPN после выхода из доверенной Wi-Fi, пробуждения телефона и смены сети. +- «Быстрые исключения» дополнены приложениями из актуальных белых списков мобильного интернета, а навигация по длинному списку стала удобнее. + +### Сервер, диагностика и обновления + +- После обновления владельцу настроенного сервера предлагается обновить серверную часть с сохранением клиентов и настроек. «Деплой» показывает установленную версию сервера. +- Сервер точнее соблюдает сроки клиентских доступов и ограничения отдельных профилей, а также лучше защищён от всплесков подключений. +- В карточке «Клиенты и сервер» считаются только устройства клиентов. Устройства владельца вынесены отдельно в обзор сервера. +- «Перенос сервера» сохраняет настройки, сроки доступа, статистику и устройства владельца, адаптирует профили к адресу и портам нового сервера и проверяет целостность новых файлов экспорта. Старые файлы остаются совместимыми. +- Переработан раздел «Выходной IP и прокси»: для локального и внешнего прокси, WARP, WireGuard и дополнительного VPS доступны корректные проверка, отключение и удаление. Настройки сохраняются после перезагрузки, а при ошибке восстанавливается прежний рабочий выход. +- Диагностика точнее проверяет сеть телефона, DNS, доступность VK и фактический выход сервера в интернет. Сообщения о неполадках прокси стали понятнее и выводятся по-русски. +- Перед установкой встроенное обновление проверяет, что APK получен из официального выпуска, не повреждён и подписан тем же ключом, что установленное приложение. + +### Готовые профили и поддержка проекта + +- Появилась возможность автоматически получить и добавить готовый профиль через Telegram-бота. +- Для таких профилей доступно автоматическое получение VK-хешей. +- Приложение следит за сроком доступа готового профиля и обновляет его состояние после продления. +- Реализовано получение резервного профиля через сообщество VK. + ## v11 — 07.07.2026 ### Туннель @@ -139,7 +179,7 @@ ### Передача и перенос данных -- Приём и передача подключения находятся в плавающей кнопке «Настройки» → «Передать или получить»: раздел «Получение VPN» принимает QR, изображение из галереи или файл, а раздел «Передача VPN» создаёт QR, ссылку или файл текущего VPN-профиля. +- Приём и передача подключения находятся в плавающей кнопке «Настройки» → «Передать или получить»: раздел «Получить профиль» принимает QR, изображение из галереи или файл, а раздел «Передать профиль» создаёт QR, ссылку или файл текущего VPN-профиля. - VPN-профиль можно передать ссылкой, файлом или QR-кодом, а принять — через Android share, выбор файла, камеру или изображение из галереи. - QR-коды передачи создаются единообразно во всех местах приложения, с подписью WDTT Plus и иконкой приложения рядом с кодом или под ним. - Добавлен выбор профиля для замены при импорте подключения. diff --git a/README.md b/README.md index 38228f8..0756ed7 100644 --- a/README.md +++ b/README.md @@ -44,28 +44,30 @@ ### Что изменено в модификации -- **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Клиента можно перенести отдельно через QR, камеру, изображение, файл, Android Share или код передачи; создать с автоматическим или заданным вручную паролем и безопасно сменить пароль без перезапуска сервера. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями. +- **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Клиента можно перенести отдельно через QR, камеру, изображение, файл, Android Share или код передачи; создать с автоматическим или заданным вручную паролем и безопасно сменить пароль без перезапуска сервера. Сервер защищён от всплесков подключений и поддерживает пределы мощности и скорости для отдельного доступа. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями. - **Обновление, восстановление и перенос сервера:** повторный деплой предлагает безопасное обновление с сохранением данных или чистую установку. Перед обновлением и прямым импортом создаётся страховочная копия; служба и целостность доступов проверяются, а при ошибке выполняется откат. Частичный экспорт переносит базу WDTT Plus, полный дополнительно сохраняет WireGuard-ключи сервера. -- **Ссылки, роли и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Импорт проверяется и занимает свободный VPN-профиль; при трёх занятых приложение запрашивает выбор профиля для замены. Переименованный профиль передаёт своё название вместе с подключением. Для администратора доступен защищённый паролем перенос локальных настроек. -- **Проверка VK-хешей:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Хеши можно копировать по одному или все заполненные сразу в порядке слотов. Настройка мощности сопровождается пояснением о потоках, нагрузке и частоте проверок VK. +- **Режимы пользователя и администратора:** режим «Юзер» оставляет подключение по ссылке или вручную, управление VPN, исключения и логи без серверных полей. Режим «Админ» открывает деплой и полное управление собственным сервером. +- **Ссылки и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Администратор может отправить клиентский доступ ещё до добавления VK-хеша — получатель заполнит его у себя перед запуском. Защищённая короткая ссылка может сразу добавить выданный доступ и предложить автоматическое либо ручное заполнение VK-хешей. Импорт занимает свободный VPN-профиль или предлагает выбрать заменяемый, сохраняет название и при наличии показывает установленный владельцем предел мощности. Полученный профиль показывает срок и доступное действие, а после окончания доступа не запускает VPN. Для администратора доступен защищённый паролем перенос локальных настроек. +- **VK-хеши и независимые провайдеры:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Несколько ссылок или хешей можно вставить из буфера сразу, не затирая заполненные поля без подтверждения. TURN-данные запрашиваются по порядку: быстрый VKCalls без капчи, собственные legacy-реквизиты (если включены), затем выбранные встроенные legacy Client ID; пользовательский secret хранится защищённо. - **Настраиваемый выходной IP:** из Android и Telegram-бота управляются прямой выход, прокси VPS, внешний TCP-прокси, бесплатный WARP, готовый VPN/WireGuard-файл и WireGuard-выход через другой сервер. Приложение показывает состояние режимов на сервере, проверяет конфликтные маршруты перед включением и откатывается при ошибке. - **Маршрутизация приложений:** ЧС и БС являются отдельными списками: в ЧС отмеченные приложения обходят VPN, в БС только отмеченные идут через VPN. Есть быстрый подбор приложений, чувствительных к VPN; смена режима перезапускает только WireGuard-слой. -- **Доверенные сети Wi-Fi:** VPN может автоматически переходить в ожидание в выбранных домашних или рабочих сетях и восстанавливать прежнее подключение после выхода из них. Ручное отключение отменяет автовосстановление, а неопределённая сеть никогда не отключает VPN. -- **Captcha и устойчивость транспорта:** перед captcha-цепочкой можно использовать VKCalls preflight; временный flood не создаёт повторный шквал запросов. Авто-режим начинает с Auto WebView и переходит к Go v2 и ручному WebView только при необходимости. Расширены восстановление после смены сети и пробуждения, контроль зависшего трафика и fail-open отключение неработающего VPN. +- **Доверенные сети Wi-Fi:** VPN может автоматически переходить в ожидание в выбранных домашних или рабочих сетях и восстанавливать прежнее подключение после выхода из них. Восстановление устойчивее работает в фоне и после пробуждения телефона; ручное отключение отменяет его, а неопределённая сеть никогда не отключает VPN. +- **Captcha и устойчивость транспорта:** современный VKCalls используется первым и обычно не требует капчи; временный flood не создаёт повторный шквал запросов. Если нужен legacy-резерв, авто-режим начинает с Auto WebView и переходит к Go v2 и ручному WebView только при необходимости. Клиент использует актуальные адреса `vk.ru`, выбирает рабочий DNS-путь и перебирает резервные TURN-соединения по UDP, TCP и TLS. +- **Диагностика телефона и VPS:** проверка устройства отдельно тестирует системный DNS, DNS-путь клиента, основной VKCalls и резервные VK/OK-узлы из сети телефона. Серверная диагностика сосредоточена на службе, UDP-портах, маршрутизации и выходном интернете; доступ к VK/OK с самого VPS показывается только справочно и не создаёт ложную ошибку. - **Самостоятельная сборка WDTT Plus:** приложение использует пакет `com.wdtt.plus`, собственный канал обновлений и отдельное оформление. Gradle пересобирает Android `libclient.so` и сервер для деплоя из исходников, а release APK получает понятные имена для каждой ABI. ## Возможности Android-версии - **Ориентир совместимости:** WDTT Plus смотрит вперёд и ориентируется на Android 10+ с современными требованиями Android SDK. `targetSdk` 35 — это целевой API сборки, а не верхний предел Android: новые версии Android должны поддерживаться по мере тестирования, включая отдельную проверку нативной части на устройствах с 16 KB page size. Android 9 и ниже не являются основной целью поддержки. -- **Проверка устройства:** при первом запуске приложение в фоне проверяет только архитектурные условия — Android, ABI, нативный клиент, память и размер страницы памяти — и предупреждает, если есть риск несовместимости. В **«Инфо»** доступна ручная расширенная проверка версии WDTT Plus, WebView, сети, разрешений Android, текущего состояния VPN и подсказок для настроек. +- **Проверка устройства:** при первом запуске приложение в фоне проверяет только архитектурные условия — Android, ABI, нативный клиент, память и размер страницы памяти — и предупреждает, если есть риск несовместимости. В **«Инфо»** доступна ручная расширенная проверка версии WDTT Plus, WebView, разрешений Android, системного и клиентского DNS, доступа к VK/OK и текущего состояния VPN. - **Полноценный VPN-режим:** приложение использует `VpnService` и WireGuard GoBackend, поэтому трафик выбранных приложений проходит через системный VPN-интерфейс без ручного импорта конфигов. -- **Три профиля подключения:** VPN 1, VPN 2 и VPN 3 хранят отдельные настройки туннеля и деплоя; профиль можно переименовать долгим нажатием в боковых настройках. Название активного профиля видно в заголовках вкладок, передаче подключения, плитке быстрых настроек и активном уведомлении туннеля. +- **Три профиля подключения:** VPN 1, VPN 2 и VPN 3 хранят отдельные настройки туннеля и деплоя; профиль можно переименовать долгим нажатием в боковых настройках. Название активного профиля видно в заголовках вкладок, передаче подключения, плитке быстрых настроек и активном уведомлении туннеля. Полученный профиль может иметь собственный предел мощности, который показывается рядом с регулятором и не влияет на остальные профили. - **Корректная передача VPN-слота:** если Android отключает WDTT Plus VPN или другой VPN забирает системный VPN-слот, WDTT Plus останавливает транспорт и переводит плитку/виджет в неактивное состояние. Плитка запускает VPN как с обычными настройками, так и в режиме ссылки, а при активном подключении показывает выбранный профиль вместе с уведомлением туннеля. - **Доверенные сети Wi-Fi:** в боковых настройках можно добавить текущую сеть или точный SSID вручную. В доверенной сети системный VPN-интерфейс снимается и интернет работает напрямую, а тихое уведомление сохраняет режим ожидания. После перехода на мобильную или другую Wi-Fi сеть прежний VPN-профиль восстанавливается. Android запрашивает доступ к местоположению только потому, что относит имя Wi-Fi к чувствительным данным; координаты приложение не получает. -- **TURN/DTLS-транспорт:** нативный Go-клиент получает временные TURN-учётные данные VK-звонка и поднимает DTLS-соединения к relay-серверу, через который передаётся трафик до вашего сервера. +- **TURN/DTLS-транспорт:** нативный Go-клиент получает временные TURN-учётные данные VK-звонка и поднимает DTLS-соединения к relay-серверу, через который передаётся трафик до вашего сервера. Если основной TURN-путь не отвечает, клиент пробует другие выданные адреса и доступные варианты UDP, TCP или TLS. - **Импорт VK-ссылок через «Поделиться»:** ссылку VK-звонка можно отправить прямо в WDTT Plus. Приложение извлечёт хеш после `/call/join/`, заполнит следующий слот VK-хеша и покажет, какой номер был обновлён. -- **Передача между устройствами:** текущий VPN-профиль отправляется как `wdtt://`-ссылка, файл или QR-код. Приложение принимает эти данные через Android, камеру, галерею и выбор файла, сохраняя совместимость со старыми ссылками. -- **Проверка VK-хешей:** окно VK-хешей умеет проверить, жив ли групповой звонок, решить VK Captcha в процессе проверки, показать понятный статус по каждому полю и скопировать один или все заполненные хеши. +- **Передача и получение подключения:** текущий VPN-профиль отправляется как `wdtt://`-ссылка, файл или QR-код. Приложение принимает эти данные через Android, камеру, галерею и выбор файла, сохраняя совместимость со старыми ссылками. Клиентский доступ можно передать без VK-хеша, чтобы получатель добавил собственный перед запуском. Защищённая короткая ссылка также может добавить выданный профиль без VK-хешей, после чего приложение предложит получить их автоматически или ввести вручную. +- **Проверка VK-хешей:** окно VK-хешей умеет проверить, жив ли групповой звонок, решить VK Captcha в процессе проверки, показать понятный статус по каждому полю, очистить отдельный слот и скопировать один или все заполненные хеши. Из буфера можно вставить до четырёх ссылок или хешей сразу с выбором: заполнить свободные поля или заменить набор. - **TLS/HTTP-отпечаток:** по умолчанию используется Firefox fingerprint, при необходимости его можно переключить в настройках приложения. - **WRAP без захардкоженного ключа:** внешний RTP AEAD/ChaCha20-Poly1305 слой выводится из пароля подключения через HKDF. Один пароль — один WRAP-ключ, ключ не хранится в APK. - **RTP AEAD обфускация:** транспорт маскируется под RTP/WebRTC аудиотрафик с OPUS payload type, а полезная нагрузка шифруется AEAD-слоем поверх DTLS/WireGuard. @@ -75,11 +77,11 @@ - **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит пользовательских паролей, 16-символьную генерацию, ручное задание пароля с проверками, привязку к устройству и срок действия. Клиентов можно создавать, импортировать, экспортировать, отключать, продлевать, отвязывать, удалять и менять им пароль из приложения или Telegram-бота. - **Горячее обновление WRAP-ключей:** создание, удаление и истечение паролей обновляют набор WRAP-ключей на сервере без перезапуска ядра. - **Исключения приложений:** ЧС и БС хранят независимые наборы. В ЧС отмеченные приложения работают напрямую, в БС только отмеченные направляются в VPN; изменения применяются быстрой перезагрузкой WireGuard. -- **Рабочая captcha-цепочка:** сначала приложение пробует получить TURN credentials через отключаемый VKCalls preflight. Если анонимный вход недоступен, Auto WebView решает обычную проверку, Go v2 используется как следующий автоматический этап, а ручной WebView остаётся fallback для slider/puzzle и других строгих проверок. -- **Живой лог-вьюер:** события Go-клиента, DTLS, WireGuard, WRAP, капчи, деплоя и статистики отображаются с группировкой повторов. Временные сбои показываются как предупреждения, а красным выделяются критические ошибки. После отключения итоговый трафик и доступная причина сохраняются, а завершённая сессия отображается неактивной. -- **Фоновая устойчивость:** `Foreground Service`, `WakeLock`, `WifiLock`, мягкий reconnect по валидированной сети и проверка после пробуждения помогают переживать Doze, смену Wi-Fi/LTE, DNS-сбои до VK и падение нативного процесса без агрессивных перезапусков. -- **VK Auth fallback:** клиент использует 2 проверенных VK `client_id` и переключается между ними при ошибках авторизации. -- **DNS fallback:** сначала используются Yandex DNS `77.88.8.8` / `77.88.8.1`, а при отказе или таймаутах выполняется fallback на системный провайдерский DNS устройства. +- **Рабочая цепочка VK:** сначала приложение пробует современный отключаемый VKCalls без капчи, затем собственный legacy Client ID и выбранные встроенные legacy ID. Для legacy-провайдеров Auto WebView решает обычную проверку, Go v2 используется как следующий автоматический этап, а ручной WebView остаётся fallback для slider/puzzle и других строгих проверок. +- **Живой лог-вьюер:** события Go-клиента, выбранного VK-провайдера, переходов между резервами, DTLS, WireGuard, WRAP, капчи, деплоя и статистики отображаются с группировкой повторов. Временные сбои показываются как предупреждения, а красным выделяются критические ошибки. После отключения итоговый трафик и доступная причина сохраняются, а завершённая сессия отображается неактивной. +- **Фоновая устойчивость:** `Foreground Service`, `WakeLock`, `WifiLock`, мягкий reconnect по валидированной сети и проверка после пробуждения помогают переживать Doze, смену Wi-Fi/LTE, DNS-сбои до VK и падение нативного процесса без агрессивных перезапусков. Выход из доверенной Wi-Fi дополнительно контролируется до фактического восстановления VPN. +- **VK Auth fallback:** собственные legacy-реквизиты не заменяют быстрый VKCalls и встроенную цепочку, а добавляются между ними как отдельный резерв. Ошибка собственного Client ID явно отображается в журнале, после чего клиент пробует выбранные встроенные ID. +- **DNS fallback:** клиент проверяет основной и резервный Yandex DNS по UDP, затем по TCP, а при их недоступности использует системный DNS устройства. - **Темы и оформление:** Material 3, Jetpack Compose, Inter, светлая/тёмная тема, Dynamic Colors на Android 12+ и встроенные палитры. - **Автообновления:** приложение проверяет релизы WDTT Plus при запуске, при возврате из фона не чаще одного раза в 5 минут и каждые 30 минут, если остаётся открытым. Подходящий APK скачивается внутри приложения и передаётся системному установщику Android. Если APK текущей версии был заменён в релизе, WDTT Plus сверяет SHA-256 установленного APK со всеми APK релиза и предлагает исправление текущей версии. @@ -103,7 +105,7 @@ Android-приложение → VpnService / WireGuard GoBackend → локал 1. Соберите APK по разделу [«Для разработки»](#для-разработки) или скачайте готовую сборку со [страницы релизов WDTT Plus](https://github.com/Ivan4537/WDTT-Plus/releases), когда она опубликована. 2. Установите приложение на Android-смартфон. Основной ориентир совместимости — Android 10+. 3. Подготовьте домен или IP сервера, SSH-логин и SSH-пароль. -4. В VK создайте или откройте групповой звонок и отправьте ссылку вида `vk.com/call/join/xxxxxxxxxxx` в WDTT Plus через **«Поделиться»** либо скопируйте её вручную. +4. В VK создайте или откройте групповой звонок и отправьте ссылку вида `vk.ru/call/join/xxxxxxxxxxx` в WDTT Plus через **«Поделиться»** либо скопируйте её вручную. Старые ссылки `vk.com/call/join/...` также поддерживаются. 5. Откройте **WDTT Plus** и перейдите во вкладку **«Деплой»**. 6. Введите IP/домен сервера, SSH-логин, пароль и SSH-порт. 7. В **«Секретах»** задайте главный пароль туннеля. При необходимости добавьте Telegram `admin_id` / `bot_token` для управления доступом. @@ -124,7 +126,7 @@ VK → группа → звонок → ссылка приглашения → 1. Откройте VK и создайте пустую группу или используйте существующую. 2. Начните групповой звонок. 3. Отправьте ссылку приглашения в WDTT Plus через системное меню **«Поделиться»** или скопируйте её вручную. -4. Приложение само разбирает полную ссылку `vk.com/call/join/...`, убирает лишние параметры и заполняет первое свободное поле VK-хеша в активном VPN-профиле. +4. Приложение само разбирает полную ссылку `vk.ru/call/join/...` (и старый вариант `vk.com/call/join/...`), убирает лишние параметры и заполняет первое свободное поле VK-хеша в активном VPN-профиле. 5. Если такой хеш уже добавлен, WDTT Plus покажет ошибку и не создаст дубль. Если все 4 поля заняты, будет обновлён следующий слот по кругу с предупреждением о перезаписи. 6. Можно использовать до **4 хешей** одновременно для распределения нагрузки и увеличения доступного числа потоков. @@ -158,7 +160,7 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se В блоке **«Клиенты и сервер»** вкладки **«Деплой»** можно искать и фильтровать клиентов, создавать доступы с автоматическим или ручным паролем, редактировать параметры, срок и привязку устройства, менять пароль, а также передавать подключение ссылкой, файлом или QR-кодом. Там же доступны экспорт и импорт отдельного клиента для ручного переноса на другой сервер, история, трафик, настройки сервера, очистка устаревших записей и сервисные действия. После импорта приложение перечитывает список сервера и выбирает добавленного клиента. -Экспорт отдельного клиента переносит только данные доступа: пароль, название, VK-хеши, срок и состояние. Устройство, WireGuard-ключи, статистика, история, адрес, порты и серверные параметры не копируются; после импорта клиент использует настройки нового сервера и привязывается к устройству при первом подключении. +Экспорт отдельного клиента переносит только данные доступа: пароль, название, имеющиеся VK-хеши, срок и состояние. Устройство, WireGuard-ключи, статистика, история, адрес, порты и серверные параметры не копируются; после импорта клиент использует настройки нового сервера и привязывается к устройству при первом подключении. Обычные изменения применяются работающим сервером сразу и не прерывают остальных клиентов: Android вызывает admin-команды по SSH, а они обращаются к закрытому локальному сокету `wdtt-server`, не открывая отдельный управляющий порт в сеть. Явный перезапуск сервиса оставлен отдельным подтверждаемым действием. При удалении или истечении пароля соответствующий WRAP-ключ удаляется из памяти сервера. @@ -166,12 +168,12 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se #### Передача между устройствами -Раздел **«Передать или получить»** находится в боковых настройках. Пользователь может отправить активный VPN-профиль ссылкой, файлом или QR-кодом; на другом устройстве данные можно открыть напрямую, выбрать как файл, отсканировать камерой либо распознать на изображении из галереи. Приложение использует первый пустой профиль VPN, а если заняты все три — предлагает выбрать профиль и подтвердить замену. Названия профилей помогают отличать подключения в заголовках вкладок «Туннель» и «Деплой». +Раздел **«Передать или получить»** находится в боковых настройках. Пользователь может отправить активный VPN-профиль ссылкой, файлом или QR-кодом; на другом устройстве данные можно открыть напрямую, выбрать как файл, отсканировать камерой либо распознать на изображении из галереи. Доступ без VK-хеша тоже распознаётся и сохраняется, но перед запуском получатель должен добавить собственный. Приложение использует первый пустой профиль VPN, а если заняты все три — предлагает выбрать профиль и подтвердить замену. Названия профилей помогают отличать подключения в заголовках вкладок «Туннель» и «Деплой». В режиме администратора там же можно передать все локальные VPN-профили, параметры деплоя, исключения и настройки выхода. Такой экспорт шифруется отдельным паролем; пароль не сохраняется и должен передаваться получателю отдельно. Резервная копия состояния самого сервера по-прежнему импортируется через **«Деплой» → «Перенос сервера»**. > [!WARNING] -> Ссылка и пользовательский QR содержат пароль подключения и VK-хеши. Не публикуйте их и передавайте только доверенному получателю. +> Ссылка и пользовательский QR всегда содержат пароль подключения и могут содержать VK-хеши. Не публикуйте их и передавайте только доверенному получателю. #### Исключения приложений @@ -179,11 +181,11 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se #### Капча -По умолчанию включён режим **«Авто капча»**: приложение пробует VKCalls, затем Auto WebView, Go v2 и при необходимости ручной WebView. Slider/puzzle считается строгой проверкой VK и передаётся пользователю. Вместо автоматической цепочки можно выбрать **«Всегда вручную»**. Ошибки мёртвой ссылки, запрета анонимного входа и переполненного звонка выводятся отдельно и не маскируются под бесконечное решение капчи. +По умолчанию включены быстрый **VKCalls** и режим **«Авто капча»**. Сначала TURN-данные запрашиваются через VKCalls без капчи. Если он недоступен, приложение пробует собственный legacy Client ID (если включён), затем встроенные legacy ID; только в этой резервной ветке используются Auto WebView, Go v2 и при необходимости ручной WebView. Slider/puzzle считается строгой проверкой VK и передаётся пользователю. Вместо автоматического решения можно выбрать **«Всегда вручную»**. Ошибки мёртвой ссылки, запрета анонимного входа и переполненного звонка выводятся отдельно. #### Логирование -Вкладка **«Логи»** показывает статус получения VK-учётных данных, решение капчи, DTLS-handshake, WRAP-состояние, готовность WireGuard, статистику активных воркеров и ошибки. Повторяющиеся строки схлопываются в одну запись со счётчиком. +Вкладка **«Логи»** показывает старт быстрого VKCalls, переходы на собственный и встроенный legacy-провайдеры, использование кэша TURN, решение капчи, DTLS-handshake, WRAP-состояние, готовность WireGuard, статистику активных воркеров и ошибки. Ожидаемый переход на резерв не помечается как критическая ошибка; повторяющиеся строки схлопываются в одну запись со счётчиком. > [!NOTE] > Если видны DTLS handshake, но `Активных: 0`, чаще всего указан неправильный пароль подключения или используется сервер без актуального WRAP-протокола. Если часть потоков уже активна, одиночные DTLS timeout больше не считаются неверным паролем и не останавливают туннель. diff --git a/admin.go b/admin.go index 37418b5..82cc552 100644 --- a/admin.go +++ b/admin.go @@ -2,6 +2,8 @@ package main import ( "context" + "crypto/sha256" + "encoding/base64" "encoding/json" "errors" "flag" @@ -14,18 +16,30 @@ import ( "sort" "strconv" "strings" + "sync" + "sync/atomic" "time" - - "golang.zx2c4.com/wireguard/device" ) type adminResponse struct { OK bool `json:"ok"` + Code string `json:"code,omitempty"` Message string `json:"message,omitempty"` RestartRequired bool `json:"restart_required,omitempty"` Server *adminServerInfo `json:"server,omitempty"` Password *adminPasswordInfo `json:"password,omitempty"` Passwords []adminPasswordInfo `json:"passwords,omitempty"` + ClientState *adminClientState `json:"client_state,omitempty"` +} + +type adminClientState struct { + Version int `json:"version"` + Password string `json:"password"` + DownBytes int64 `json:"down_bytes"` + UpBytes int64 `json:"up_bytes"` + Traffic []TrafficBucket `json:"traffic,omitempty"` + TrafficImports map[string]TrafficImport `json:"traffic_imports,omitempty"` + BindHistory []BindHistoryEntry `json:"bind_history,omitempty"` } type adminRequest struct { @@ -33,26 +47,99 @@ type adminRequest struct { Args []string `json:"args"` } +type adminCommandError struct { + code string + message string +} + +func (e *adminCommandError) Error() string { + if e == nil { + return "" + } + return e.message +} + +func newAdminCommandError(code, message string) error { + return &adminCommandError{code: code, message: message} +} + +func adminErrorResponse(err error) adminResponse { + response := adminResponse{OK: false} + if err == nil { + return response + } + response.Message = err.Error() + var coded *adminCommandError + if errors.As(err, &coded) { + response.Code = coded.code + } + return response +} + type adminLiveSnapshot struct { password string device *ClientDevice } type adminServerInfo struct { - ConfigDir string `json:"config_dir"` - PublicIP string `json:"public_ip,omitempty"` - EffectivePublic string `json:"effective_public_ip,omitempty"` - DNS string `json:"dns,omitempty"` - DefaultPorts string `json:"default_ports"` - MaxPasswords int `json:"max_passwords"` - PasswordCount int `json:"password_count"` - DeviceCount int `json:"device_count"` - ExpiredCount int `json:"expired_count"` - OrphanDeviceCount int `json:"orphan_device_count"` - OrphanDevices []adminDeviceInfo `json:"orphan_devices,omitempty"` - Traffic adminTrafficPeriod `json:"traffic"` - AdminTraffic adminTrafficPeriod `json:"admin_traffic"` - AdminProfile AdminProfileEntry `json:"admin_profile,omitempty"` + WDTTPlusVersion string `json:"wdtt_plus_version"` + BinarySHA256 string `json:"binary_sha256,omitempty"` + WGBackend string `json:"wg_backend,omitempty"` + ConfigDir string `json:"config_dir"` + PublicIP string `json:"public_ip,omitempty"` + EffectivePublic string `json:"effective_public_ip,omitempty"` + DNS string `json:"dns,omitempty"` + DefaultPorts string `json:"default_ports"` + MaxPasswords int `json:"max_passwords"` + MaxWorkersPerAccess int `json:"max_workers_per_access"` + MaxClientMbps float64 `json:"max_client_mbps"` + PasswordCount int `json:"password_count"` + ActivePasswordCount int `json:"active_password_count"` + RetainedExpiredCount int `json:"retained_expired_count"` + AvailablePasswordCount int `json:"available_password_count"` + DeviceCount int `json:"device_count"` + OwnerDeviceCount int `json:"owner_device_count"` + ExpiredCount int `json:"expired_count"` + OrphanDeviceCount int `json:"orphan_device_count"` + ActiveConnections int32 `json:"active_connections"` + CPUPercent float64 `json:"cpu_percent"` + MemoryPercent float64 `json:"memory_percent"` + NetworkRxMbps float64 `json:"network_rx_mbps"` + NetworkTxMbps float64 `json:"network_tx_mbps"` + PacketDrops int64 `json:"packet_drops"` + Reconnects int64 `json:"reconnects"` + HandshakeFailures int64 `json:"handshake_failures"` + HandshakeThrottles int64 `json:"handshake_throttles"` + WorkerLimitRejects int64 `json:"worker_limit_rejections"` + OrphanDevices []adminDeviceInfo `json:"orphan_devices,omitempty"` + Traffic adminTrafficPeriod `json:"traffic"` + AdminTraffic adminTrafficPeriod `json:"admin_traffic"` + AdminProfile AdminProfileEntry `json:"admin_profile,omitempty"` +} + +var ( + runningBinarySHA256Once sync.Once + runningBinarySHA256Sum string +) + +func runningBinarySHA256() string { + runningBinarySHA256Once.Do(func() { + executable, err := os.Executable() + if err != nil { + return + } + source, err := os.Open(executable) + if err != nil { + return + } + defer source.Close() + digest := sha256.New() + if _, err := io.Copy(digest, source); err != nil { + return + } + runningBinarySHA256Sum = fmt.Sprintf("%x", digest.Sum(nil)) + }) + return runningBinarySHA256Sum } type adminTrafficValue struct { @@ -92,6 +179,7 @@ type adminPasswordInfo struct { Ports string `json:"ports"` Status string `json:"status"` ExpiresAt int64 `json:"expires_at,omitempty"` + PurgeAfter int64 `json:"purge_after,omitempty"` DownBytes int64 `json:"down_bytes,omitempty"` UpBytes int64 `json:"up_bytes,omitempty"` DeviceID string `json:"device_id,omitempty"` @@ -154,7 +242,7 @@ func runAdminCLI(args []string) int { return 0 } -func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDev *device.Device, live bool) (adminResponse, error) { +func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDev wgDevice, live bool) (adminResponse, error) { var response adminResponse var err error snapshot := captureAdminLiveSnapshot(loaded, rest) @@ -170,8 +258,12 @@ func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDe } case "details": response, err = adminPasswordDetails(configDir, loaded, rest[1:]) + case "export-client-state": + response, err = adminExportClientState(configDir, loaded, rest[1:]) case "create": response, err = adminCreatePassword(configDir, loaded, rest[1:]) + case "import-client-state": + response, err = adminImportClientState(configDir, loaded, rest[1:]) case "delete": response, err = adminDeletePassword(configDir, loaded, rest[1:]) case "unbind": @@ -186,6 +278,8 @@ func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDe response, err = adminSetPasswordHash(configDir, loaded, rest[1:]) case "set-expiry": response, err = adminSetPasswordExpiry(configDir, loaded, rest[1:]) + case "set-retention": + response, err = adminSetPasswordRetention(configDir, loaded, rest[1:]) case "set-ports": response, err = adminSetPasswordPorts(configDir, loaded, rest[1:]) case "set-password": @@ -212,6 +306,8 @@ func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDe response, err = adminCleanupOrphans(configDir, loaded, wgDev, live) case "reset-traffic": response, err = adminResetTraffic(configDir, loaded) + case "merge-client-traffic": + response, err = adminMergeClientTraffic(configDir, loaded, rest[1:]) case "restart": response = adminResponse{OK: true, Message: "Перезапуск сервиса", RestartRequired: true} default: @@ -268,7 +364,7 @@ func captureAdminLiveSnapshot(loaded *Database, args []string) adminLiveSnapshot } } -func applyLiveAdminEffects(configDir string, loaded *Database, args []string, response adminResponse, snapshot adminLiveSnapshot, wgDev *device.Device) error { +func applyLiveAdminEffects(configDir string, loaded *Database, args []string, response adminResponse, snapshot adminLiveSnapshot, wgDev wgDevice) error { if len(args) == 0 { return nil } @@ -287,16 +383,16 @@ func applyLiveAdminEffects(configDir string, loaded *Database, args []string, re return fmt.Errorf("не удалось добавить WRAP-ключ: %w", err) } case "delete": - if !isAdminSnapshotDevice(loaded, snapshot) { + if shouldRemoveAdminSnapshotPeer(loaded, snapshot) { removePeerFromWG(wgDev, snapshot.device) } serverWrapKeys.RemovePassword(snapshot.password) case "unbind": - if !isAdminSnapshotDevice(loaded, snapshot) { + if shouldRemoveAdminSnapshotPeer(loaded, snapshot) { removePeerFromWG(wgDev, snapshot.device) } case "deactivate": - if !isAdminSnapshotDevice(loaded, snapshot) { + if shouldRemoveAdminSnapshotPeer(loaded, snapshot) { removePeerFromWG(wgDev, snapshot.device) } serverWrapKeys.RemovePassword(snapshot.password) @@ -314,9 +410,10 @@ func applyLiveAdminEffects(configDir string, loaded *Database, args []string, re return errors.New("сервер изменил пароль клиента без нового значения") } newPassword := response.Password.Password - if response.Password.Status == "active" { + entry := loaded.Passwords[newPassword] + if entry != nil && !entry.IsDeactivated && !isPasswordPurgeable(entry) { if err := serverWrapKeys.AddPassword(newPassword); err != nil { - if entry := loaded.Passwords[newPassword]; entry != nil { + if entry != nil { delete(loaded.Passwords, newPassword) loaded.Passwords[snapshot.password] = entry _ = saveAdminDB(configDir, loaded) @@ -325,9 +422,21 @@ func applyLiveAdminEffects(configDir string, loaded *Database, args []string, re } } serverWrapKeys.RemovePassword(snapshot.password) - if !isAdminSnapshotDevice(loaded, snapshot) { + if shouldRemoveAdminSnapshotPeer(loaded, snapshot) { removePeerFromWG(wgDev, snapshot.device) } + case "set-expiry": + if response.Password == nil { + return errors.New("сервер обновил срок клиента без состояния доступа") + } + password := response.Password.Password + if response.Password.Status == "active" { + if err := serverWrapKeys.AddPassword(password); err != nil { + return fmt.Errorf("не удалось вернуть WRAP-ключ после продления: %w", err) + } + } else if response.Password.Status == "deactivated" { + serverWrapKeys.RemovePassword(password) + } case "set-dns", "update-settings": setServerDNS(loaded.DNS) setServerDefaultPorts(loaded.DefaultPorts) @@ -357,6 +466,13 @@ func isAdminSnapshotDevice(loaded *Database, snapshot adminLiveSnapshot) bool { return ok } +func shouldRemoveAdminSnapshotPeer(loaded *Database, snapshot adminLiveSnapshot) bool { + if snapshot.device == nil || isAdminSnapshotDevice(loaded, snapshot) { + return false + } + return !databaseUsesDeviceIDExcept(loaded, snapshot.device.DeviceID, snapshot.password) +} + func adminSocketPath(configDir string) string { if filepath.Clean(configDir) == "/etc/wdtt" { return "/run/wdtt/admin.sock" @@ -381,7 +497,7 @@ func callAdminSocket(configDir string, request adminRequest) (adminResponse, err return response, nil } -func startAdminSocket(ctx context.Context, configDir string, wgDev *device.Device) error { +func startAdminSocket(ctx context.Context, configDir string, wgDev wgDevice) error { path := adminSocketPath(configDir) if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { return err @@ -419,7 +535,7 @@ func startAdminSocket(ctx context.Context, configDir string, wgDev *device.Devic return nil } -func handleAdminSocketConn(conn net.Conn, configDir string, wgDev *device.Device) { +func handleAdminSocketConn(conn net.Conn, configDir string, wgDev wgDevice) { defer conn.Close() _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) var request adminRequest @@ -439,7 +555,7 @@ func handleAdminSocketConn(conn net.Conn, configDir string, wgDev *device.Device } response, err := executeAdminCommand(configDir, db, request.Args, wgDev, true) if err != nil { - response = adminResponse{OK: false, Message: err.Error()} + response = adminErrorResponse(err) } _ = json.NewEncoder(conn).Encode(response) } @@ -620,19 +736,43 @@ func saveAdminDB(configDir string, loaded *Database) error { func buildAdminServerInfo(configDir string, loaded *Database) *adminServerInfo { expired := 0 + active := 0 + retainedExpired := 0 + occupied := 0 + nowUnix := time.Now().Unix() usedDevices := make(map[string]struct{}) + clientDevices := make(map[string]struct{}) for _, entry := range loaded.Passwords { if entry == nil { continue } - if isPasswordExpired(entry) { + if !isPasswordPurgeableAt(entry, nowUnix) { + occupied++ + } + if isPasswordExpiredAt(entry, nowUnix) { expired++ + if isPasswordRetainedExpiredAt(entry, nowUnix) { + retainedExpired++ + } + } else if !entry.IsDeactivated { + active++ } if entry.DeviceID != "" { usedDevices[entry.DeviceID] = struct{}{} + clientDevices[entry.DeviceID] = struct{}{} + } + for _, event := range entry.BindHistory { + deviceID := strings.TrimSpace(event.DeviceID) + if deviceID == "" || event.Status == "denied_mismatch" { + continue + } + if event.BoundAt > 0 || event.Status == "active" || event.Status == "unbound" { + clientDevices[deviceID] = struct{}{} + } } } - for deviceID := range adminDeviceIDSet(loaded) { + ownerDevices := adminDeviceIDSet(loaded) + for deviceID := range ownerDevices { usedDevices[deviceID] = struct{}{} } orphans := 0 @@ -652,21 +792,45 @@ func buildAdminServerInfo(configDir string, loaded *Database) *adminServerInfo { if effectivePublic == "" { effectivePublic = publicIP } + available := loaded.MaxPasswords - occupied + if available < 0 { + available = 0 + } + maxWorkersPerAccess, maxClientMbps := configuredAccessRuntimeLimits() return &adminServerInfo{ - ConfigDir: configDir, - PublicIP: loaded.PublicIP, - EffectivePublic: effectivePublic, - DNS: loaded.DNS, - DefaultPorts: loaded.DefaultPorts, - MaxPasswords: loaded.MaxPasswords, - PasswordCount: len(loaded.Passwords), - DeviceCount: len(loaded.Devices), - ExpiredCount: expired, - OrphanDeviceCount: orphans, - OrphanDevices: orphanDevices, - Traffic: buildAdminDatabaseTraffic(loaded), - AdminTraffic: buildAdminTrafficPeriod(loaded.AdminTraffic, loaded.AdminDownBytes, loaded.AdminUpBytes), - AdminProfile: buildAdminProfileInfo(loaded), + WDTTPlusVersion: wdttServerVersion, + BinarySHA256: runningBinarySHA256(), + WGBackend: activeWGBackend.Load(), + ConfigDir: configDir, + PublicIP: loaded.PublicIP, + EffectivePublic: effectivePublic, + DNS: loaded.DNS, + DefaultPorts: loaded.DefaultPorts, + MaxPasswords: loaded.MaxPasswords, + MaxWorkersPerAccess: maxWorkersPerAccess, + MaxClientMbps: maxClientMbps, + PasswordCount: len(loaded.Passwords), + ActivePasswordCount: active, + RetainedExpiredCount: retainedExpired, + AvailablePasswordCount: available, + DeviceCount: len(clientDevices), + OwnerDeviceCount: len(ownerDevices), + ExpiredCount: expired, + OrphanDeviceCount: orphans, + ActiveConnections: atomic.LoadInt32(&activeConns), + CPUPercent: runtimeCPUPercent(), + MemoryPercent: runtimeMemoryPercent(), + NetworkRxMbps: runtimeNetworkRxMbps(), + NetworkTxMbps: runtimeNetworkTxMbps(), + PacketDrops: atomic.LoadInt64(&runtimePacketDrops), + Reconnects: atomic.LoadInt64(&reconnectCount), + HandshakeFailures: atomic.LoadInt64(&handshakeFailures), + HandshakeThrottles: atomic.LoadInt64(&handshakeThrottles), + WorkerLimitRejects: atomic.LoadInt64(&workerLimitRejections), + OrphanDevices: orphanDevices, + Traffic: buildAdminDatabaseTraffic(loaded), + AdminTraffic: buildAdminTrafficPeriod(loaded.AdminTraffic, loaded.AdminDownBytes, loaded.AdminUpBytes), + AdminProfile: buildAdminProfileInfo(loaded), } } @@ -711,6 +875,148 @@ func adminPasswordDetails(configDir string, loaded *Database, args []string) (ad }, nil } +func adminExportClientState(configDir string, loaded *Database, args []string) (adminResponse, error) { + password, err := adminPasswordArg("export-client-state", args) + if err != nil { + return adminResponse{}, err + } + entry, err := requireAdminPassword(loaded, password) + if err != nil { + return adminResponse{}, err + } + state := &adminClientState{ + Version: 1, + Password: password, + DownBytes: entry.DownBytes, + UpBytes: entry.UpBytes, + Traffic: append([]TrafficBucket(nil), entry.Traffic...), + TrafficImports: cloneTrafficImports(entry.TrafficImports), + BindHistory: append([]BindHistoryEntry(nil), entry.BindHistory...), + } + return adminResponse{ + OK: true, + Message: "Состояние клиента подготовлено", + Server: buildAdminServerInfo(configDir, loaded), + Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, password, entry)), + ClientState: state, + }, nil +} + +func adminImportClientState(configDir string, loaded *Database, args []string) (adminResponse, error) { + fs := flag.NewFlagSet("import-client-state", flag.ContinueOnError) + fs.SetOutput(io.Discard) + password := fs.String("password", "", "пароль клиента") + operationID := fs.String("operation-id", "", "уникальный идентификатор переноса") + encoded := fs.String("state", "", "base64url-состояние клиента") + if err := fs.Parse(args); err != nil { + return adminResponse{}, err + } + key := strings.TrimSpace(*operationID) + if key == "" || len(key) > 160 { + return adminResponse{}, errors.New("operation-id должен содержать 1..160 символов") + } + entry, err := requireAdminPassword(loaded, strings.TrimSpace(*password)) + if err != nil { + return adminResponse{}, err + } + if entry.TrafficImports != nil { + if _, applied := entry.TrafficImports[key]; applied { + return adminResponse{ + OK: true, + Message: "Состояние клиента уже было перенесено", + Server: buildAdminServerInfo(configDir, loaded), + Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, strings.TrimSpace(*password), entry)), + }, nil + } + } + raw, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(*encoded)) + if err != nil || len(raw) == 0 || len(raw) > 128<<10 { + return adminResponse{}, errors.New("состояние клиента повреждено или слишком велико") + } + var state adminClientState + if err := json.Unmarshal(raw, &state); err != nil { + return adminResponse{}, errors.New("состояние клиента имеет неверный формат") + } + if err := validateAdminClientState(&state, strings.TrimSpace(*password)); err != nil { + return adminResponse{}, err + } + if entry.DeviceID != "" || entry.DownBytes != 0 || entry.UpBytes != 0 || + len(entry.Traffic) != 0 || len(entry.BindHistory) != 0 { + return adminResponse{}, newAdminCommandError( + "target_not_empty", + "целевой клиент уже содержит устройство или статистику", + ) + } + previousDown := entry.DownBytes + previousUp := entry.UpBytes + previousTraffic := append([]TrafficBucket(nil), entry.Traffic...) + previousImports := cloneTrafficImports(entry.TrafficImports) + previousHistory := append([]BindHistoryEntry(nil), entry.BindHistory...) + + entry.DownBytes = state.DownBytes + entry.UpBytes = state.UpBytes + entry.Traffic = append([]TrafficBucket(nil), state.Traffic...) + entry.TrafficImports = cloneTrafficImports(state.TrafficImports) + if entry.TrafficImports == nil { + entry.TrafficImports = make(map[string]TrafficImport) + } + entry.TrafficImports[key] = TrafficImport{AppliedAt: time.Now().Unix()} + entry.BindHistory = append([]BindHistoryEntry(nil), state.BindHistory...) + if err := saveAdminDB(configDir, loaded); err != nil { + entry.DownBytes = previousDown + entry.UpBytes = previousUp + entry.Traffic = previousTraffic + entry.TrafficImports = previousImports + entry.BindHistory = previousHistory + return adminResponse{}, err + } + return adminResponse{ + OK: true, + Message: "Статистика и история клиента перенесены", + Server: buildAdminServerInfo(configDir, loaded), + Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, strings.TrimSpace(*password), entry)), + }, nil +} + +func validateAdminClientState(state *adminClientState, password string) error { + if state == nil || state.Version != 1 || state.Password != password { + return errors.New("состояние клиента относится к другому паролю или версии") + } + if state.DownBytes < 0 || state.UpBytes < 0 { + return errors.New("счётчики состояния клиента не могут быть отрицательными") + } + if len(state.Traffic) > trafficHistoryDays || len(state.BindHistory) > 50 || + len(state.TrafficImports) > 1024 { + return errors.New("история состояния клиента превышает допустимый размер") + } + for _, bucket := range state.Traffic { + if len(bucket.Date) != 10 || bucket.DownBytes < 0 || bucket.UpBytes < 0 { + return errors.New("история трафика клиента повреждена") + } + if _, err := time.Parse("2006-01-02", bucket.Date); err != nil { + return errors.New("история трафика клиента содержит неверную дату") + } + } + for key, imported := range state.TrafficImports { + if strings.TrimSpace(key) == "" || len(key) > 160 || + imported.DownBytes < 0 || imported.UpBytes < 0 || imported.AppliedAt < 0 { + return errors.New("история учёта перенесённого трафика повреждена") + } + } + return nil +} + +func cloneTrafficImports(source map[string]TrafficImport) map[string]TrafficImport { + if len(source) == 0 { + return nil + } + result := make(map[string]TrafficImport, len(source)) + for key, value := range source { + result[key] = value + } + return result +} + func buildAdminPasswordInfo(loaded *Database, password string, entry *PasswordEntry) adminPasswordInfo { info := adminPasswordInfo{ Password: password, @@ -727,16 +1033,20 @@ func buildAdminPasswordInfo(loaded *Database, password string, entry *PasswordEn info.Label = entry.Label info.VkHash = entry.VkHash info.ExpiresAt = entry.ExpiresAt + info.PurgeAfter = entry.PurgeAfter info.DownBytes = entry.DownBytes info.UpBytes = entry.UpBytes info.DeviceID = entry.DeviceID info.BindEventsCount = len(entry.BindHistory) info.Traffic = buildAdminTrafficPeriod(entry.Traffic, entry.DownBytes, entry.UpBytes) info.BindHistory = append([]BindHistoryEntry(nil), entry.BindHistory...) - if entry.IsDeactivated { - info.Status = "deactivated" - } else if isPasswordExpired(entry) { + nowUnix := time.Now().Unix() + if isPasswordRetainedExpiredAt(entry, nowUnix) { + info.Status = "expired_retained" + } else if isPasswordExpiredAt(entry, nowUnix) { info.Status = "expired" + } else if entry.IsDeactivated { + info.Status = "deactivated" } if entry.DeviceID != "" { if dev := loaded.Devices[entry.DeviceID]; dev != nil { @@ -810,6 +1120,11 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm ports := fs.String("ports", "", "DTLS,WG,TUN") clientPassword := fs.String("client-password", "", "заданный пароль клиента") expiresAt := fs.Int64("expires-at", -1, "точная дата окончания unix, 0 = бессрочно") + purgeAfter := fs.Int64( + "purge-after", + 0, + "не удалять истёкшую запись до unix timestamp", + ) deactivated := fs.Bool("deactivated", false, "создать клиента отключённым") if err := fs.Parse(args); err != nil { return adminResponse{}, err @@ -819,7 +1134,7 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm } cleanupExpiredPasswordsAdmin(loaded) if len(loaded.Passwords) >= loaded.MaxPasswords { - return adminResponse{}, fmt.Errorf("лимит клиентов: максимум %d", loaded.MaxPasswords) + return adminResponse{}, newAdminCommandError("capacity_full", fmt.Sprintf("лимит клиентов: максимум %d", loaded.MaxPasswords)) } normalizedPorts := loaded.DefaultPorts if strings.TrimSpace(*ports) != "" { @@ -879,6 +1194,10 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm } else if *days > 0 { entry.ExpiresAt = time.Now().Add(time.Duration(*days) * 24 * time.Hour).Unix() } + if err := validatePasswordRetention(entry.ExpiresAt, *purgeAfter); err != nil { + return adminResponse{}, err + } + entry.PurgeAfter = *purgeAfter loaded.Passwords[password] = entry if err := saveAdminDB(configDir, loaded); err != nil { return adminResponse{}, err @@ -1071,21 +1390,67 @@ func adminSetPasswordExpiry(configDir string, loaded *Database, args []string) ( fs.SetOutput(io.Discard) password := fs.String("password", "", "пароль клиента") days := fs.Int("days", 30, "новый срок от текущего момента, 0 = бессрочно") + expiresAt := fs.Int64("expires-at", -1, "точная дата окончания unix, 0 = бессрочно") + purgeAfter := fs.Int64( + "purge-after", + -1, + "не удалять истёкшую запись до unix timestamp; по умолчанию сохраняется прежний интервал", + ) if err := fs.Parse(args); err != nil { return adminResponse{}, err } - if *days < 0 || *days > 365 { + provided := make(map[string]bool) + fs.Visit(func(value *flag.Flag) { + provided[value.Name] = true + }) + if provided["days"] && provided["expires-at"] { + return adminResponse{}, errors.New("укажите только один из параметров: days или expires-at") + } + if !provided["expires-at"] && (*days < 0 || *days > 365) { return adminResponse{}, errors.New("days должен быть 0..365") } entry, err := requireAdminPassword(loaded, *password) if err != nil { return adminResponse{}, err } - if *days == 0 { - entry.ExpiresAt = 0 - } else { - entry.ExpiresAt = time.Now().Add(time.Duration(*days) * 24 * time.Hour).Unix() + nowUnix := time.Now().Unix() + if isPasswordPurgeableAt(entry, nowUnix) { + return adminResponse{}, newAdminCommandError( + "retention_expired", + "запись уже подлежит удалению; создайте доступ заново", + ) } + + newExpiresAt := int64(0) + if provided["expires-at"] { + if *expiresAt < 0 { + return adminResponse{}, errors.New("expires-at должен быть 0 или будущим unix timestamp") + } + newExpiresAt = *expiresAt + if newExpiresAt > 0 && newExpiresAt <= nowUnix { + return adminResponse{}, errors.New("новый срок действия уже истёк") + } + } else if *days > 0 { + newExpiresAt = time.Now().Add(time.Duration(*days) * 24 * time.Hour).Unix() + } + + newPurgeAfter := int64(0) + if provided["purge-after"] { + newPurgeAfter = *purgeAfter + } else { + oldRetentionDuration := entry.PurgeAfter - entry.ExpiresAt + if newExpiresAt > 0 && entry.ExpiresAt > 0 && oldRetentionDuration > 0 { + newPurgeAfter = newExpiresAt + oldRetentionDuration + if newPurgeAfter < newExpiresAt { + return adminResponse{}, errors.New("срок хранения выходит за допустимый диапазон") + } + } + } + if err := validatePasswordRetention(newExpiresAt, newPurgeAfter); err != nil { + return adminResponse{}, err + } + entry.ExpiresAt = newExpiresAt + entry.PurgeAfter = newPurgeAfter if err := saveAdminDB(configDir, loaded); err != nil { return adminResponse{}, err } @@ -1097,6 +1462,80 @@ func adminSetPasswordExpiry(configDir string, loaded *Database, args []string) ( }, nil } +func validatePasswordRetention(expiresAt, purgeAfter int64) error { + if purgeAfter < 0 { + return errors.New("purge-after должен быть неотрицательным unix timestamp") + } + if expiresAt == 0 { + if purgeAfter != 0 { + return errors.New("для бессрочного доступа purge-after должен быть 0") + } + return nil + } + if purgeAfter > 0 && purgeAfter < expiresAt { + return errors.New("purge-after не может быть раньше expires-at") + } + return nil +} + +func adminSetPasswordRetention(configDir string, loaded *Database, args []string) (adminResponse, error) { + fs := flag.NewFlagSet("set-retention", flag.ContinueOnError) + fs.SetOutput(io.Discard) + password := fs.String("password", "", "пароль клиента") + expectedExpiresAt := fs.Int64("expected-expires-at", -1, "ожидаемая дата окончания unix") + purgeAfter := fs.Int64("purge-after", -1, "новая дата удаления истёкшей записи unix") + if err := fs.Parse(args); err != nil { + return adminResponse{}, newAdminCommandError("invalid", err.Error()) + } + if fs.NArg() != 0 { + return adminResponse{}, newAdminCommandError("invalid", "лишние аргументы set-retention") + } + passwordValue := strings.TrimSpace(*password) + if passwordValue == "" { + return adminResponse{}, newAdminCommandError("invalid", "укажите --password") + } + if *expectedExpiresAt <= 0 { + return adminResponse{}, newAdminCommandError("invalid", "expected-expires-at должен быть положительным unix timestamp") + } + if *purgeAfter <= 0 { + return adminResponse{}, newAdminCommandError("invalid", "purge-after должен быть положительным unix timestamp") + } + + entry, err := requireAdminPassword(loaded, passwordValue) + if err != nil { + return adminResponse{}, err + } + nowUnix := time.Now().Unix() + if isPasswordPurgeableAt(entry, nowUnix) { + return adminResponse{}, newAdminCommandError("retention_expired", "истёкшая запись уже подлежит удалению") + } + if entry.ExpiresAt != *expectedExpiresAt { + return adminResponse{}, newAdminCommandError("retention_conflict", "срок доступа изменился; обновите состояние перед повтором") + } + if entry.ExpiresAt <= 0 || entry.PurgeAfter <= 0 { + return adminResponse{}, newAdminCommandError("invalid", "изменить можно только существующий конечный срок хранения") + } + if *purgeAfter < entry.ExpiresAt { + return adminResponse{}, newAdminCommandError("invalid", "purge-after не может быть раньше expires-at") + } + if *purgeAfter <= entry.PurgeAfter { + return adminResponse{}, newAdminCommandError("retention_conflict", "запись уже хранится до такого же или более позднего срока") + } + + previousPurgeAfter := entry.PurgeAfter + entry.PurgeAfter = *purgeAfter + if err := saveAdminDB(configDir, loaded); err != nil { + entry.PurgeAfter = previousPurgeAfter + return adminResponse{}, err + } + return adminResponse{ + OK: true, + Message: "Срок хранения обновлён", + Server: buildAdminServerInfo(configDir, loaded), + Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, passwordValue, entry)), + }, nil +} + func adminSetPasswordPorts(configDir string, loaded *Database, args []string) (adminResponse, error) { fs := flag.NewFlagSet("set-ports", flag.ContinueOnError) fs.SetOutput(io.Discard) @@ -1365,7 +1804,7 @@ func adminRefreshPublicIP(configDir string, loaded *Database, live bool) (adminR return adminResponse{OK: true, Message: "Публичный IP сервера определён: " + value, Server: buildAdminServerInfo(configDir, loaded)}, nil } -func adminCleanupExpired(configDir string, loaded *Database, wgDev *device.Device, live bool) (adminResponse, error) { +func adminCleanupExpired(configDir string, loaded *Database, wgDev wgDevice, live bool) (adminResponse, error) { removed := 0 if live { removed = cleanupExpiredPasswordsLocked(wgDev) @@ -1380,7 +1819,7 @@ func adminCleanupExpired(configDir string, loaded *Database, wgDev *device.Devic return adminResponse{OK: true, Message: fmt.Sprintf("Удалено истёкших клиентов: %d", removed), Server: buildAdminServerInfo(configDir, loaded)}, nil } -func adminCleanupOrphans(configDir string, loaded *Database, wgDev *device.Device, live bool) (adminResponse, error) { +func adminCleanupOrphans(configDir string, loaded *Database, wgDev wgDevice, live bool) (adminResponse, error) { used := make(map[string]struct{}) for _, entry := range loaded.Passwords { if entry != nil && entry.DeviceID != "" { @@ -1427,6 +1866,69 @@ func adminResetTraffic(configDir string, loaded *Database) (adminResponse, error return adminResponse{OK: true, Message: "Счётчики трафика сброшены", Server: buildAdminServerInfo(configDir, loaded)}, nil } +func adminMergeClientTraffic(configDir string, loaded *Database, args []string) (adminResponse, error) { + fs := flag.NewFlagSet("merge-client-traffic", flag.ContinueOnError) + fs.SetOutput(io.Discard) + password := fs.String("password", "", "пароль клиента") + operationID := fs.String("operation-id", "", "уникальный идентификатор переноса") + downBytes := fs.Int64("down-bytes", 0, "скачано на другом сервере") + upBytes := fs.Int64("up-bytes", 0, "отдано на другом сервере") + if err := fs.Parse(args); err != nil { + return adminResponse{}, err + } + key := strings.TrimSpace(*operationID) + if key == "" || len(key) > 160 { + return adminResponse{}, errors.New("operation-id должен содержать 1..160 символов") + } + if *downBytes < 0 || *upBytes < 0 { + return adminResponse{}, errors.New("счётчики трафика не могут быть отрицательными") + } + entry, err := requireAdminPassword(loaded, strings.TrimSpace(*password)) + if err != nil { + return adminResponse{}, err + } + if entry.TrafficImports == nil { + entry.TrafficImports = make(map[string]TrafficImport) + } + if previous, exists := entry.TrafficImports[key]; exists { + if previous.DownBytes != *downBytes || previous.UpBytes != *upBytes { + return adminResponse{}, errors.New("этот operation-id уже применён с другими значениями") + } + return adminResponse{ + OK: true, + Message: "Трафик уже был учтён", + Server: buildAdminServerInfo(configDir, loaded), + Password: ptrAdminPasswordInfo( + buildAdminPasswordInfo(loaded, strings.TrimSpace(*password), entry), + ), + }, nil + } + entry.DownBytes += *downBytes + entry.UpBytes += *upBytes + entry.Traffic = addTrafficBucket( + entry.Traffic, + trafficDayKey(time.Now()), + *downBytes, + *upBytes, + ) + entry.TrafficImports[key] = TrafficImport{ + DownBytes: *downBytes, + UpBytes: *upBytes, + AppliedAt: time.Now().Unix(), + } + if err := saveAdminDB(configDir, loaded); err != nil { + return adminResponse{}, err + } + return adminResponse{ + OK: true, + Message: "Трафик клиента учтён", + Server: buildAdminServerInfo(configDir, loaded), + Password: ptrAdminPasswordInfo( + buildAdminPasswordInfo(loaded, strings.TrimSpace(*password), entry), + ), + }, nil +} + func adminPasswordArg(command string, args []string) (string, error) { fs := flag.NewFlagSet(command, flag.ContinueOnError) fs.SetOutput(io.Discard) @@ -1448,23 +1950,35 @@ func requireAdminPassword(loaded *Database, password string) (*PasswordEntry, er } entry, exists := loaded.Passwords[password] if !exists || entry == nil { - return nil, errors.New("пароль не найден") + return nil, newAdminCommandError("not_found", "пароль не найден") } return entry, nil } func cleanupExpiredPasswordsAdmin(loaded *Database) int { + return cleanupExpiredPasswordsAdminAt(loaded, time.Now().Unix()) +} + +func cleanupExpiredPasswordsAdminAt(loaded *Database, nowUnix int64) int { removed := 0 - nowUnix := time.Now().Unix() + deviceCandidates := make(map[string]struct{}) for password, entry := range loaded.Passwords { - if isPasswordExpired(entry) { - if entry != nil { - unbindPasswordDeviceAdminAt(loaded, entry, nowUnix) + if isPasswordPurgeableAt(entry, nowUnix) { + if entry != nil && entry.DeviceID != "" { + markActiveBindUnbound(entry, entry.DeviceID, nowUnix) + deviceCandidates[entry.DeviceID] = struct{}{} } delete(loaded.Passwords, password) removed++ } } + adminDevices := adminDeviceIDSet(loaded) + for deviceID := range deviceCandidates { + if _, isAdminDevice := adminDevices[deviceID]; isAdminDevice || databaseUsesDeviceID(loaded, deviceID) { + continue + } + delete(loaded.Devices, deviceID) + } return removed } @@ -1478,10 +1992,10 @@ func unbindPasswordDeviceAdminAt(loaded *Database, entry *PasswordEntry, ts int6 } oldDeviceID := entry.DeviceID markActiveBindUnbound(entry, oldDeviceID, ts) - if _, isAdminDevice := adminDeviceIDSet(loaded)[oldDeviceID]; !isAdminDevice { + entry.DeviceID = "" + if _, isAdminDevice := adminDeviceIDSet(loaded)[oldDeviceID]; !isAdminDevice && !databaseUsesDeviceID(loaded, oldDeviceID) { delete(loaded.Devices, oldDeviceID) } - entry.DeviceID = "" } func ptrAdminPasswordInfo(value adminPasswordInfo) *adminPasswordInfo { @@ -1497,7 +2011,7 @@ func writeAdminJSON(response adminResponse) { func writeAdminError(err error) { enc := json.NewEncoder(os.Stdout) enc.SetEscapeHTML(false) - _ = enc.Encode(adminResponse{OK: false, Message: err.Error()}) + _ = enc.Encode(adminErrorResponse(err)) } func adminAtoi(value string) (int, error) { diff --git a/admin_test.go b/admin_test.go index 7ddba5d..032215d 100644 --- a/admin_test.go +++ b/admin_test.go @@ -2,10 +2,142 @@ package main import ( "context" + "encoding/base64" + "encoding/json" "reflect" + "regexp" "testing" + "time" ) +func TestAdminServerInfoReportsRunningBinarySHA256(t *testing.T) { + sum := runningBinarySHA256() + if !regexp.MustCompile(`^[0-9a-f]{64}$`).MatchString(sum) { + t.Fatalf("unexpected running binary SHA-256: %q", sum) + } + info := buildAdminServerInfo(t.TempDir(), &Database{ + DefaultPorts: "56000,56001,9000", + MaxPasswords: 10, + Passwords: make(map[string]*PasswordEntry), + Devices: make(map[string]*ClientDevice), + }) + if info.BinarySHA256 != sum { + t.Fatalf("admin server SHA-256 = %q, want %q", info.BinarySHA256, sum) + } +} + +func TestAdminServerInfoSeparatesClientAndOwnerDevices(t *testing.T) { + loaded := &Database{ + DefaultPorts: "56000,56001,9000", + MaxPasswords: 10, + AdminProfile: AdminProfileEntry{ + DeviceIDs: []string{"owner-phone", "shared-phone", "owner-phone"}, + }, + Passwords: map[string]*PasswordEntry{ + "client-one": { + DeviceID: "shared-phone", + BindHistory: []BindHistoryEntry{ + {DeviceID: "shared-phone", BoundAt: 10, Status: "active"}, + {DeviceID: "old-client-phone", BoundAt: 5, UnboundAt: 9, Status: "unbound"}, + {DeviceID: "rejected-phone", EventAt: 11, Status: "denied_mismatch"}, + }, + }, + "client-two": {}, + }, + Devices: map[string]*ClientDevice{ + "shared-phone": {DeviceID: "shared-phone"}, + "owner-phone": {DeviceID: "owner-phone"}, + "orphan": {DeviceID: "orphan"}, + }, + } + + info := buildAdminServerInfo(t.TempDir(), loaded) + if info.DeviceCount != 2 { + t.Fatalf("client device count = %d, want current plus successful history = 2", info.DeviceCount) + } + if info.OwnerDeviceCount != 2 { + t.Fatalf("owner device count = %d, want 2 unique owner devices", info.OwnerDeviceCount) + } + if info.OrphanDeviceCount != 1 { + t.Fatalf("orphan device count = %d, want 1", info.OrphanDeviceCount) + } +} + +func TestAdminClientStateMovesTrafficAndBindingHistoryExactlyOnce(t *testing.T) { + sourceDir := t.TempDir() + targetDir := t.TempDir() + password := "ABCDEFGHJKLMNPQR" + today := time.Now().Format("2006-01-02") + source := &Database{ + DefaultPorts: "56000,56001,9000", + MaxPasswords: 10, + Passwords: map[string]*PasswordEntry{ + password: { + DownBytes: 8192, + UpBytes: 4096, + Traffic: []TrafficBucket{ + {Date: today, DownBytes: 8192, UpBytes: 4096}, + }, + TrafficImports: map[string]TrafficImport{ + "older-transfer": {DownBytes: 128, UpBytes: 64, AppliedAt: 100}, + }, + BindHistory: []BindHistoryEntry{ + {DeviceID: "old-phone", BoundAt: 10, UnboundAt: 20, Status: "unbound"}, + {DeviceID: "current-phone", BoundAt: 30, Status: "active"}, + }, + }, + }, + Devices: make(map[string]*ClientDevice), + } + exported, err := adminExportClientState( + sourceDir, + source, + []string{"--password", password}, + ) + if err != nil || exported.ClientState == nil { + t.Fatalf("export-client-state failed: response=%#v error=%v", exported, err) + } + raw, err := json.Marshal(exported.ClientState) + if err != nil { + t.Fatal(err) + } + encoded := base64.RawURLEncoding.EncodeToString(raw) + target := &Database{ + DefaultPorts: "56000,56001,9000", + MaxPasswords: 10, + Passwords: map[string]*PasswordEntry{ + password: {}, + }, + Devices: make(map[string]*ClientDevice), + } + args := []string{ + "--password", password, + "--operation-id", "client-transfer-row", + "--state", encoded, + } + for attempt := 0; attempt < 2; attempt++ { + if _, err := adminImportClientState(targetDir, target, args); err != nil { + t.Fatalf("import-client-state attempt %d failed: %v", attempt+1, err) + } + } + entry := target.Passwords[password] + if entry.DownBytes != 8192 || entry.UpBytes != 4096 { + t.Fatalf("traffic totals changed during import: %#v", entry) + } + if !reflect.DeepEqual(entry.Traffic, source.Passwords[password].Traffic) { + t.Fatalf("daily traffic history was not preserved: %#v", entry.Traffic) + } + if !reflect.DeepEqual(entry.BindHistory, source.Passwords[password].BindHistory) { + t.Fatalf("binding history was not preserved: %#v", entry.BindHistory) + } + if _, ok := entry.TrafficImports["client-transfer-row"]; !ok { + t.Fatal("idempotency marker was not recorded") + } + if entry.DeviceID != "" || len(target.Devices) != 0 { + t.Fatal("live device keys must be rebound on the destination, not copied") + } +} + func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) { configDir := t.TempDir() loaded := &Database{ @@ -165,6 +297,23 @@ func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) { if db.Passwords[password].DownBytes != 0 || db.Passwords[password].UpBytes != 0 { t.Fatal("traffic counters were not reset") } + request( + "merge-client-traffic", + "--password", password, + "--operation-id", "incident-row-return", + "--down-bytes", "3072", + "--up-bytes", "4096", + ) + request( + "merge-client-traffic", + "--password", password, + "--operation-id", "incident-row-return", + "--down-bytes", "3072", + "--up-bytes", "4096", + ) + if db.Passwords[password].DownBytes != 3072 || db.Passwords[password].UpBytes != 4096 { + t.Fatal("traffic import must be applied exactly once") + } request("deactivate", "--password", password) dbMutex.Lock() diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 76cb62f..6bee935 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,11 +1,52 @@ +import java.io.File import java.util.Properties +import org.gradle.api.DefaultTask +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.TaskAction + +abstract class VerifyReleaseConfiguration : DefaultTask() { + @get:Input + abstract val keystorePath: Property + + @get:Input + abstract val credentialsComplete: Property + + @get:Input + abstract val productionDomain: Property + + @get:Input + abstract val releaseAuditRequired: Property + + @get:Input + abstract val releaseAuditPath: Property + + @TaskAction + fun verify() { + require(File(keystorePath.get()).isFile) { + "Release signing keystore is required." + } + require(credentialsComplete.get()) { + "Complete release signing credentials are required." + } + require(productionDomain.get()) { + "Release builds must use the production WDTT Plus domain." + } + require( + !releaseAuditRequired.get() || + File(releaseAuditPath.get()).let { it.isFile && it.canExecute() } + ) { + "The local release audit is required but unavailable." + } + } +} plugins { id("com.android.application") id("org.jetbrains.kotlin.plugin.compose") } -val appVersionName = "11" +val appVersionName = "12" val releaseApkBaseName = "WDTT-Plus" val localProperties = Properties() @@ -14,17 +55,47 @@ if (localPropertiesFile.exists()) { localProperties.load(localPropertiesFile.inputStream()) } +fun buildConfigString(value: String): String = + "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + +val wdttPlusDomain = localProperties.getProperty("WDTT_PLUS_DOMAIN") + ?.trim() + ?.trimEnd('/') + ?.takeIf { it.isNotBlank() } + ?: "wdttplus.ru" +val remoteActionPreview = providers.gradleProperty("REMOTE_ACTION_PREVIEW") + .orNull + ?.toBooleanStrictOrNull() + ?: false +val releaseKeystoreProperty = localProperties.getProperty("KEYSTORE_FILE") + ?.trim() + .orEmpty() +val releaseKeystoreFile = when { + releaseKeystoreProperty.startsWith("..") -> + rootDir.resolve(releaseKeystoreProperty.removePrefix("../")) + releaseKeystoreProperty.isNotBlank() -> file(releaseKeystoreProperty) + else -> null +} +val releaseCredentialsComplete = + listOf("KEYSTORE_PASSWORD", "KEY_ALIAS", "KEY_PASSWORD") + .all { !localProperties.getProperty(it).isNullOrBlank() } +val localReleaseAuditRequired = rootProject.file("release.keystore").exists() +val localReleaseAudit = rootProject.file("release-audit") + android { namespace = "com.wdtt.plus" - compileSdk = 35 + compileSdk = 36 defaultConfig { applicationId = "com.wdtt.plus" minSdk = 28 targetSdk = 35 - versionCode = 11 + versionCode = 12 versionName = appVersionName - buildConfigField("String", "MOD_RELEASE_DATE", "\"07.07.2026\"") + buildConfigField("String", "MOD_RELEASE_DATE", "\"29.07.2026\"") + buildConfigField("String", "WDTT_PLUS_DOMAIN", buildConfigString(wdttPlusDomain)) + manifestPlaceholders["wdttPlusDomain"] = wdttPlusDomain + manifestPlaceholders["appLabel"] = "WDTT Plus" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" vectorDrawables { @@ -47,23 +118,11 @@ android { signingConfigs { create("release") { - val keyFile = localProperties.getProperty("KEYSTORE_FILE") - if (keyFile != null) { - // Резолвим путь: если начинается с "..", берём от корня проекта - val resolvedFile = if (keyFile.startsWith("..")) { - // ../release.keystore -> корень проекта / release.keystore - file(rootDir.resolve(keyFile.substring(3))) - } else { - file(keyFile) - } - if (resolvedFile.exists()) { - storeFile = resolvedFile - storePassword = localProperties.getProperty("KEYSTORE_PASSWORD") - keyAlias = localProperties.getProperty("KEY_ALIAS") - keyPassword = localProperties.getProperty("KEY_PASSWORD") - } else { - println("WARNING: Keystore file not found: $keyFile (resolved: ${resolvedFile.absolutePath})") - } + if (releaseKeystoreFile?.isFile == true) { + storeFile = releaseKeystoreFile + storePassword = localProperties.getProperty("KEYSTORE_PASSWORD") + keyAlias = localProperties.getProperty("KEY_ALIAS") + keyPassword = localProperties.getProperty("KEY_PASSWORD") } enableV1Signing = true enableV2Signing = true @@ -72,28 +131,31 @@ android { } buildTypes { + getByName("debug") { + applicationIdSuffix = ".preview" + versionNameSuffix = "-preview" + manifestPlaceholders["appLabel"] = "WDTT Plus Preview" + buildConfigField("boolean", "REMOTE_ACTION_PREVIEW", remoteActionPreview.toString()) + } getByName("release") { + buildConfigField("boolean", "REMOTE_ACTION_PREVIEW", "false") isMinifyEnabled = true isShrinkResources = true proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) - val keyFile = localProperties.getProperty("KEYSTORE_FILE") - val resolvedFile = if (keyFile != null && keyFile.startsWith("..")) { - file(rootDir.resolve(keyFile.substring(3))) - } else if (keyFile != null) { - file(keyFile) - } else null - - if (resolvedFile != null && resolvedFile.exists()) { + if (releaseKeystoreFile?.isFile == true) { signingConfig = signingConfigs.getByName("release") - println("✅ Signing config applied: ${resolvedFile.absolutePath}") - } else { - println("⚠️ WARNING: Keystore not found, using debug signing") - println(" Looked for: ${resolvedFile?.absolutePath ?: keyFile}") } } + create("preview") { + initWith(getByName("release")) + versionNameSuffix = "-preview-ui2" + manifestPlaceholders["appLabel"] = "WDTT Plus Preview" + buildConfigField("boolean", "REMOTE_ACTION_PREVIEW", "true") + signingConfig = signingConfigs.getByName("release") + } } packaging { @@ -113,8 +175,8 @@ android { } lint { - checkReleaseBuilds = false - abortOnError = false + checkReleaseBuilds = true + abortOnError = true } compileOptions { @@ -129,6 +191,19 @@ android { } } +val verifyReleaseConfiguration = + tasks.register("verifyReleaseConfiguration") { + keystorePath.set(releaseKeystoreFile?.absolutePath.orEmpty()) + credentialsComplete.set(releaseCredentialsComplete) + productionDomain.set(wdttPlusDomain == "wdttplus.ru") + releaseAuditRequired.set(localReleaseAuditRequired) + releaseAuditPath.set(localReleaseAudit.absolutePath) + } + +tasks.matching { it.name == "preReleaseBuild" }.configureEach { + dependsOn(verifyReleaseConfiguration) +} + val goClientDir = rootProject.layout.projectDirectory.dir("go_client") val jniLibsDir = layout.projectDirectory.dir("src/main/jniLibs") val serverAssetFile = layout.projectDirectory.file("src/main/assets/server") @@ -174,11 +249,11 @@ tasks.register("buildNativeClient") { mkdir -p "${'$'}jni_dir/${'$'}abi" if [ -n "${'$'}goarm" ]; then env GOOS=android GOARCH="${'$'}goarch" GOARM="${'$'}goarm" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \ - go build -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \ + go build -buildvcs=false -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \ -o "${'$'}jni_dir/${'$'}abi/libclient.so" . else env GOOS=android GOARCH="${'$'}goarch" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \ - go build -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \ + go build -buildvcs=false -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \ -o "${'$'}jni_dir/${'$'}abi/libclient.so" . fi } @@ -220,7 +295,7 @@ tasks.register("buildServerAsset") { out="${'$'}1" mkdir -p "$(dirname "${'$'}out")" env GOOS=linux GOARCH=amd64 CGO_ENABLED=0 \ - go build -trimpath -ldflags="-s -w" -o "${'$'}out" . + go build -buildvcs=false -trimpath -ldflags="-s -w" -o "${'$'}out" . """.trimIndent(), "bash", serverAssetFile.asFile.absolutePath @@ -233,9 +308,17 @@ tasks.matching { dependsOn("buildServerAsset") } -tasks.register("nameReleaseApks") { +// Lint reads the source asset/native folders directly. During assembleRelease +// the generators are in the same task graph, so make their order explicit +// without forcing public source-only lint runs to build private local artifacts. +tasks.matching { it.name.contains("Lint", ignoreCase = true) }.configureEach { + mustRunAfter("buildServerAsset", "buildNativeClient") +} + +val nameReleaseApks = tasks.register("nameReleaseApks") { group = "build" description = "Copies release APKs to filenames with app name and version." + dependsOn("packageRelease") val releaseDir = layout.buildDirectory.dir("outputs/apk/release") val namedReleaseDir = layout.buildDirectory.dir("outputs/apk/release/named") @@ -266,8 +349,28 @@ tasks.register("nameReleaseApks") { ) } +val auditReleaseApks = tasks.register("auditReleaseApks") { + group = "verification" + description = "Runs the configured local source and APK publication audit." + dependsOn(nameReleaseApks) + enabled = localReleaseAuditRequired + + val namedReleaseDir = layout.buildDirectory.dir("outputs/apk/release/named").get().asFile + val variants = listOf("universal", "arm64-v8a", "armeabi-v7a", "x86_64") + val releaseApks = variants.map { abi -> + namedReleaseDir.resolve("$releaseApkBaseName-v$appVersionName-$abi-release.apk") + } + inputs.files(releaseApks) + commandLine( + listOf( + localReleaseAudit.absolutePath, + rootDir.absolutePath, + ) + releaseApks.map(File::getAbsolutePath) + ) +} + tasks.matching { it.name == "assembleRelease" }.configureEach { - finalizedBy("nameReleaseApks") + finalizedBy(auditReleaseApks) } dependencies { @@ -281,6 +384,7 @@ dependencies { implementation("androidx.compose.material3:material3") implementation("androidx.compose.material:material-icons-extended") implementation("androidx.activity:activity-compose:1.9.3") + implementation("androidx.browser:browser:1.9.0") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7") implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7") implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7") diff --git a/app/src/debug/java/com/wdtt/plus/WDTTPreviews.kt b/app/src/debug/java/com/wdtt/plus/WDTTPreviews.kt index 6b7ab57..f8a045c 100644 --- a/app/src/debug/java/com/wdtt/plus/WDTTPreviews.kt +++ b/app/src/debug/java/com/wdtt/plus/WDTTPreviews.kt @@ -6,7 +6,9 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.wdtt.plus.ui.DeployTab @@ -62,8 +64,10 @@ private fun InfoTabPreview() { ) @Composable private fun TunnelTabPreview() { + val context = LocalContext.current + val settingsStore = remember { SettingsStore(context) } PreviewScreen { - SettingsTab() + SettingsTab(settingsStore = settingsStore) } } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d3a570b..cbd2ac8 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -28,7 +28,7 @@ android:name=".WdttApplication" android:allowBackup="false" android:icon="@mipmap/ic_launcher" - android:label="WDTT Plus" + android:label="${appLabel}" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.WDTTClient"> @@ -54,8 +54,10 @@ + + @@ -64,13 +66,33 @@ + + + + + + + + + + + + + + + + + diff --git a/app/src/main/assets/deploy.sh b/app/src/main/assets/deploy.sh index d6d3ebe..6366079 100755 --- a/app/src/main/assets/deploy.sh +++ b/app/src/main/assets/deploy.sh @@ -2,19 +2,24 @@ # ============================================================================== # WDTT Plus Server — Универсальный установщик для VPS # Поддержка: Debian 11+, Ubuntu 20.04+, CentOS/RHEL/Fedora/AlmaLinux/Rocky -# Версия: 3.3 | Дата: 2026-07-02 +# Версия: 3.4 | Дата: 2026-07-13 # NAT: MASQUERADE через iptables # WG: порт 56001 (не конфликтует с существующим WG на 51820) # DTLS: порт 56000 # ============================================================================== set -uo pipefail -readonly SCRIPT_VERSION="3.3" +readonly SCRIPT_VERSION="3.4" readonly LOG_FILE="/var/log/wdtt-install.log" readonly WG_PORT="${WDTT_WG_PORT:-56001}" readonly DTLS_PORT="${WDTT_DTLS_PORT:-56000}" readonly SSH_PORT="${WDTT_SSH_PORT:-22}" readonly MAX_PASSWORDS="${WDTT_MAX_PASSWORDS:-50}" +readonly MAX_WORKERS_PER_ACCESS="${WDTT_MAX_WORKERS_PER_ACCESS:-0}" +readonly MAX_HANDSHAKES="${WDTT_MAX_HANDSHAKES:-32}" +readonly HANDSHAKE_RATE="${WDTT_HANDSHAKE_RATE:-24}" +readonly MAX_CLIENT_MBPS="${WDTT_MAX_CLIENT_MBPS:-0}" +readonly WG_BACKEND="${WDTT_WG_BACKEND:-auto}" readonly WDTT_ARGS="${WDTT_ARGS:-}" readonly WDTT_PRESERVE_DATA="${WDTT_PRESERVE_DATA:-0}" readonly WDTT_IFACE="wdtt0" @@ -34,6 +39,33 @@ validate_port() { fi } +validate_runtime_limits() { + for item in \ + "WDTT_MAX_PASSWORDS:$MAX_PASSWORDS" \ + "WDTT_MAX_HANDSHAKES:$MAX_HANDSHAKES"; do + local name="${item%%:*}" value="${item#*:}" + case "$value" in + ''|*[!0-9]*) die "$name должен быть положительным целым числом" ;; + esac + [ "$value" -ge 1 ] || die "$name должен быть не меньше 1" + done + case "$MAX_WORKERS_PER_ACCESS" in + ''|*[!0-9]*) die "WDTT_MAX_WORKERS_PER_ACCESS должен быть целым числом" ;; + esac + for item in \ + "WDTT_HANDSHAKE_RATE:$HANDSHAKE_RATE" \ + "WDTT_MAX_CLIENT_MBPS:$MAX_CLIENT_MBPS"; do + local name="${item%%:*}" value="${item#*:}" + case "$value" in + ''|*[!0-9.]*) die "$name должен быть неотрицательным числом" ;; + esac + done + case "$WG_BACKEND" in + auto|kernel|userspace) ;; + *) die "WDTT_WG_BACKEND должен быть auto, kernel или userspace" ;; + esac +} + # ─── Цвета ─────────────────────────────────────────────────────────────────── C_GREEN=''; C_YELLOW=''; C_RED='' C_CYAN=''; C_BOLD=''; C_NC='' @@ -115,14 +147,20 @@ install_prerequisites() { apt) pkg_install ca-certificates iproute2 iptables nftables procps psmisc || \ log_warn "Часть apt-пакетов не установилась, продолжаю с доступными утилитами" + pkg_install wireguard-tools || \ + log_warn "wireguard-tools не установлен; будет использован userspace WireGuard" ;; dnf|yum) pkg_install ca-certificates iproute iptables nftables procps-ng psmisc || \ log_warn "Часть rpm-пакетов не установилась, продолжаю с доступными утилитами" + pkg_install wireguard-tools || \ + log_warn "wireguard-tools не установлен; будет использован userspace WireGuard" ;; pacman) pkg_install ca-certificates iproute2 iptables nftables procps-ng psmisc || \ log_warn "Часть pacman-пакетов не установилась, продолжаю с доступными утилитами" + pkg_install wireguard-tools || \ + log_warn "wireguard-tools не установлен; будет использован userspace WireGuard" ;; esac } @@ -378,8 +416,22 @@ setup_sysctl() { mkdir -p /etc/sysctl.d cat > /etc/sysctl.d/99-wdtt.conf << 'SYSEOF' net.ipv4.ip_forward = 1 +net.core.default_qdisc = fq +net.core.rmem_max = 25165824 +net.core.wmem_max = 25165824 +net.core.rmem_default = 4194304 +net.core.wmem_default = 4194304 +net.core.netdev_max_backlog = 16384 +net.ipv4.udp_rmem_min = 262144 +net.ipv4.udp_wmem_min = 262144 +net.ipv4.tcp_rmem = 4096 87380 25165824 +net.ipv4.tcp_wmem = 4096 65536 25165824 SYSEOF + if sysctl -n net.ipv4.tcp_available_congestion_control 2>/dev/null | grep -qw bbr; then + echo 'net.ipv4.tcp_congestion_control = bbr' >> /etc/sysctl.d/99-wdtt.conf + fi + sysctl -p /etc/sysctl.d/99-wdtt.conf >/dev/null 2>&1 || true echo "✓ Sysctl настроен" @@ -461,7 +513,7 @@ Wants=network-online.target Type=simple ExecStartPre=-/usr/bin/env bash -c "ip link show ${WDTT_IFACE} >/dev/null 2>&1 && ip link del ${WDTT_IFACE} 2>/dev/null || true" ExecStartPre=-/usr/bin/env bash -c "if command -v iptables >/dev/null 2>&1; then iptables -C INPUT -p udp --dport ${DTLS_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${DTLS_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; iptables -C INPUT -p udp --dport ${WG_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${WG_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; iptables -C INPUT -p tcp --dport ${SSH_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport ${SSH_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; fi" -ExecStart=/usr/local/bin/wdtt-server -listen 0.0.0.0:${DTLS_PORT} -wg-port ${WG_PORT} -config-dir ${WDTT_CONFIG_DIR} -max-passwords ${MAX_PASSWORDS} ${WDTT_ARGS} +ExecStart=/usr/local/bin/wdtt-server -listen 0.0.0.0:${DTLS_PORT} -wg-port ${WG_PORT} -config-dir ${WDTT_CONFIG_DIR} -max-passwords ${MAX_PASSWORDS} -max-workers-per-access ${MAX_WORKERS_PER_ACCESS} -max-handshakes ${MAX_HANDSHAKES} -handshake-rate ${HANDSHAKE_RATE} -max-client-mbps ${MAX_CLIENT_MBPS} -wg-backend ${WG_BACKEND} ${WDTT_ARGS} Restart=always RestartSec=5 LimitNOFILE=65535 @@ -572,6 +624,7 @@ main() { validate_port "WDTT_DTLS_PORT" "$DTLS_PORT" validate_port "WDTT_WG_PORT" "$WG_PORT" validate_port "WDTT_SSH_PORT" "$SSH_PORT" + validate_runtime_limits mkdir -p "$(dirname "$LOG_FILE")" echo "=== WDTT Plus Installer v${SCRIPT_VERSION} — $(date) ===" >> "$LOG_FILE" diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt new file mode 100644 index 0000000..753f9ea --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt @@ -0,0 +1,216 @@ +package com.wdtt.plus + +enum class AccessLifecycleSeverity { + NORMAL, + WARNING, + ERROR; + + companion object { + fun parse(value: String, allowConnect: Boolean): AccessLifecycleSeverity = + when (value.trim().lowercase()) { + "normal", "info" -> NORMAL + "warning", "warn" -> WARNING + "error", "danger" -> ERROR + else -> if (allowConnect) NORMAL else ERROR + } + } +} + +/** + * Opaque provider-neutral capability attached to a remotely managed profile. + * + * Android does not interpret the provider policy behind this capability. It + * submits the protected key to the exact HTTPS service URL, then applies only + * the generic connection decision and optional document/action returned by it. + */ +data class RemoteAccessCapability( + val available: Boolean, + val key: String = "", + val url: String = "", + val binding: String = "", + val initialStatus: AccessLifecycleStatus? = null, + val cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable, + val exchange: RemoteProfileExchange = RemoteProfileExchange.Unavailable, +) { + companion object { + val Unavailable = RemoteAccessCapability(available = false) + } +} + +/** + * Provider-neutral exchange attached to one remotely managed profile. + * + * Tokens are opaque and device-bound. Android can submit the profile's normal + * auxiliary values or invoke the remotely presented action, but it does not + * know why the provider stores them or how the returned update is produced. + */ +data class RemoteProfileExchange( + val submitAvailable: Boolean, + val submitToken: String = "", + val actionAvailable: Boolean = false, + val actionToken: String = "", + val label: String = "", + val message: String = "", +) { + companion object { + val Unavailable = RemoteProfileExchange(submitAvailable = false) + } +} + +/** + * A provider-neutral action cached with a remotely managed profile. + * + * Android treats [payload] as an opaque clipboard value and opens [target] + * exactly as supplied. Presentation is also remote-provided, so the APK does + * not know which external channel fulfills the action. + */ +data class CachedRemoteAction( + val available: Boolean, + val payload: String = "", + val target: RemoteLaunchTarget = RemoteLaunchTarget(primaryUrl = ""), + val title: String = "", + val message: String = "", + val label: String = "", + val clipboardLabel: String = "", + val copiedMessage: String = "", + val failedMessage: String = "", + val helpTitle: String = "", + val helpIntro: String = "", + val helpSteps: String = "", +) { + companion object { + val Unavailable = CachedRemoteAction(available = false) + } +} + +data class AccessProfileUpdate( + val revision: Long, + val link: RemoteDocumentLink, +) + +data class AccessLifecycleStatus( + val allowConnect: Boolean, + val actionAvailable: Boolean, + val actionLabel: String = "", + val actionMessage: String = "", + val title: String = "", + val message: String = "", + val detailLabel: String = "", + val detailValue: String = "", + val actionIcon: String = "", + val severity: AccessLifecycleSeverity = AccessLifecycleSeverity.NORMAL, + val checkedAtMillis: Long = System.currentTimeMillis(), + val profileRevision: Long = 0, + val profileUpdate: AccessProfileUpdate? = null, + val cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable, + val exchange: RemoteProfileExchange? = null, +) + +data class StoredAccessLifecycle( + val managed: Boolean, + val capability: RemoteAccessCapability, + val status: AccessLifecycleStatus?, + val appliedProfileRevision: Long, + val lastAttemptAtMillis: Long, +) + +data class AccessLifecycleUiState( + val managed: Boolean, + val allowConnect: Boolean, + val actionAvailable: Boolean, + val actionLabel: String, + val actionMessage: String, + val title: String, + val message: String, + val detailLabel: String = "", + val detailValue: String = "", + val actionIcon: String = "", + val severity: AccessLifecycleSeverity, + val checkedAtMillis: Long, +) { + companion object { + val Unmanaged = AccessLifecycleUiState( + managed = false, + allowConnect = true, + actionAvailable = false, + actionLabel = "", + actionMessage = "", + title = "", + message = "", + detailLabel = "", + detailValue = "", + actionIcon = "", + severity = AccessLifecycleSeverity.NORMAL, + checkedAtMillis = 0, + ) + } +} + +internal fun accessLifecycleDismissalSignature( + lifecycle: AccessLifecycleUiState, +): String { + if (!lifecycle.managed) return "" + return listOf( + lifecycle.allowConnect, + lifecycle.actionAvailable, + lifecycle.title, + lifecycle.message, + lifecycle.detailLabel, + lifecycle.detailValue, + ).joinToString("|") +} + +internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState { + val current = status + return AccessLifecycleUiState( + managed = managed, + allowConnect = current?.allowConnect ?: true, + actionAvailable = current?.actionAvailable == true, + actionLabel = current?.actionLabel.orEmpty(), + actionMessage = current?.actionMessage.orEmpty(), + title = current?.title.orEmpty(), + message = current?.message.orEmpty(), + detailLabel = current?.detailLabel.orEmpty(), + detailValue = current?.detailValue.orEmpty(), + actionIcon = current?.actionIcon.orEmpty(), + severity = current?.severity ?: AccessLifecycleSeverity.NORMAL, + checkedAtMillis = current?.checkedAtMillis ?: 0, + ) +} + +internal sealed interface AccessStartDecision { + data object Allowed : AccessStartDecision + data class Denied(val status: AccessLifecycleStatus) : AccessStartDecision +} + +internal fun accessStartDecision( + lifecycle: StoredAccessLifecycle, +): AccessStartDecision { + val status = lifecycle.status + val pendingProfileUpdate = status?.profileUpdate + ?.revision + ?.let { it > lifecycle.appliedProfileRevision } == true + return if ( + !lifecycle.capability.available || + status == null || + (status.allowConnect && !pendingProfileUpdate) + ) { + AccessStartDecision.Allowed + } else { + AccessStartDecision.Denied( + if (pendingProfileUpdate) { + status.copy( + allowConnect = false, + title = "Нужно обновить профиль", + message = "Не удалось применить новые параметры. Повторите подключение.", + severity = AccessLifecycleSeverity.WARNING, + ) + } else { + status + } + ) + } +} + +internal fun AccessLifecycleUiState.fallbackTitle(): String = + if (allowConnect) "Профиль доступен" else "Профиль временно недоступен" diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt new file mode 100644 index 0000000..0f11b62 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt @@ -0,0 +1,567 @@ +package com.wdtt.plus + +import android.content.Context +import android.os.Build +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.util.TimeZone + +sealed interface AccessLifecycleRefreshResult { + data object Unmanaged : AccessLifecycleRefreshResult + data class Success(val status: AccessLifecycleStatus) : AccessLifecycleRefreshResult + data class Cached(val status: AccessLifecycleStatus?) : AccessLifecycleRefreshResult + data class Throttled( + val status: AccessLifecycleStatus?, + val retryAfterMillis: Long, + ) : AccessLifecycleRefreshResult + data class Failed(val message: String, val cached: AccessLifecycleStatus?) : + AccessLifecycleRefreshResult +} + +object AccessLifecycleCoordinator { + private const val STATUS_CACHE_TTL_MS = 10 * 60 * 1000L + private const val MIN_ATTEMPT_INTERVAL_MS = 10_000L + private val profileLocks = Array(3) { Mutex() } + private val _refreshingProfiles = MutableStateFlow>(emptySet()) + val refreshingProfiles: StateFlow> = _refreshingProfiles.asStateFlow() + private val pendingExternalRefresh = mutableSetOf() + + suspend fun refreshProfile( + context: Context, + profileIndex: Int, + force: Boolean = false, + ): AccessLifecycleRefreshResult { + val appContext = context.applicationContext + val profile = profileIndex.coerceIn(0, 2) + val store = SettingsStore(appContext) + val before = store.accessLifecycleForProfile(profile) + if (!before.capability.available) return AccessLifecycleRefreshResult.Unmanaged + val now = System.currentTimeMillis() + if ( + !force && + before.status != null && + now - before.status.checkedAtMillis in 0 until STATUS_CACHE_TTL_MS + ) { + return AccessLifecycleRefreshResult.Cached(before.status) + } + val attemptAge = now - before.lastAttemptAtMillis + if (attemptAge in 0 until MIN_ATTEMPT_INTERVAL_MS) { + return AccessLifecycleRefreshResult.Throttled( + status = before.status, + retryAfterMillis = MIN_ATTEMPT_INTERVAL_MS - attemptAge, + ) + } + return profileLocks[profile].withLock { + val current = store.accessLifecycleForProfile(profile) + val currentNow = System.currentTimeMillis() + if (!current.capability.available) return@withLock AccessLifecycleRefreshResult.Unmanaged + syncPendingProfileValues(store, profile, current.capability) + if ( + !force && + current.status != null && + currentNow - current.status.checkedAtMillis in 0 until STATUS_CACHE_TTL_MS + ) { + return@withLock AccessLifecycleRefreshResult.Cached(current.status) + } + val currentAttemptAge = currentNow - current.lastAttemptAtMillis + if (currentAttemptAge in 0 until MIN_ATTEMPT_INTERVAL_MS) { + return@withLock AccessLifecycleRefreshResult.Throttled( + status = current.status, + retryAfterMillis = MIN_ATTEMPT_INTERVAL_MS - currentAttemptAge, + ) + } + store.saveAccessLifecycleAttempt(profile, currentNow) + setRefreshing(profile, true) + try { + val received = AccessLifecycleGateway.fetch( + capability = current.capability, + device = store.getOrCreateConnectDeviceId(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + timezone = TimeZone.getDefault().id, + profileRevision = current.appliedProfileRevision, + ) + val effectiveCapability = current.capability.copy( + exchange = received.exchange ?: current.capability.exchange, + ) + if (effectiveCapability != current.capability) { + store.saveRemoteAccessCapability(effectiveCapability, profile) + } + val effectiveCurrent = current.copy(capability = effectiveCapability) + // Статус доступа самодостаточен: сохраняем его даже если отдельное + // обновление параметров профиля временно не удалось скачать или применить. + if ( + !store.saveAccessLifecycleStatus( + profile, + received, + expectedCapability = effectiveCapability, + ) + ) { + return@withLock AccessLifecycleRefreshResult.Unmanaged + } + val profileUpdated = applyProfileUpdateIfNeeded( + appContext = appContext, + store = store, + profile = profile, + current = effectiveCurrent, + status = received, + ) + // Новая capability может очистить прежний статус при ротации ключа. + if (profileUpdated) { + store.saveAccessLifecycleStatus( + profile, + received, + expectedCapability = effectiveCapability, + ) + } + // Состояние управляемого доступа показывается своей профильной карточкой. + // Общая ошибка подключения не должна дублировать её и переноситься на + // другой, в том числе ручной, профиль. + TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS) + if ( + current.status?.allowConnect != received.allowConnect || + current.status?.title != received.title + ) { + TunnelManager.noteAccessLifecycleEvent( + key = "profile_${profile}_decision", + message = received.title.ifBlank { "Состояние профиля обновлено" }, + warning = received.severity != AccessLifecycleSeverity.NORMAL, + ) + } + updateExternalSurfaces(appContext) + AccessLifecycleRefreshResult.Success(received) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: AccessLifecycleRequestException) { + if (!error.kind.authoritative) { + return@withLock accessRefreshFailure(profile, current, error) + } + val denied = authoritativeAccessDenialStatus( + failure = error, + cached = current.status, + ) + if ( + !store.saveAccessLifecycleStatus( + profile, + denied, + expectedCapability = current.capability, + ) + ) { + return@withLock AccessLifecycleRefreshResult.Unmanaged + } + TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS) + if ( + current.status?.allowConnect != denied.allowConnect || + current.status?.title != denied.title + ) { + TunnelManager.noteAccessLifecycleEvent( + key = "profile_${profile}_${error.code}", + message = denied.title, + warning = true, + ) + } + updateExternalSurfaces(appContext) + AccessLifecycleRefreshResult.Success(denied) + } catch (error: Exception) { + accessRefreshFailure(profile, current, error) + } finally { + setRefreshing(profile, false) + } + } + } + + private fun accessRefreshFailure( + profile: Int, + current: StoredAccessLifecycle, + error: Exception, + ): AccessLifecycleRefreshResult.Failed { + TunnelManager.noteAccessLifecycleEvent( + key = "profile_${profile}_check_failed", + message = error.message ?: "Не удалось обновить сведения о доступе", + warning = true, + ) + return AccessLifecycleRefreshResult.Failed( + message = error.message ?: "Не удалось проверить профиль.", + cached = current.status, + ) + } + + internal suspend fun prepareStart( + context: Context, + profileIndex: Int, + ): AccessStartDecision { + val profile = profileIndex.coerceIn(0, 2) + val store = SettingsStore(context.applicationContext) + val current = store.accessLifecycleForProfile(profile) + if (!current.capability.available) return AccessStartDecision.Allowed + val now = System.currentTimeMillis() + val cachedDecision = accessStartDecision(current) + val fresh = current.status?.checkedAtMillis?.let { + now - it in 0 until STATUS_CACHE_TTL_MS + } == true + if (fresh && cachedDecision == AccessStartDecision.Allowed) { + return AccessStartDecision.Allowed + } + + return when (val refreshed = refreshProfile(context, profile, force = true)) { + is AccessLifecycleRefreshResult.Success -> + if (refreshed.status.allowConnect) { + AccessStartDecision.Allowed + } else { + AccessStartDecision.Denied(refreshed.status) + } + is AccessLifecycleRefreshResult.Cached -> { + accessStartDecision(store.accessLifecycleForProfile(profile)) + } + is AccessLifecycleRefreshResult.Throttled -> { + accessStartDecision(store.accessLifecycleForProfile(profile)) + } + is AccessLifecycleRefreshResult.Failed -> + accessStartDecision(store.accessLifecycleForProfile(profile)) + AccessLifecycleRefreshResult.Unmanaged -> AccessStartDecision.Allowed + } + } + + suspend fun beginAction( + context: Context, + profileIndex: Int, + ): RemoteLaunchTarget { + val profile = profileIndex.coerceIn(0, 2) + val store = SettingsStore(context.applicationContext) + val current = store.accessLifecycleForProfile(profile) + require(current.capability.available && current.status?.actionAvailable == true) { + current.status?.actionMessage?.ifBlank { + "Действие сейчас недоступно." + } ?: "Действие сейчас недоступно." + } + val target = AccessLifecycleGateway.begin( + capability = current.capability, + device = store.getOrCreateConnectDeviceId(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + timezone = TimeZone.getDefault().id, + profileRevision = current.appliedProfileRevision, + ) + store.markAccessLifecycleActionLaunched(profile) + synchronized(pendingExternalRefresh) { + pendingExternalRefresh += profile + } + return target + } + + suspend fun noteServerDenied(context: Context, profileIndex: Int) { + val appContext = context.applicationContext + val profile = profileIndex.coerceIn(0, 2) + val store = SettingsStore(appContext) + store.markAccessLifecycleDenied(profile) + updateExternalSurfaces(appContext) + refreshProfile(appContext, profile, force = true) + } + + suspend fun refreshAllIfStale(context: Context) { + val store = SettingsStore(context.applicationContext) + store.accessLifecycleProfiles().forEach { profile -> + refreshProfile(context, profile, force = false) + } + } + + suspend fun refreshAllOnForeground( + context: Context, + alreadyScheduledProfiles: Set = emptySet(), + ) { + val store = SettingsStore(context.applicationContext) + accessProfilesForForegroundRefresh( + managedProfiles = store.accessLifecycleProfiles(), + alreadyScheduledProfiles = alreadyScheduledProfiles, + ).forEach { profile -> + refreshAfterAttemptWindow(context, profile) + } + } + + suspend fun refreshAfterSuccessfulConnect(context: Context, profileIndex: Int) { + refreshAfterAttemptWindow(context, profileIndex) + } + + suspend fun refreshAfterExternalAction( + context: Context, + profileIndex: Int, + ): AccessLifecycleRefreshResult = + refreshAfterAttemptWindow(context, profileIndex) + + private suspend fun refreshAfterAttemptWindow( + context: Context, + profileIndex: Int, + ): AccessLifecycleRefreshResult { + val first = refreshProfile( + context.applicationContext, + profileIndex, + force = true, + ) + if (first !is AccessLifecycleRefreshResult.Throttled) return first + delay(first.retryAfterMillis) + return refreshProfile( + context.applicationContext, + profileIndex, + force = true, + ) + } + + fun takePendingExternalRefreshProfiles(): Set = synchronized(pendingExternalRefresh) { + pendingExternalRefresh.toSet().also { pendingExternalRefresh.clear() } + } + + suspend fun syncProfileValues( + context: Context, + profileIndex: Int, + values: List, + ): Boolean { + val profile = profileIndex.coerceIn(0, 2) + val cleaned = values + .map(VkJoinLink::extractHash) + .filter(VkJoinLink::isValidHash) + .distinct() + .take(4) + val store = SettingsStore(context.applicationContext) + val current = store.accessLifecycleForProfile(profile) + val exchange = current.capability.exchange + if ( + !current.capability.available || + !exchange.submitAvailable || + exchange.submitToken.isBlank() + ) { + return false + } + store.markProfileValuesSyncPending(profile) + val updatedExchange = AccessLifecycleGateway.submitProfileValues( + capability = current.capability, + token = exchange.submitToken, + device = store.getOrCreateConnectDeviceId(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + timezone = TimeZone.getDefault().id, + values = cleaned, + ) + store.saveRemoteAccessCapability( + current.capability.copy(exchange = updatedExchange), + profile, + ) + store.clearProfileValuesSyncPending(profile) + return true + } + + suspend fun restoreProfileValues( + context: Context, + profileIndex: Int, + expectedCapability: RemoteAccessCapability, + ): WdttDeepLinkApplyResult { + val appContext = context.applicationContext + val profile = profileIndex.coerceIn(0, 2) + val store = SettingsStore(appContext) + return profileLocks[profile].withLock { + val current = store.accessLifecycleForProfile(profile) + require( + current.capability.available && + expectedCapability.available && + current.capability.key == expectedCapability.key && + current.capability.url == expectedCapability.url && + current.capability.binding == expectedCapability.binding + ) { + "Сохранённые данные относятся к другому профилю." + } + val exchange = current.capability.exchange + require( + exchange.actionAvailable && exchange.actionToken.isNotBlank() + ) { + "Действие для этого профиля больше недоступно." + } + val link = AccessLifecycleGateway.invokeProfileAction( + capability = current.capability, + token = exchange.actionToken, + device = store.getOrCreateConnectDeviceId(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + timezone = TimeZone.getDefault().id, + profileRevision = current.appliedProfileRevision, + ) + val delivery = RemoteDocumentGateway.receive( + link = link, + device = store.getOrCreateConnectDeviceId(), + label = androidDeviceLabel(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + localBindings = store.remoteDocumentBindings(), + ) + require(delivery.kind == RemoteDocumentKind.UPDATE) { + "WDTT Plus вернул неподходящее обновление профиля." + } + require( + current.capability.binding.isNotBlank() && + delivery.binding == current.capability.binding + ) { + "Обновление относится к другому профилю." + } + val applied = store.applyRemoteDocumentDelivery( + plan = WdttDeepLinkApplyPlan( + link = delivery.document, + targetProfile = profile, + requiresConfirmation = false, + storeAsLink = false, + ), + delivery = delivery, + isBoundUpdate = true, + ) ?: throw IllegalStateException("Не удалось применить обновление профиля.") + store.clearProfileValuesSyncPending(profile) + requestTunnelProfileRuntimeUpdate(profile) + applied + } + } + + private suspend fun syncPendingProfileValues( + store: SettingsStore, + profile: Int, + capability: RemoteAccessCapability, + ) { + if (!store.profileValuesSyncPending(profile)) return + val exchange = capability.exchange + if (!exchange.submitAvailable || exchange.submitToken.isBlank()) return + val values = store.tunnelProfileSnapshot(profile).vkHashes + .split(",") + .map(VkJoinLink::extractHash) + .filter(VkJoinLink::isValidHash) + .distinct() + .take(4) + runCatching { + val updatedExchange = AccessLifecycleGateway.submitProfileValues( + capability = capability, + token = exchange.submitToken, + device = store.getOrCreateConnectDeviceId(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + timezone = TimeZone.getDefault().id, + values = values, + ) + store.saveRemoteAccessCapability( + capability.copy(exchange = updatedExchange), + profile, + ) + }.onSuccess { + store.clearProfileValuesSyncPending(profile) + } + } + + private suspend fun applyProfileUpdateIfNeeded( + appContext: Context, + store: SettingsStore, + profile: Int, + current: StoredAccessLifecycle, + status: AccessLifecycleStatus, + ): Boolean { + val update = status.profileUpdate ?: return false + if (update.revision <= current.appliedProfileRevision) return false + val delivery = RemoteDocumentGateway.receive( + link = update.link, + device = store.getOrCreateConnectDeviceId(), + label = androidDeviceLabel(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + localBindings = store.remoteDocumentBindings(), + ) + require(delivery.kind == RemoteDocumentKind.UPDATE) { + "WDTT Plus вернул неподходящее обновление профиля." + } + val binding = store.remoteAccessBindingForProfile(profile) + require(binding.isNotBlank() && delivery.binding == binding) { + "Обновление относится к другому профилю." + } + val applied = store.applyWdttDeepLink( + plan = WdttDeepLinkApplyPlan( + link = delivery.document, + targetProfile = profile, + requiresConfirmation = false, + storeAsLink = false, + ), + resetRemoteContinuation = false, + profileMaxWorkers = delivery.profileMaxWorkers, + remoteManaged = null, + preserveVkHashes = true, + ) + require(applied != null) { "Не удалось применить обновление профиля." } + if (delivery.access.available) { + store.saveRemoteAccessCapability(delivery.access, profile) + } + store.saveAppliedAccessProfileRevision(profile, update.revision) + requestTunnelProfileRuntimeUpdate(profile) + TunnelManager.noteAccessLifecycleEvent( + key = "profile_${profile}_updated", + message = "Параметры профиля обновлены", + warning = false, + ) + return true + } + + private fun androidDeviceLabel(): String { + val values = listOf(Build.MANUFACTURER, Build.MODEL) + .map(String::trim) + .filter(String::isNotBlank) + .distinctBy(String::lowercase) + return values.joinToString(" ").ifBlank { "Android-устройство" } + } + + private fun setRefreshing(profile: Int, refreshing: Boolean) { + _refreshingProfiles.value = _refreshingProfiles.value.toMutableSet().apply { + if (refreshing) add(profile) else remove(profile) + } + } + + private fun updateExternalSurfaces(context: Context) { + VpnWidgetProvider.updateAllWidgets(context) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + android.service.quicksettings.TileService.requestListeningState( + context, + android.content.ComponentName(context, QuickToggleTileService::class.java), + ) + } + } +} + +internal fun accessProfilesForForegroundRefresh( + managedProfiles: Collection, + alreadyScheduledProfiles: Set, +): List = managedProfiles + .filter { it in 0..2 && it !in alreadyScheduledProfiles } + .distinct() + .sorted() + +internal fun authoritativeAccessDenialStatus( + failure: AccessLifecycleRequestException, + cached: AccessLifecycleStatus?, + checkedAtMillis: Long = System.currentTimeMillis(), +): AccessLifecycleStatus { + require(failure.kind.authoritative) + val (title, fallbackMessage) = when (failure.kind) { + AccessLifecycleFailureKind.REJECTED -> + "Профиль недоступен" to + "Поставщик отклонил использование этого профиля." + AccessLifecycleFailureKind.UNBOUND -> + "Профиль отвязан" to + "Запросите новую ссылку на профиль у поставщика." + AccessLifecycleFailureKind.UNAVAILABLE -> + "Профиль больше недоступен" to + "Проверьте профиль и привязку устройства у поставщика." + AccessLifecycleFailureKind.TEMPORARY -> error("temporary failure is not authoritative") + } + return AccessLifecycleStatus( + allowConnect = false, + actionAvailable = false, + title = title, + message = failure.message?.takeIf { it.isNotBlank() } ?: fallbackMessage, + severity = AccessLifecycleSeverity.ERROR, + checkedAtMillis = checkedAtMillis, + profileRevision = cached?.profileRevision ?: 0, + ) +} diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt new file mode 100644 index 0000000..2953e1d --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt @@ -0,0 +1,384 @@ +package com.wdtt.plus + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URI +import java.net.URL + +enum class AccessLifecycleFailureKind { + REJECTED, + UNBOUND, + UNAVAILABLE, + TEMPORARY; + + val authoritative: Boolean + get() = this != TEMPORARY +} + +class AccessLifecycleRequestException( + val kind: AccessLifecycleFailureKind, + val code: String, + message: String, +) : IllegalStateException(message) + +object AccessLifecycleGateway { + private const val MAX_RESPONSE_CHARS = 32 * 1024 + + suspend fun fetch( + capability: RemoteAccessCapability, + device: String, + client: String, + system: String, + timezone: String, + profileRevision: Long, + ): AccessLifecycleStatus = request( + capability = capability, + device = device, + client = client, + system = system, + timezone = timezone, + profileRevision = profileRevision, + operation = "status", + ).let(::parseStatus) + + suspend fun begin( + capability: RemoteAccessCapability, + device: String, + client: String, + system: String, + timezone: String, + profileRevision: Long, + ): RemoteLaunchTarget = request( + capability = capability, + device = device, + client = client, + system = system, + timezone = timezone, + profileRevision = profileRevision, + operation = "continue", + ).let(::parseLaunchTarget) + + suspend fun submitProfileValues( + capability: RemoteAccessCapability, + token: String, + device: String, + client: String, + system: String, + timezone: String, + values: List, + ): RemoteProfileExchange = + parseExchangeResult( + request( + capability = capability, + device = device, + client = client, + system = system, + timezone = timezone, + profileRevision = 0, + action = token, + values = values, + ) + ) + + suspend fun invokeProfileAction( + capability: RemoteAccessCapability, + token: String, + device: String, + client: String, + system: String, + timezone: String, + profileRevision: Long, + ): RemoteDocumentLink = request( + capability = capability, + device = device, + client = client, + system = system, + timezone = timezone, + profileRevision = profileRevision, + action = token, + ).let(::parseActionDocument) + + private suspend fun request( + capability: RemoteAccessCapability, + device: String, + client: String, + system: String, + timezone: String, + profileRevision: Long, + operation: String = "", + action: String = "", + values: List = emptyList(), + ): String { + require(capability.available && opaqueValue(capability.key)) { + "Управление доступом недоступно для этого профиля." + } + require(safeServiceUrl(capability.url)) { + "Не удалось проверить доступ для этого профиля." + } + require(validDevice(device)) { "Не удалось определить текущее устройство." } + require( + ( + operation in setOf("status", "continue") && + action.isBlank() + ) || + ( + operation.isBlank() && + opaqueValue(action) + ) + ) + require(values.size <= 16) + return withContext(Dispatchers.IO) { + val payload = JSONObject() + .put("key", capability.key.trim()) + .put("device", device.trim()) + .put("client", client.trim().take(64)) + .put("system", system.trim().take(64)) + .put("timezone", timezone.trim().take(64)) + .put("profile_revision", profileRevision.coerceAtLeast(0)) + .put("values", org.json.JSONArray(values)) + .apply { + if (operation.isNotBlank()) put("operation", operation) + if (action.isNotBlank()) put("action", action) + } + .toString() + .toByteArray(Charsets.UTF_8) + var connection: HttpURLConnection? = null + try { + connection = URL(capability.url).openConnection() as HttpURLConnection + connection.requestMethod = "POST" + connection.instanceFollowRedirects = false + connection.connectTimeout = 7_000 + connection.readTimeout = 9_000 + connection.doOutput = true + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8") + connection.setRequestProperty("Accept", "application/json") + connection.outputStream.use { it.write(payload) } + val status = connection.responseCode + val body = readBody(connection, status) + if (status !in 200..299) { + throw parseHttpFailure( + status = status, + body = body, + operation = operation, + codeHint = connection.getHeaderField("X-WDTT-Access-Code").orEmpty(), + ) + } + body + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + if (error is IllegalStateException) throw error + throw IllegalStateException( + if (operation == "continue") { + "Не удалось открыть страницу. Проверьте интернет и повторите попытку." + } else if (action.isNotBlank()) { + "Не удалось обновить сохранённые данные профиля." + } else { + "Не удалось проверить профиль. Проверьте интернет." + } + ) + } finally { + connection?.disconnect() + } + } + } + + internal fun parseHttpFailure( + status: Int, + body: String, + operation: String, + codeHint: String = "", + ): AccessLifecycleRequestException { + val root = runCatching { JSONObject(body) }.getOrNull() + val detail = root?.opt("detail") + val structured = detail as? JSONObject + val code = structured?.optString("code").orEmpty() + .ifBlank { root?.optString("code").orEmpty() } + .ifBlank { codeHint } + .trim() + .lowercase() + val message = ( + structured?.optString("message") + ?: (detail as? String) + ?: "" + ).trim().take(300) + val kind = when { + status == 410 || code == "expired" -> AccessLifecycleFailureKind.REJECTED + code in setOf("unbound", "device_mismatch") -> AccessLifecycleFailureKind.UNBOUND + status in setOf(401, 403, 404) || + code in setOf("removed", "revoked", "not_found", "forbidden") -> + AccessLifecycleFailureKind.UNAVAILABLE + else -> AccessLifecycleFailureKind.TEMPORARY + } + val fallback = when { + operation == "continue" -> "Действие сейчас недоступно. Попробуйте позже." + kind == AccessLifecycleFailureKind.REJECTED -> + "Поставщик отклонил использование этого профиля." + kind == AccessLifecycleFailureKind.UNBOUND -> + "Профиль отвязан от этого устройства." + kind == AccessLifecycleFailureKind.UNAVAILABLE -> + "Профиль больше недоступен для этого устройства." + else -> "Не удалось проверить профиль." + } + return AccessLifecycleRequestException( + kind = kind, + code = code.ifBlank { "http_$status" }, + message = message.ifBlank { fallback }, + ) + } + + internal fun parseStatus(body: String): AccessLifecycleStatus { + val root = parseRoot(body) + require(root.optInt("version", 0) == 1) { + "Для проверки доступа нужна более новая версия WDTT Plus." + } + require(root.has("allow_connect")) { + "WDTT Plus вернул неполное решение по профилю." + } + val allowConnect = root.optBoolean("allow_connect", false) + val action = root.optJSONObject("action") + val actionAvailable = action?.optBoolean("available", false) == true + val actionLabel = action?.optString("label").orEmpty().trim().take(80) + val actionMessage = action?.optString("message").orEmpty().trim().take(240) + val actionIcon = action?.optString("icon").orEmpty().trim().take(32) + .takeIf { it == "update" } + .orEmpty() + val title = root.optString("title").trim().take(120) + val message = root.optString("message").trim().take(400) + val detail = root.optJSONObject("detail") + val detailLabel = detail?.optString("label").orEmpty().trim().take(80) + val detailValue = detail?.optString("value").orEmpty().trim().take(120) + val severity = AccessLifecycleSeverity.parse( + root.optString("severity"), + allowConnect, + ) + + val profile = root.optJSONObject("profile") + val revision = profile?.optLong("revision", 0)?.coerceAtLeast(0) ?: 0 + val update = if (profile?.optBoolean("update_available", false) == true) { + val link = RemoteDocumentGateway.extractLink(profile.optString("document")) + ?: throw IllegalStateException("WDTT Plus вернул повреждённое обновление профиля.") + require(revision > 0) { "WDTT Plus вернул неполное обновление профиля." } + AccessProfileUpdate(revision = revision, link = link) + } else { + null + } + val cachedAction = root.optJSONObject("cached_action") + ?.let(RemoteDocumentGateway::parseCachedAction) + ?: CachedRemoteAction.Unavailable + val exchange = root.optJSONObject("exchange") + ?.let(RemoteDocumentGateway::parseProfileExchange) + return AccessLifecycleStatus( + allowConnect = allowConnect, + actionAvailable = actionAvailable, + actionLabel = actionLabel, + actionMessage = actionMessage, + title = title, + message = message, + detailLabel = detailLabel, + detailValue = detailValue, + actionIcon = actionIcon, + severity = severity, + profileRevision = revision, + profileUpdate = update, + cachedAction = cachedAction, + exchange = exchange, + ) + } + + internal fun parseLaunchTarget(body: String): RemoteLaunchTarget { + val root = parseRoot(body) + val primary = root.optString("url").trim() + val fallback = root.optString("fallback").trim() + val handler = root.optString("handler").trim() + val alternateHandlers = root.optJSONArray("alternate_handlers")?.let { source -> + if (source.length() > 7) null else { + (0 until source.length()) + .map { index -> source.optString(index).trim() } + .takeIf { values -> + values.all { it.isNotBlank() && safePackageName(it) } && + values.distinct().size == values.size + } + } + } ?: if (root.has("alternate_handlers")) null else emptyList() + require(safeExternalUrl(primary)) { + "WDTT Plus вернул повреждённый адрес продолжения." + } + require(fallback.isBlank() || safeExternalUrl(fallback)) { + "WDTT Plus вернул повреждённый резервный адрес." + } + require(handler.isBlank() || safePackageName(handler)) { + "WDTT Plus вернул повреждённый обработчик продолжения." + } + require(alternateHandlers != null) { + "WDTT Plus вернул повреждённые резервные обработчики." + } + return RemoteLaunchTarget( + primaryUrl = primary, + fallbackUrl = fallback, + preferredHandler = handler, + alternateHandlers = alternateHandlers, + ) + } + + internal fun parseActionDocument(body: String): RemoteDocumentLink { + val root = parseRoot(body) + require(root.optInt("version", 0) == 1) { + "Для действия нужна более новая версия WDTT Plus." + } + return RemoteDocumentGateway.extractLink(root.optString("document")) + ?: throw IllegalStateException("WDTT Plus вернул повреждённое обновление профиля.") + } + + internal fun parseExchangeResult(body: String): RemoteProfileExchange { + val root = parseRoot(body) + require(root.optInt("version", 0) == 1) { + "WDTT Plus не подтвердил обновление данных профиля." + } + val source = root.optJSONObject("exchange") + ?: throw IllegalStateException("WDTT Plus вернул неполный ответ.") + return RemoteDocumentGateway.parseProfileExchange(source) + } + + private fun parseRoot(body: String): JSONObject { + require(body.length <= MAX_RESPONSE_CHARS) { "Ответ WDTT Plus слишком большой." } + return runCatching { JSONObject(body) } + .getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") } + } + + private fun safeServiceUrl(value: String): Boolean { + val uri = runCatching { URI(value) }.getOrNull() ?: return false + return uri.scheme.equals("https", ignoreCase = true) && + uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) && + uri.rawUserInfo.isNullOrBlank() && + uri.rawQuery.isNullOrBlank() && + uri.rawFragment.isNullOrBlank() && + (uri.port == -1 || uri.port == 443) + } + + private fun safeExternalUrl(value: String): Boolean { + val uri = runCatching { URI(value) }.getOrNull() ?: return false + return uri.scheme.equals("https", ignoreCase = true) && + !uri.host.isNullOrBlank() && + uri.rawUserInfo.isNullOrBlank() && + (uri.port == -1 || uri.port == 443) + } + + private fun safePackageName(value: String): Boolean = + value.length in 3..255 && + Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value) + + private fun opaqueValue(value: String): Boolean = + value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value) + + private fun validDevice(value: String): Boolean = + Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim()) + + private fun readBody(connection: HttpURLConnection, status: Int): String { + val stream = if (status in 200..299) connection.inputStream else connection.errorStream + return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty() + } +} diff --git a/app/src/main/java/com/wdtt/plus/AppUpdate.kt b/app/src/main/java/com/wdtt/plus/AppUpdate.kt index fb5cad0..d5fca99 100644 --- a/app/src/main/java/com/wdtt/plus/AppUpdate.kt +++ b/app/src/main/java/com/wdtt/plus/AppUpdate.kt @@ -2,6 +2,8 @@ package com.wdtt.plus import android.content.Context import android.content.Intent +import android.content.pm.PackageInfo +import android.content.pm.PackageManager import android.os.Build import android.util.Log import androidx.core.content.FileProvider @@ -33,8 +35,16 @@ private const val UPDATE_CHECK_TOTAL_TIMEOUT_MS = 25_000L private const val UPDATE_CHECK_REQUEST_TIMEOUT_MS = 6_000L private const val UPDATE_CHECK_MIN_REQUEST_TIMEOUT_MS = 1_000L private const val UPDATE_APK_HASH_TIMEOUT_MS = 4_000L +private const val MAX_UPDATE_APK_BYTES = 200L * 1024L * 1024L +private const val MAX_UPDATE_METADATA_BYTES = 1024 * 1024 +private const val MAX_UPDATE_WEB_BYTES = 512 * 1024 +private const val MAX_UPDATE_REDIRECTS = 5 private const val GITHUB_API_RATE_LIMIT_FALLBACK_MS = 30L * 60L * 1000L private val SIMPLE_VERSION_TAG_REGEX = Regex("^v?(\\d+)$", RegexOption.IGNORE_CASE) +private val TRUSTED_UPDATE_ASSET_HOSTS = setOf( + "objects.githubusercontent.com", + "release-assets.githubusercontent.com", +) @Volatile private var githubApiCooldownUntilMs = 0L @@ -185,7 +195,12 @@ suspend fun resolveAppUpdateCandidate( fun selectUpdateApkAsset(release: AppReleaseInfo): AppReleaseAsset? { val apkAssets = release.assets - .filter { it.name.endsWith(".apk", ignoreCase = true) && it.downloadUrl.isNotBlank() } + .filter { + it.name.endsWith(".apk", ignoreCase = true) && + it.sha256 != null && + it.sizeBytes in 1..MAX_UPDATE_APK_BYTES && + isTrustedUpdateDownloadUrl(it.downloadUrl, initialRequest = true) + } if (apkAssets.isEmpty()) return null Build.SUPPORTED_ABIS.orEmpty().forEach { abi -> @@ -201,6 +216,14 @@ suspend fun downloadUpdateApk( asset: AppReleaseAsset, onProgress: suspend (AppUpdateDownloadProgress) -> Unit = {} ): File = withContext(Dispatchers.IO) { + val expectedSha256 = asset.sha256 + ?: throw SecurityException("Для APK отсутствует обязательный SHA-256.") + require(asset.sizeBytes in 1..MAX_UPDATE_APK_BYTES) { + "Размер APK отсутствует или превышает безопасный лимит." + } + require(isTrustedUpdateDownloadUrl(asset.downloadUrl, initialRequest = true)) { + "Адрес APK не принадлежит официальному выпуску WDTT Plus." + } val appContext = context.applicationContext val updatesDir = File(appContext.cacheDir, "updates").apply { mkdirs() } updatesDir.listFiles()?.forEach { file -> @@ -217,28 +240,58 @@ suspend fun downloadUpdateApk( } try { - conn = URL(asset.downloadUrl).openConnection() as HttpURLConnection - applyNoCacheHeaders(conn) - conn.instanceFollowRedirects = true - conn.requestMethod = "GET" - conn.setRequestProperty("Accept", "application/vnd.android.package-archive,application/octet-stream,*/*") - conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}") - conn.connectTimeout = 15_000 - conn.readTimeout = 30_000 - - val responseCode = conn.responseCode + var currentUrl = URL(asset.downloadUrl) + var responseCode = 0 + for (redirect in 0..MAX_UPDATE_REDIRECTS) { + val currentConnection = currentUrl.openConnection() as HttpURLConnection + conn = currentConnection + applyNoCacheHeaders(currentConnection) + currentConnection.instanceFollowRedirects = false + currentConnection.requestMethod = "GET" + currentConnection.setRequestProperty( + "Accept", + "application/vnd.android.package-archive,application/octet-stream", + ) + currentConnection.setRequestProperty( + "User-Agent", + "WDTTAndroid/${BuildConfig.VERSION_NAME}", + ) + currentConnection.connectTimeout = 15_000 + currentConnection.readTimeout = 30_000 + responseCode = currentConnection.responseCode + if (responseCode !in 300..399) break + val location = currentConnection.getHeaderField("Location") + ?.takeIf { it.isNotBlank() } + ?: throw IOException("GitHub вернул перенаправление без адреса.") + if (redirect >= MAX_UPDATE_REDIRECTS) { + throw IOException("GitHub вернул слишком много перенаправлений.") + } + val nextUrl = URL(currentUrl, location) + require(isTrustedUpdateDownloadUrl(nextUrl.toString(), initialRequest = false)) { + "GitHub перенаправил загрузку на недоверенный адрес." + } + currentConnection.disconnect() + conn = null + currentUrl = nextUrl + } + val activeConnection = conn ?: throw IOException("Не удалось открыть загрузку APK.") if (responseCode !in 200..299) { throw IOException("GitHub вернул HTTP $responseCode при скачивании APK") } - val total = asset.sizeBytes.takeIf { it > 0L } - ?: conn.contentLengthLong.takeIf { it > 0L } - ?: 0L + val responseLength = activeConnection.contentLengthLong + if (responseLength > MAX_UPDATE_APK_BYTES) { + throw IOException("APK превышает безопасный лимит размера.") + } + if (responseLength > 0L && responseLength != asset.sizeBytes) { + throw IOException("Размер APK не совпал с данными выпуска.") + } + val total = asset.sizeBytes var downloaded = 0L var lastEmitAt = 0L emit(0L, total) - conn.inputStream.use { input -> + activeConnection.inputStream.use { input -> outputFile.outputStream().use { output -> val buffer = ByteArray(DEFAULT_BUFFER_SIZE) while (true) { @@ -246,6 +299,9 @@ suspend fun downloadUpdateApk( if (read < 0) break output.write(buffer, 0, read) downloaded += read + if (downloaded > MAX_UPDATE_APK_BYTES || downloaded > asset.sizeBytes) { + throw IOException("APK превышает заявленный размер.") + } val now = System.currentTimeMillis() if (now - lastEmitAt >= 250L || downloaded == total) { lastEmitAt = now @@ -260,13 +316,12 @@ suspend fun downloadUpdateApk( throw IOException("Размер APK не совпал с GitHub asset") } - asset.sha256?.let { expected -> - val actual = outputFile.sha256Hex() - if (!actual.equals(expected, ignoreCase = true)) { - outputFile.delete() - throw SecurityException("SHA-256 скачанного APK не совпал с GitHub digest") - } + val actual = outputFile.sha256Hex() + if (!actual.equals(expectedSha256, ignoreCase = true)) { + outputFile.delete() + throw SecurityException("SHA-256 скачанного APK не совпал с GitHub digest") } + validateUpdatePackage(appContext, outputFile) emit(outputFile.length(), total.takeIf { it > 0L } ?: outputFile.length()) outputFile @@ -285,6 +340,7 @@ fun canRequestApkInstall(context: Context): Boolean { fun installUpdateApk(context: Context, apkFile: File) { val appContext = context.applicationContext + validateUpdatePackage(appContext, apkFile) val uri = FileProvider.getUriForFile(appContext, "${appContext.packageName}.files", apkFile) val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, "application/vnd.android.package-archive") @@ -294,6 +350,90 @@ fun installUpdateApk(context: Context, apkFile: File) { appContext.startActivity(intent) } +internal fun isTrustedUpdateDownloadUrl( + value: String, + initialRequest: Boolean, +): Boolean { + val uri = runCatching { java.net.URI(value) }.getOrNull() ?: return false + val host = uri.host?.lowercase(Locale.US)?.trimEnd('.') ?: return false + if ( + !uri.scheme.equals("https", ignoreCase = true) || + !uri.rawUserInfo.isNullOrBlank() || + (uri.port != -1 && uri.port != 443) || + !uri.rawFragment.isNullOrBlank() + ) { + return false + } + if (initialRequest) { + return host == "github.com" && + uri.path.orEmpty().startsWith( + "/Ivan4537/WDTT-Plus/releases/download/", + ignoreCase = true, + ) + } + return host in TRUSTED_UPDATE_ASSET_HOSTS || + host.endsWith(".release-assets.githubusercontent.com") +} + +private fun validateUpdatePackage(context: Context, apkFile: File) { + require(apkFile.isFile && apkFile.length() in 1..MAX_UPDATE_APK_BYTES) { + "Файл обновления отсутствует или имеет недопустимый размер." + } + val packageManager = context.packageManager + val archive = packageManager.updateArchiveInfo(apkFile) + ?: throw SecurityException("Не удалось проверить пакет обновления.") + val installed = packageManager.installedUpdateTargetInfo(context.packageName) + if (archive.packageName != context.packageName) { + throw SecurityException("APK предназначен для другого приложения.") + } + val archiveSigners = archive.currentSignerDigests() + val installedSigners = installed.currentSignerDigests() + if ( + archiveSigners.isEmpty() || + installedSigners.isEmpty() || + archiveSigners != installedSigners + ) { + throw SecurityException("Подпись APK не совпадает с установленным WDTT Plus.") + } +} + +@Suppress("DEPRECATION") +private fun PackageManager.updateArchiveInfo(apkFile: File): PackageInfo? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + getPackageArchiveInfo( + apkFile.absolutePath, + PackageManager.PackageInfoFlags.of( + PackageManager.GET_SIGNING_CERTIFICATES.toLong(), + ), + ) + } else { + getPackageArchiveInfo(apkFile.absolutePath, PackageManager.GET_SIGNING_CERTIFICATES) + } +} + +@Suppress("DEPRECATION") +private fun PackageManager.installedUpdateTargetInfo(packageName: String): PackageInfo { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + getPackageInfo( + packageName, + PackageManager.PackageInfoFlags.of( + PackageManager.GET_SIGNING_CERTIFICATES.toLong(), + ), + ) + } else { + getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES) + } +} + +private fun PackageInfo.currentSignerDigests(): Set { + val signers = signingInfo?.apkContentsSigners.orEmpty() + return signers.mapTo(linkedSetOf()) { signature -> + MessageDigest.getInstance("SHA-256") + .digest(signature.toByteArray()) + .joinToString("") { "%02x".format(it) } + } +} + fun isNewerVersion(local: String, remote: String): Boolean { val localParts = versionParts(local) val remoteParts = versionParts(remote) @@ -442,7 +582,9 @@ private fun fetchReleaseFromLatestWebRedirect(budget: UpdateCheckBudget): AppRel } if (responseCode in 200..299) { - val response = conn.inputStream.bufferedReader().use { it.readText() } + val response = conn.inputStream.use { + it.readUtf8TextLimited(MAX_UPDATE_WEB_BYTES) + } val versionTag = Regex("/releases/tag/([^\"?#<]+)").find(response)?.groupValues?.getOrNull(1) if (!versionTag.isNullOrBlank()) { return AppReleaseInfo(versionTag, "$GITHUB_RELEASE_TAG_URL_PREFIX$versionTag", RemoteVersionSource.Release) @@ -494,7 +636,9 @@ private fun fetchHttpText( val responseCode = conn.responseCode val stream = if (responseCode in 200..299) conn.inputStream else conn.errorStream - val response = stream?.bufferedReader()?.use { it.readText() }.orEmpty() + val response = stream?.use { + it.readUtf8TextLimited(MAX_UPDATE_METADATA_BYTES) + }.orEmpty() if (responseCode in 200..299) { if (isGitHubApi) githubApiCooldownUntilMs = 0L diff --git a/app/src/main/java/com/wdtt/plus/BoundedInput.kt b/app/src/main/java/com/wdtt/plus/BoundedInput.kt new file mode 100644 index 0000000..e613e38 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/BoundedInput.kt @@ -0,0 +1,19 @@ +package com.wdtt.plus + +import java.io.ByteArrayOutputStream +import java.io.InputStream + +internal fun InputStream.readUtf8TextLimited(maxBytes: Int): String { + require(maxBytes > 0) { "Лимит ответа должен быть положительным." } + val output = ByteArrayOutputStream(minOf(maxBytes, DEFAULT_BUFFER_SIZE)) + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + var total = 0 + while (true) { + val read = read(buffer) + if (read < 0) break + total += read + require(total <= maxBytes) { "Ответ сервиса слишком большой." } + output.write(buffer, 0, read) + } + return output.toString(Charsets.UTF_8.name()) +} diff --git a/app/src/main/java/com/wdtt/plus/CaptchaWebViewManager.kt b/app/src/main/java/com/wdtt/plus/CaptchaWebViewManager.kt index a958591..4ca7659 100644 --- a/app/src/main/java/com/wdtt/plus/CaptchaWebViewManager.kt +++ b/app/src/main/java/com/wdtt/plus/CaptchaWebViewManager.kt @@ -384,14 +384,8 @@ object CaptchaWebViewManager { handler: android.webkit.SslErrorHandler, error: android.net.http.SslError ) { - // Разрешаем только для доверенных доменов VK/OK - val url = error.url ?: "" - if (url.contains("vk.ru") || url.contains("vk.com") || url.contains("okcdn.ru")) { - handler.proceed() - } else { - handler.cancel() - Log.w(TAG, "SSL error rejected for: $url") - } + handler.cancel() + Log.w(TAG, "Отклонена страница с ошибкой TLS") } } diff --git a/app/src/main/java/com/wdtt/plus/ClientNetworkDiagnostics.kt b/app/src/main/java/com/wdtt/plus/ClientNetworkDiagnostics.kt new file mode 100644 index 0000000..9494c44 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ClientNetworkDiagnostics.kt @@ -0,0 +1,562 @@ +package com.wdtt.plus + +import android.content.Context +import android.net.ConnectivityManager +import android.net.DnsResolver +import android.net.LinkProperties +import android.net.Network +import android.net.NetworkCapabilities +import android.os.Build +import android.os.CancellationSignal +import android.os.SystemClock +import android.telephony.TelephonyManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.runInterruptible +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import java.io.DataInputStream +import java.io.DataOutputStream +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.Inet4Address +import java.net.Inet6Address +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.Socket +import java.net.SocketTimeoutException +import java.net.URL +import java.net.UnknownHostException +import java.util.concurrent.Executor +import javax.net.ssl.HttpsURLConnection +import kotlin.coroutines.resume + +data class ClientNetworkDiagnosticsReport( + val summaryLines: List, + val items: List +) + +private data class DiagnosticNetwork( + val network: Network, + val capabilities: NetworkCapabilities, + val linkProperties: LinkProperties?, + val activeNetworkIsVpn: Boolean, + val mobileOperator: String +) + +private data class NetworkProbeResult( + val label: String, + val success: Boolean, + val result: String, + val elapsedMs: Long +) { + fun display(): String = "$label: $result (${elapsedMs} мс)" +} + +internal data class DnsResponseStatus( + val responseCode: Int, + val answerCount: Int, + val truncated: Boolean +) + +internal data class ClientDnsPathAssessment( + val status: String, + val recommendation: String, + val severity: DeviceCheckSeverity, + val action: DeviceCheckAction? +) + +private const val NETWORK_PROBE_TIMEOUT_MS = 4_500L +private const val SOCKET_TIMEOUT_MS = 3_500 +private val directExecutor = Executor { command -> command.run() } +private val clientDnsServers = listOf("77.88.8.8", "77.88.8.1") +private val clientDnsRouteOrder = listOf( + "77.88.8.8 UDP", + "77.88.8.1 UDP", + "77.88.8.8 TCP", + "77.88.8.1 TCP" +) +internal const val clientDnsProbeHost = "api.vk.me" +internal val primaryVkDiagnosticHosts = linkedSetOf( + "api.vk.me", + "calls.okcdn.ru" +) +internal val reserveVkDiagnosticHosts = linkedSetOf( + "vk.ru", + "login.vk.ru", + "api.vk.ru", + "id.vk.ru", + "static.vk.ru", + "vk.com", + "id.vk.com", + "static.vk.com" +) +private val vkDnsHosts = (primaryVkDiagnosticHosts + reserveVkDiagnosticHosts).toList() +private val vkHttpsTargets = listOf( + "api.vk.me" to "https://api.vk.me/method/users.get?v=5.276", + "calls.okcdn.ru" to "https://calls.okcdn.ru/fb.do", + "vk.ru" to "https://vk.ru/", + "login.vk.ru" to "https://login.vk.ru/", + "api.vk.ru" to "https://api.vk.ru/method/users.get?v=5.275", + "id.vk.ru" to "https://id.vk.ru/", + "static.vk.ru" to "https://static.vk.ru/", + "vk.com" to "https://vk.com/", + "id.vk.com" to "https://id.vk.com/", + "static.vk.com" to "https://static.vk.com/" +) + +suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiagnosticsReport = + withContext(Dispatchers.IO) { + val connectivityManager = context.getSystemService(ConnectivityManager::class.java) + val diagnosticNetwork = connectivityManager?.let { selectDiagnosticNetwork(context, it) } + if (diagnosticNetwork == null) { + return@withContext ClientNetworkDiagnosticsReport( + summaryLines = listOf("Активная физическая сеть для проверки DNS/VK не найдена"), + items = listOf( + DeviceCheckItem( + title = "Сетевой путь телефона", + status = "физическая сеть не найдена", + details = "Не удалось выбрать сеть без VPN для безопасной проверки DNS и узлов VK/OK.", + recommendation = "Отключите режим полёта, включите Wi‑Fi или мобильную сеть и повторите диагностику.", + severity = DeviceCheckSeverity.Warning, + action = DeviceCheckAction.NetworkSettings + ) + ) + ) + } + + val networkItem = buildNetworkPathItem(diagnosticNetwork) + val (dnsResults, clientDnsResults, httpsResults) = coroutineScope { + val systemDns = async { probeSystemDns(diagnosticNetwork.network) } + val clientDns = async { probeClientDns(diagnosticNetwork.network) } + val vkHttps = async { probeVkHttps(diagnosticNetwork.network) } + Triple(systemDns.await(), clientDns.await(), vkHttps.await()) + } + + val primaryDnsResults = dnsResults.filter { it.label in primaryVkDiagnosticHosts } + val reserveDnsResults = dnsResults.filter { it.label in reserveVkDiagnosticHosts } + val primaryDnsOk = primaryDnsResults.count { it.success } + val clientUdp = clientDnsResults.filter { it.label.endsWith("UDP") } + val clientTcp = clientDnsResults.filter { it.label.endsWith("TCP") } + val clientUdpOk = clientUdp.count { it.success } + val clientTcpOk = clientTcp.count { it.success } + val primaryHttpsResults = httpsResults.filter { it.label in primaryVkDiagnosticHosts } + val reserveHttpsResults = httpsResults.filter { it.label in reserveVkDiagnosticHosts } + val primaryHttpsOk = primaryHttpsResults.count { it.success } + + val systemPrimaryApiWorks = dnsResults.firstOrNull { it.label == clientDnsProbeHost }?.success == true + val successfulClientDnsRoutes = clientDnsResults + .filter { it.success } + .mapTo(linkedSetOf()) { it.label } + val clientDnsAssessment = assessClientDnsPath(successfulClientDnsRoutes, systemPrimaryApiWorks) + + val dnsItem = DeviceCheckItem( + title = "DNS основного VKCalls на телефоне", + status = "$primaryDnsOk из ${primaryDnsResults.size} основных узлов разрешаются", + details = primaryDnsResults.joinToString(". ") { it.display() } + ". " + + "Резервные legacy- и совместимые узлы: " + + reserveDnsResults.joinToString(". ") { it.display() } + ".", + recommendation = if (primaryDnsOk == primaryDnsResults.size) "" else + "Быстрый VKCalls может быть недоступен. Проверьте системный или Private DNS и сеть оператора; приложение также попробует legacy-резерв.", + severity = if (primaryDnsOk == primaryDnsResults.size) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning, + action = if (primaryDnsOk == primaryDnsResults.size) null else DeviceCheckAction.NetworkSettings + ) + + val clientDnsItem = DeviceCheckItem( + title = "DNS-путь нативного клиента", + status = clientDnsAssessment.status, + details = clientDnsResults.joinToString(". ") { it.display() } + + ". Нативный клиент проверяет эти прямые DNS-пути, а при их недоступности автоматически использует системный DNS Android.", + recommendation = clientDnsAssessment.recommendation, + severity = clientDnsAssessment.severity, + action = clientDnsAssessment.action + ) + + val httpsItem = DeviceCheckItem( + title = "Основной VKCalls HTTPS с телефона", + status = "$primaryHttpsOk из ${primaryHttpsResults.size} основных узлов отвечают", + details = primaryHttpsResults.joinToString(". ") { it.display() } + ". " + + "Резервные legacy- и совместимые узлы: " + + reserveHttpsResults.joinToString(". ") { it.display() } + + ". Любой HTTP-код означает, что DNS, TCP и TLS до узла отработали; авторизация и VK-хеш не используются.", + recommendation = if (primaryHttpsOk == primaryHttpsResults.size) "" else + "Для быстрого VKCalls сеть должна пропускать api.vk.me и calls.okcdn.ru. При их недоступности приложение попробует legacy-резерв.", + severity = if (primaryHttpsOk == primaryHttpsResults.size) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning, + action = if (primaryHttpsOk == primaryHttpsResults.size) null else DeviceCheckAction.NetworkSettings + ) + + val recentNetworkEvents = buildRecentNetworkEventsItem() + ClientNetworkDiagnosticsReport( + summaryLines = listOf( + "Физическая сеть диагностики: ${networkPathSummary(diagnosticNetwork)}", + "DNS основного VKCalls: $primaryDnsOk/${primaryDnsResults.size}", + "DNS клиента: ${clientDnsAssessment.status}; UDP $clientUdpOk/${clientUdp.size}, TCP $clientTcpOk/${clientTcp.size}", + "HTTPS основного VKCalls: $primaryHttpsOk/${primaryHttpsResults.size}" + ), + items = buildList { + add(networkItem) + add(dnsItem) + add(clientDnsItem) + add(httpsItem) + recentNetworkEvents?.let(::add) + } + ) + } + +internal fun assessClientDnsPath( + successfulDirectRoutes: Set, + systemPrimaryApiWorks: Boolean +): ClientDnsPathAssessment { + val selectedDirectRoute = clientDnsRouteOrder.firstOrNull(successfulDirectRoutes::contains) + return when { + selectedDirectRoute == "77.88.8.8 UDP" -> ClientDnsPathAssessment( + status = "основной UDP DNS доступен", + recommendation = "", + severity = DeviceCheckSeverity.Ok, + action = null + ) + selectedDirectRoute == "77.88.8.1 UDP" -> ClientDnsPathAssessment( + status = "резервный UDP DNS доступен", + recommendation = "Основной прямой DNS ограничен, но нативный клиент автоматически выберет рабочий резервный адрес.", + severity = DeviceCheckSeverity.Info, + action = null + ) + selectedDirectRoute?.endsWith(" TCP") == true -> ClientDnsPathAssessment( + status = "UDP DNS недоступен, TCP отвечает", + recommendation = "Оператор ограничивает прямой UDP DNS, но нативный клиент автоматически использует рабочий TCP-путь.", + severity = DeviceCheckSeverity.Info, + action = null + ) + systemPrimaryApiWorks -> ClientDnsPathAssessment( + status = "прямой DNS недоступен, используется системный DNS", + recommendation = "Это штатный автоматический fallback: менять DNS вручную не требуется.", + severity = DeviceCheckSeverity.Info, + action = null + ) + else -> ClientDnsPathAssessment( + status = "DNS до VK недоступен", + recommendation = "Не ответили ни прямые DNS-пути клиента, ни системный DNS Android. Проверьте Private DNS или повторите проверку в другой сети.", + severity = DeviceCheckSeverity.Error, + action = DeviceCheckAction.NetworkSettings + ) + } +} + +private fun selectDiagnosticNetwork(context: Context, connectivityManager: ConnectivityManager): DiagnosticNetwork? { + val activeNetwork = runCatching { connectivityManager.activeNetwork }.getOrNull() + val activeCapabilities = activeNetwork?.let { + runCatching { connectivityManager.getNetworkCapabilities(it) }.getOrNull() + } + val activeNetworkIsVpn = activeCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true + + val candidates = runCatching { connectivityManager.allNetworks.toList() }.getOrDefault(emptyList()) + .mapNotNull { network -> + val capabilities = runCatching { connectivityManager.getNetworkCapabilities(network) }.getOrNull() + ?: return@mapNotNull null + if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) || + !capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + ) { + return@mapNotNull null + } + Triple(network, capabilities, runCatching { connectivityManager.getLinkProperties(network) }.getOrNull()) + } + + val selected = candidates.maxByOrNull { (network, capabilities, _) -> + var score = 0 + if (network == activeNetwork) score += 100 + if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) score += 50 + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) score += 10 + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) score += 5 + score + } ?: return null + + return DiagnosticNetwork( + network = selected.first, + capabilities = selected.second, + linkProperties = selected.third, + activeNetworkIsVpn = activeNetworkIsVpn, + mobileOperator = mobileOperatorSummary(context, selected.second) + ) +} + +private fun mobileOperatorSummary(context: Context, capabilities: NetworkCapabilities): String { + if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return "не применяется" + return runCatching { + val telephonyManager = context.getSystemService(TelephonyManager::class.java) + val network = telephonyManager?.networkOperatorName.orEmpty().trim() + val sim = telephonyManager?.simOperatorName.orEmpty().trim() + val names = listOf(network, sim).filter(String::isNotBlank).distinct() + buildString { + append(names.joinToString(" / ").ifBlank { "не определён" }) + append(", roaming=") + append(telephonyManager?.isNetworkRoaming ?: false) + } + }.getOrDefault("недоступен") +} + +private fun buildNetworkPathItem(network: DiagnosticNetwork): DeviceCheckItem { + val capabilities = network.capabilities + val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) + val details = networkPathSummary(network) + return DeviceCheckItem( + title = "Сетевой путь телефона", + status = if (validated) "физическая сеть подтверждена" else "интернет не подтверждён Android", + details = details, + recommendation = if (validated) "" else + "Проверьте ограничения оператора, captive portal или доступность интернета без VPN.", + severity = if (validated) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning, + action = if (validated) null else DeviceCheckAction.NetworkSettings + ) +} + +private fun networkPathSummary(network: DiagnosticNetwork): String { + val capabilities = network.capabilities + val properties = network.linkProperties + val transports = buildList { + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) add("мобильная") + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) add("Wi‑Fi") + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) add("Ethernet") + }.joinToString().ifBlank { "не определена" } + val hasIpv4 = properties?.linkAddresses?.any { it.address is Inet4Address } == true + val hasIpv6 = properties?.linkAddresses?.any { it.address is Inet6Address } == true + val dnsServers = properties?.dnsServers + ?.joinToString { it.hostAddress.orEmpty() } + ?.ifBlank { "не указаны" } + ?: "недоступны" + val privateDns = if (properties?.isPrivateDnsActive == true) { + properties.privateDnsServerName?.takeIf(String::isNotBlank)?.let { "включён ($it)" } ?: "включён" + } else { + "выключен" + } + val nat64 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + properties?.nat64Prefix?.toString() ?: "нет" + } else { + "не поддерживается Android" + } + val mtu = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + properties?.mtu?.toString() ?: "недоступно" + } else { + "не поддерживается Android" + } + return "Сеть: $transports; validated=${capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)}; " + + "metered=${!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)}; " + + "активный VPN=${network.activeNetworkIsVpn}; оператор=${network.mobileOperator}; " + + "IPv4=$hasIpv4; IPv6=$hasIpv6; NAT64=$nat64; " + + "MTU=$mtu; системные DNS: $dnsServers; Private DNS: $privateDns. " + + "Локальные IP-адреса телефона в отчёт не включаются." +} + +private suspend fun probeSystemDns(network: Network): List = coroutineScope { + vkDnsHosts.map { host -> + async(Dispatchers.IO) { + timedProbe(host) { + val addresses = resolveWithSystemDns(network, host) + val ipv4 = addresses.count { it is Inet4Address } + val ipv6 = addresses.count { it is Inet6Address } + if (addresses.isEmpty()) error("пустой DNS-ответ") + "OK, IPv4=$ipv4, IPv6=$ipv6" + } + } + }.awaitAll() +} + +private suspend fun resolveWithSystemDns(network: Network, host: String): List = + withTimeout(NETWORK_PROBE_TIMEOUT_MS) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + suspendCancellableCoroutine { continuation -> + val cancellationSignal = CancellationSignal() + continuation.invokeOnCancellation { cancellationSignal.cancel() } + DnsResolver.getInstance().query( + network, + host, + DnsResolver.FLAG_EMPTY, + directExecutor, + cancellationSignal, + object : DnsResolver.Callback> { + override fun onAnswer(answer: List, rcode: Int) { + if (!continuation.isActive) return + if (rcode == 0 && answer.isNotEmpty()) continuation.resume(answer) + else continuation.resumeWith(Result.failure(UnknownHostException("DNS rcode=$rcode"))) + } + + override fun onError(error: DnsResolver.DnsException) { + if (continuation.isActive) continuation.resumeWith(Result.failure(error)) + } + } + ) + } + } else { + runInterruptible(Dispatchers.IO) { network.getAllByName(host).toList() } + } + } + +private suspend fun probeClientDns(network: Network): List = coroutineScope { + clientDnsServers.flatMap { server -> + listOf( + async(Dispatchers.IO) { + timedProbe("$server UDP") { directDnsQuery(network, server, useTcp = false) } + }, + async(Dispatchers.IO) { + timedProbe("$server TCP") { directDnsQuery(network, server, useTcp = true) } + } + ) + }.awaitAll() +} + +private fun directDnsQuery(network: Network, server: String, useTcp: Boolean): String { + val queryId = (SystemClock.elapsedRealtimeNanos() and 0xffff).toInt() + val query = buildDnsQuery(clientDnsProbeHost, queryId) + val response = if (useTcp) { + Socket().use { socket -> + network.bindSocket(socket) + socket.connect(InetSocketAddress(server, 53), SOCKET_TIMEOUT_MS) + socket.soTimeout = SOCKET_TIMEOUT_MS + DataOutputStream(socket.getOutputStream()).use { output -> + output.writeShort(query.size) + output.write(query) + output.flush() + val input = DataInputStream(socket.getInputStream()) + val responseLength = input.readUnsignedShort() + require(responseLength in 12..65_535) { "некорректная длина DNS-ответа" } + ByteArray(responseLength).also(input::readFully) + } + } + } else { + DatagramSocket(null).use { socket -> + network.bindSocket(socket) + socket.soTimeout = SOCKET_TIMEOUT_MS + socket.connect(InetSocketAddress(server, 53)) + socket.send(DatagramPacket(query, query.size)) + val buffer = ByteArray(2_048) + val packet = DatagramPacket(buffer, buffer.size) + socket.receive(packet) + packet.data.copyOfRange(packet.offset, packet.offset + packet.length) + } + } + val status = parseDnsResponse(response, queryId) + require(status.responseCode == 0) { "DNS rcode=${status.responseCode}" } + require(status.answerCount > 0) { "DNS-ответ без записей" } + return "OK, ответов=${status.answerCount}${if (status.truncated) ", truncated" else ""}" +} + +internal fun buildDnsQuery(host: String, queryId: Int): ByteArray { + val labels = host.trim('.').split('.') + require(labels.isNotEmpty() && labels.all { it.isNotBlank() && it.toByteArray(Charsets.US_ASCII).size <= 63 }) { + "некорректное DNS-имя" + } + val bytes = ArrayList(host.length + 18) + fun addShort(value: Int) { + bytes += ((value ushr 8) and 0xff).toByte() + bytes += (value and 0xff).toByte() + } + addShort(queryId) + addShort(0x0100) + addShort(1) + addShort(0) + addShort(0) + addShort(0) + labels.forEach { label -> + val encoded = label.toByteArray(Charsets.US_ASCII) + bytes += encoded.size.toByte() + encoded.forEach { bytes += it } + } + bytes += 0.toByte() + addShort(1) + addShort(1) + return bytes.toByteArray() +} + +internal fun parseDnsResponse(response: ByteArray, expectedId: Int): DnsResponseStatus { + require(response.size >= 12) { "короткий DNS-ответ" } + fun unsignedShort(offset: Int): Int = + ((response[offset].toInt() and 0xff) shl 8) or (response[offset + 1].toInt() and 0xff) + require(unsignedShort(0) == (expectedId and 0xffff)) { "чужой DNS-ответ" } + val flags = unsignedShort(2) + require(flags and 0x8000 != 0) { "DNS-пакет не является ответом" } + return DnsResponseStatus( + responseCode = flags and 0x000f, + answerCount = unsignedShort(6), + truncated = flags and 0x0200 != 0 + ) +} + +private suspend fun probeVkHttps(network: Network): List = coroutineScope { + vkHttpsTargets.map { (label, url) -> + async(Dispatchers.IO) { + timedProbe(label) { httpsProbe(network, url) } + } + }.awaitAll() +} + +private fun httpsProbe(network: Network, target: String): String { + val connection = network.openConnection(URL(target)) as HttpsURLConnection + return try { + connection.connectTimeout = SOCKET_TIMEOUT_MS + connection.readTimeout = SOCKET_TIMEOUT_MS + connection.instanceFollowRedirects = false + connection.requestMethod = "GET" + connection.setRequestProperty("User-Agent", "WDTT-Plus-Diagnostics/${BuildConfig.VERSION_NAME}") + connection.setRequestProperty("Range", "bytes=0-0") + val responseCode = connection.responseCode + require(responseCode in 100..599) { "нет HTTP-ответа" } + "HTTP $responseCode" + } finally { + connection.disconnect() + } +} + +private suspend inline fun timedProbe(label: String, crossinline block: suspend () -> String): NetworkProbeResult { + val started = SystemClock.elapsedRealtime() + return try { + val result = block() + NetworkProbeResult(label, true, result, SystemClock.elapsedRealtime() - started) + } catch (error: CancellationException) { + if (error !is TimeoutCancellationException) throw error + NetworkProbeResult(label, false, "тайм-аут", SystemClock.elapsedRealtime() - started) + } catch (_: SocketTimeoutException) { + NetworkProbeResult(label, false, "тайм-аут", SystemClock.elapsedRealtime() - started) + } catch (_: UnknownHostException) { + NetworkProbeResult(label, false, "DNS не разрешён", SystemClock.elapsedRealtime() - started) + } catch (error: Throwable) { + val reason = error.message + ?.replace(Regex("[\\r\\n]+"), " ") + ?.take(120) + ?.takeIf(String::isNotBlank) + ?: error.javaClass.simpleName + NetworkProbeResult(label, false, reason, SystemClock.elapsedRealtime() - started) + } +} + +private fun buildRecentNetworkEventsItem(): DeviceCheckItem? { + val entries = TunnelManager.logs.value + .filter { entry -> + entry.severity != LogSeverity.Info || + entry.key.startsWith("err_") || + entry.key.startsWith("vkcalls_") || + entry.key.startsWith("vk_provider_") || + entry.key.startsWith("vk_credentials_") || + entry.key.startsWith("vk_legacy_") || + entry.key.startsWith("turn_") || + entry.key.startsWith("worker_turn_") + } + .take(12) + if (entries.isEmpty()) return null + val details = entries.joinToString(" | ") { entry -> + val message = entry.message + .replace(Regex("(https?://[^?\\s]+)\\?[^\\s]+"), "\$1?<параметры скрыты>") + .replace(Regex("(?i)(token|password|credential|secret)=([^&\\s]+)"), "\$1=<скрыто>") + .take(220) + "${entry.key}: $message${if (entry.count > 1) " ×${entry.count}" else ""}" + } + return DeviceCheckItem( + title = "Последние сетевые события туннеля", + status = "собрано ${entries.size}", + details = details, + severity = DeviceCheckSeverity.Info + ) +} diff --git a/app/src/main/java/com/wdtt/plus/ClientTransferCodec.kt b/app/src/main/java/com/wdtt/plus/ClientTransferCodec.kt index 01e4021..58667a8 100644 --- a/app/src/main/java/com/wdtt/plus/ClientTransferCodec.kt +++ b/app/src/main/java/com/wdtt/plus/ClientTransferCodec.kt @@ -90,13 +90,11 @@ object ClientTransferCodec { val clean = value.trim() if (clean.isBlank()) return "" require(clean.length <= 4096 && clean.none(Char::isISOControl)) { "Поле VK-хешей повреждено." } - val hashes = clean.split(Regex("[,\\s]+")) - .map { VkJoinLink.extractHash(it) } - .filter { it.isNotBlank() } - require(hashes.isNotEmpty() && hashes.all { it.length >= 16 } && hashes.none { it.contains('/') || it.contains('\\') }) { + val hashes = VkJoinLink.normalizeHashes(clean) + require(hashes != null) { "VK-хеши в переносе имеют неверный формат." } - return hashes.distinct().joinToString(",") + return hashes } } diff --git a/app/src/main/java/com/wdtt/plus/DeployManager.kt b/app/src/main/java/com/wdtt/plus/DeployManager.kt index e875984..4f265e2 100644 --- a/app/src/main/java/com/wdtt/plus/DeployManager.kt +++ b/app/src/main/java/com/wdtt/plus/DeployManager.kt @@ -17,6 +17,7 @@ object DeployManager { val deployProgress = MutableStateFlow(0f) val currentStep = MutableStateFlow("") val lastResult = MutableStateFlow("") // "success", "error: ...", "" + val installedServerVersion = MutableStateFlow("") @Volatile var activeSession: com.jcraft.jsch.Session? = null @@ -59,6 +60,7 @@ object DeployManager { deployProgress.value = 0f currentStep.value = "Инициализация..." lastResult.value = "" + installedServerVersion.value = "" } fun stopDeploy(result: String = "") { diff --git a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt index 3554e3c..a74a9d7 100644 --- a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt +++ b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt @@ -340,8 +340,8 @@ object DeviceCompatibility { DeviceCheckItem( title = "WebView", status = "не найден", - details = "Автоматическая и ручная captcha через WebView могут не работать.", - recommendation = "Проверьте системный Android System WebView или браузер-провайдер WebView.", + details = "Быстрый VKCalls может работать без WebView, но автоматическая и ручная капча резервного способа будут недоступны.", + recommendation = "Обновите или включите Android System WebView либо браузер-провайдер WebView, чтобы резервное подключение могло пройти капчу.", severity = DeviceCheckSeverity.Warning, firstLaunchRelevant = false, action = DeviceCheckAction.WebViewSettings @@ -350,7 +350,7 @@ object DeviceCompatibility { DeviceCheckItem( title = "WebView", status = webView.packageName, - details = "Версия: ${webView.versionName}. WebView доступен для captcha-сценариев.", + details = "Версия: ${webView.versionName}. WebView доступен для капчи резервного способа.", severity = DeviceCheckSeverity.Ok, firstLaunchRelevant = false ) @@ -395,7 +395,7 @@ object DeviceCompatibility { return DeviceCheckItem( title = "Сеть Android", status = "активная сеть не найдена", - details = "Приложение запустится, но для VKCalls, TURN и обновлений нужна сеть.", + details = "Приложение запустится, но для быстрого VKCalls, TURN и обновлений нужна сеть.", recommendation = "Подключитесь к Wi‑Fi или мобильной сети.", severity = DeviceCheckSeverity.Warning, action = DeviceCheckAction.NetworkSettings @@ -422,7 +422,7 @@ object DeviceCompatibility { DeviceCheckItem( title = "Сеть Android", status = "$transports, интернет подтверждён", - details = "Активная сеть выглядит пригодной для проверки VK/TURN.", + details = "Android подтвердил общий доступ в интернет. Системный DNS, DNS-путь нативного клиента и служебные узлы VK/OK проверяются отдельными пунктами ниже.", severity = DeviceCheckSeverity.Ok ) } diff --git a/app/src/main/java/com/wdtt/plus/DeviceIdentity.kt b/app/src/main/java/com/wdtt/plus/DeviceIdentity.kt new file mode 100644 index 0000000..0391dae --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/DeviceIdentity.kt @@ -0,0 +1,29 @@ +package com.wdtt.plus + +internal object DeviceIdentity { + private val validPattern = Regex("^[A-Za-z0-9_.:-]{8,128}$") + private val knownInvalidAndroidIds = setOf( + "9774d56d682e549c", + "unknown", + ) + + fun valid(value: String): Boolean = + value.trim().matches(validPattern) && + value.trim().lowercase() !in knownInvalidAndroidIds + + fun resolve( + existing: String?, + platformId: String?, + generatedId: String, + ): String { + val stored = existing.orEmpty().trim() + if (valid(stored)) return stored + + val platform = platformId.orEmpty().trim() + if (valid(platform)) return platform + + val generated = generatedId.trim() + require(valid(generated)) { "Некорректный резервный идентификатор устройства." } + return generated + } +} diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt index 04aa179..50dbec5 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -12,17 +12,21 @@ import android.os.PowerManager import android.provider.Settings import android.util.Log import android.view.HapticFeedbackConstants +import android.view.ViewTreeObserver import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts +import androidx.browser.auth.AuthTabIntent import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.SizeTransform import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.CubicBezierEasing import androidx.compose.animation.core.tween +import androidx.compose.animation.core.snap import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.togetherWith @@ -91,7 +95,9 @@ import com.wdtt.plus.ui.ExceptionsTab import com.wdtt.plus.ui.InfoTab import com.wdtt.plus.ui.AdminImportDialog import com.wdtt.plus.ui.TransferCenterDialog +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.flow.first @@ -99,20 +105,81 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import java.io.File +import java.util.concurrent.ConcurrentHashMap import kotlin.math.PI import kotlin.math.abs import kotlin.math.cos import kotlin.math.min import kotlin.math.sin +private const val STATE_EXTERNAL_INTENT_CONSUMED = "external_intent_consumed" + +internal fun isOneShotIncomingIntentAction(action: String?): Boolean = + action == Intent.ACTION_VIEW || action == Intent.ACTION_SEND + +internal fun shouldHandleIncomingIntent( + action: String?, + restoredAsConsumed: Boolean, +): Boolean = !isOneShotIncomingIntentAction(action) || !restoredAsConsumed + +private sealed interface WdttConnectFlow { + data class Progress(val message: String) : WdttConnectFlow + data class SelectProfile( + val plan: WdttDeepLinkApplyPlan, + val delivery: RemoteDocumentDelivery + ) : WdttConnectFlow + data class ConfirmLimitedSetup( + val plan: WdttDeepLinkApplyPlan, + val delivery: RemoteDocumentDelivery + ) : WdttConnectFlow + data class SelectHashes( + val profile: Int, + val continuation: RemoteContinuation, + val access: RemoteAccessCapability, + ) : WdttConnectFlow + data class ExternalAction( + val profile: Int, + val continuation: RemoteContinuation, + val access: RemoteAccessCapability, + val message: String + ) : WdttConnectFlow + data class Complete(val message: String) : WdttConnectFlow + data class Failed( + val message: String, + val action: RemoteDocumentFailureAction? = null, + ) : WdttConnectFlow +} + class MainActivity : ComponentActivity() { private var sharedVkHashResult by mutableStateOf(null) private var sharedVkHashError by mutableStateOf(null) private var wdttDeepLinkMessage by mutableStateOf(null) private var pendingWdttDeepLinkPlan by mutableStateOf(null) + private var wdttConnectFlow by mutableStateOf(null) private var pendingAdminTransfer by mutableStateOf(null) + private var connectActionJob: Job? = null + private lateinit var settingsStore: SettingsStore + private var externalIntentConsumed = false + @Volatile + private var uiReadyForFirstDraw = false + private val remoteAuthTabLauncher = AuthTabIntent.registerActivityResultLauncher(this) { result -> + if (result.resultCode != AuthTabIntent.RESULT_OK) return@registerActivityResultLauncher + if (RemoteContinuationLauncher.isCancellationCallback(result.resultUri)) { + connectActionJob?.cancel() + connectActionJob = null + wdttConnectFlow = null + return@registerActivityResultLauncher + } + val documentUri = RemoteContinuationLauncher.callbackDocumentUri(result.resultUri) + if (documentUri == null) { + wdttDeepLinkMessage = "WDTT Plus получил повреждённый результат автоматической настройки." + return@registerActivityResultLauncher + } + handleRemoteDocument(documentUri) + } companion object { + private val remoteDocumentRequests = ConcurrentHashMap.newKeySet() var activeActivities = 0 var isForeground: Boolean get() = activeActivities > 0 @@ -123,6 +190,22 @@ class MainActivity : ComponentActivity() { super.onStart() activeActivities++ ManlCaptchaWebViewManager.checkAndShowPendingCaptcha(this) + lifecycleScope.launch(Dispatchers.IO) { + val profiles = AccessLifecycleCoordinator.takePendingExternalRefreshProfiles() + + settingsStore.takeAccessLifecycleActionProfiles() + profiles.forEach { profile -> + launch { + AccessLifecycleCoordinator.refreshAfterExternalAction( + this@MainActivity, + profile, + ) + } + } + AccessLifecycleCoordinator.refreshAllOnForeground( + context = this@MainActivity, + alreadyScheduledProfiles = profiles, + ) + } } override fun onStop() { @@ -132,13 +215,26 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - + settingsStore = SettingsStore(this) + + val contentView = findViewById(android.R.id.content) + contentView.viewTreeObserver.addOnPreDrawListener( + object : ViewTreeObserver.OnPreDrawListener { + override fun onPreDraw(): Boolean { + if (uiReadyForFirstDraw && contentView.viewTreeObserver.isAlive) { + contentView.viewTreeObserver.removeOnPreDrawListener(this) + } + return uiReadyForFirstDraw + } + } + ) + TunnelManager.initObservers(this) enableEdgeToEdge() setContent { - val settingsStore = remember { SettingsStore(this) } + val settingsStore = remember { this@MainActivity.settingsStore } val themeMode by settingsStore.themeMode.collectAsStateWithLifecycle(initialValue = "system") val isDynamicColor by settingsStore.isDynamicColor.collectAsStateWithLifecycle(initialValue = false) val themePalette by settingsStore.themePalette.collectAsStateWithLifecycle(initialValue = "indigo") @@ -149,6 +245,7 @@ class MainActivity : ComponentActivity() { WDTTTheme(themeMode = themeMode, dynamicColor = isDynamicColor, themePalette = themePalette) { MainScreen( settingsStore = settingsStore, + onUiReadyForFirstDraw = { uiReadyForFirstDraw = true }, sharedVkHashResult = sharedVkHashResult, sharedVkHashError = sharedVkHashError, onSharedVkHashMessageShown = { @@ -158,6 +255,7 @@ class MainActivity : ComponentActivity() { wdttDeepLinkMessage = wdttDeepLinkMessage, onWdttDeepLinkMessageShown = { wdttDeepLinkMessage = null }, pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan, + wdttConnectFlow = wdttConnectFlow, pendingAdminTransfer = pendingAdminTransfer, onIncomingTransferContent = ::handleIncomingTransferText, onAdminTransferDismissed = { pendingAdminTransfer = null }, @@ -176,6 +274,52 @@ class MainActivity : ComponentActivity() { pendingWdttDeepLinkPlan = null wdttDeepLinkMessage = "Импорт wdtt:// ссылки отменён." }, + onSelectWdttConnectProfile = { profile -> + (wdttConnectFlow as? WdttConnectFlow.SelectProfile)?.let { flow -> + wdttConnectFlow = flow.copy(plan = flow.plan.copy(targetProfile = profile)) + } + }, + onConfirmWdttConnectProfile = { plan -> + (wdttConnectFlow as? WdttConnectFlow.SelectProfile)?.delivery?.let { delivery -> + applyWdttDeepLinkPlan( + plan, + fromRemoteDocument = true, + delivery = delivery + ) + } + }, + onContinueLimitedWdttSetup = { plan, delivery -> + if (plan.requiresConfirmation) { + wdttConnectFlow = WdttConnectFlow.SelectProfile(plan, delivery) + } else { + applyWdttDeepLinkPlan( + plan, + fromRemoteDocument = true, + delivery = delivery, + ) + } + }, + onStartWdttConnectAction = ::startConnectAction, + onCancelWdttConnectAction = ::cancelConnectAction, + onSaveWdttConnectManualHashes = ::saveConnectManualHashes, + onRestoreWdttConnectHashes = ::restoreConnectHashes, + onVkHashesSaved = { profile, hashes -> + lifecycleScope.launch { + runCatching { + AccessLifecycleCoordinator.syncProfileValues( + context = this@MainActivity, + profileIndex = profile, + values = hashes, + ) + } + } + }, + onSkipWdttConnectHashes = ::skipConnectHashes, + onOpenWdttConnectFailureAction = { target -> + dismissWdttConnectFlow() + launchRemoteContinuation(target) + }, + onDismissWdttConnectFlow = ::dismissWdttConnectFlow, themeMode = themeMode, onThemeChange = { mode -> scope.launch { @@ -201,53 +345,110 @@ class MainActivity : ComponentActivity() { ) } } - handleIncomingIntent(intent) + val restoredAsConsumed = + savedInstanceState?.getBoolean(STATE_EXTERNAL_INTENT_CONSUMED) == true + if (!shouldHandleIncomingIntent(intent?.action, restoredAsConsumed)) { + externalIntentConsumed = true + replaceConsumedIncomingIntent() + } else { + handleIncomingIntent(intent) + } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) - setIntent(intent) + externalIntentConsumed = false handleIncomingIntent(intent) } + override fun onSaveInstanceState(outState: Bundle) { + outState.putBoolean(STATE_EXTERNAL_INTENT_CONSUMED, externalIntentConsumed) + super.onSaveInstanceState(outState) + } + + internal fun launchRemoteContinuation(target: RemoteLaunchTarget) { + RemoteContinuationLauncher.launch(this, target, remoteAuthTabLauncher) + } + private fun handleIncomingIntent(intent: Intent?) { when (intent?.action) { Intent.ACTION_VIEW -> { - val data = intent.data ?: return - if (data.scheme.equals("wdtt", ignoreCase = true)) { + val data = intent.data + val mimeType = intent.type + externalIntentConsumed = true + replaceConsumedIncomingIntent() + if (data == null) return + if (RemoteDocumentGateway.extractLink(data) != null) { + handleRemoteDocument(data) + } else if ( + data.scheme.equals("wdtt", ignoreCase = true) && + data.host.equals("return", ignoreCase = true) + ) { + val documentUri = RemoteContinuationLauncher.callbackDocumentUri(data) + if (documentUri != null) { + handleRemoteDocument(documentUri) + } else { + connectActionJob?.cancel() + connectActionJob = null + wdttConnectFlow = null + } + } else if (data.scheme.equals("wdtt", ignoreCase = true)) { handleIncomingTransferText(data.toString()) } else { - handleIncomingUri(data, intent.type) + handleIncomingUri(data, mimeType) } } Intent.ACTION_SEND -> { + val mimeType = intent.type val streamUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) } else { @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri } ?: intent.clipData?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.uri - val streamFirst = intent.type?.let { type -> - type.startsWith("image/") || type == "application/json" || - type == "application/vnd.wdtt.plus.transfer" || - type == "application/vnd.wdtt.plus.client" || - type == "application/octet-stream" + val streamFirst = mimeType?.let { type -> + type.startsWith("image/") || WdttDocument.isAcceptedMimeType(type) } == true + val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT) + ?: intent.clipData + ?.takeIf { it.itemCount > 0 } + ?.getItemAt(0) + ?.text + ?.toString() + externalIntentConsumed = true + replaceConsumedIncomingIntent() if (streamFirst && streamUri != null) { - handleIncomingUri(streamUri, intent.type) + handleIncomingUri(streamUri, mimeType) return } - val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT) - ?: intent.clipData?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text?.toString() if (!sharedText.isNullOrBlank()) { handleIncomingTransferText(sharedText) return } - if (streamUri != null) handleIncomingUri(streamUri, intent.type) + if (streamUri != null) handleIncomingUri(streamUri, mimeType) } } } + private fun replaceConsumedIncomingIntent() { + setIntent( + Intent(this, MainActivity::class.java).apply { + action = Intent.ACTION_MAIN + addCategory(Intent.CATEGORY_LAUNCHER) + } + ) + } + + private fun vkHashDeviceName(): String { + val manufacturer = Build.MANUFACTURER.orEmpty().trim() + val model = Build.MODEL.orEmpty().trim() + val name = listOf(manufacturer, model) + .filter { it.isNotBlank() } + .distinctBy { it.lowercase() } + .joinToString(" ") + return name.ifBlank { "Android-устройство" } + } + private fun handleIncomingUri(uri: Uri, mimeType: String?) { lifecycleScope.launch { runCatching { @@ -264,6 +465,10 @@ class MainActivity : ComponentActivity() { } private fun handleIncomingTransferText(value: String) { + RemoteDocumentGateway.extractLink(value.trim())?.let { link -> + receiveRemoteDocument(link) + return + } val link = WdttTransferCodec.extractWdttLink(value) when { ClientTransferCodec.isClientTransfer(value) -> { @@ -276,47 +481,427 @@ class MainActivity : ComponentActivity() { wdttDeepLinkMessage = "Распознана резервная копия сервера. Она применяется к выбранному серверу во вкладке «Деплой» → «Перенос сервера» → «Импорт»." } WdttTransferCodec.documentFormat(value) == "wdtt-plus-admin-settings" -> { - wdttDeepLinkMessage = "Распознаны незашифрованные настройки администратора. В целях безопасности импортируется только защищённый файл, созданный через раздел «Передача»." + wdttDeepLinkMessage = "Распознаны незашифрованные настройки администратора. В целях безопасности импортируется только защищённый файл, созданный в разделе «Получение/Передача»." } else -> handleIncomingVkShare(value) } } - private fun handleIncomingWdttLink(link: String) { + private fun handleRemoteDocument(uri: Uri) { + val link = RemoteDocumentGateway.extractLink(uri) + if (link == null) { + wdttDeepLinkMessage = "Ссылка подключения повреждена или устарела." + return + } + receiveRemoteDocument(link) + } + + private fun receiveRemoteDocument(link: RemoteDocumentLink) { + if (!remoteDocumentRequests.add(link.url)) return lifecycleScope.launch { - val store = SettingsStore(this@MainActivity) - runCatching { - store.createWdttDeepLinkApplyPlan(link) - }.onSuccess { plan -> - if (plan == null) { - wdttDeepLinkMessage = WdttDeepLink.validate(link).userMessage() - } else if (plan.requiresConfirmation) { - pendingWdttDeepLinkPlan = plan - } else { - applyWdttDeepLinkPlan(plan) + try { + wdttConnectFlow = WdttConnectFlow.Progress("Проверяем ссылку и получаем доступ...") + val delivery = RemoteDocumentGateway.receive( + link = link, + device = settingsStore.getOrCreateConnectDeviceId(), + label = vkHashDeviceName(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + localBindings = settingsStore.remoteDocumentBindings(), + ) + wdttConnectFlow = WdttConnectFlow.Progress("Доступ получен. Подготавливаем VPN-профиль...") + var boundProfile: Int? = null + for (binding in listOf(delivery.binding, delivery.access.binding)) { + if (binding.isBlank()) continue + boundProfile = settingsStore.profileForRemoteBinding(binding) + if (boundProfile != null) break } - }.onFailure { error -> - wdttDeepLinkMessage = error.message ?: "Не удалось применить wdtt:// ссылку." + if (boundProfile == null && delivery.kind == RemoteDocumentKind.BASE) { + boundProfile = settingsStore.profileForConnectionDocument(delivery.document) + } + if ( + delivery.kind == RemoteDocumentKind.UPDATE && + boundProfile == null && + delivery.binding.isNotBlank() + ) { + wdttConnectFlow = WdttConnectFlow.Failed( + "Профиль не найден на этом устройстве. Если он был подключён " + + "на другом телефоне, сначала отвяжите прежнее устройство " + + "в боте. Затем получите там новую ссылку подключения " + + "и откройте её на этом телефоне." + ) + return@launch + } + handleIncomingWdttLink( + delivery.document, + fromRemoteDocument = true, + delivery = delivery, + preferredProfile = boundProfile, + existingRemoteProfile = boundProfile != null, + ) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: RemoteDocumentFailure) { + wdttConnectFlow = WdttConnectFlow.Failed( + message = error.message + ?: "Не удалось активировать доступ. Получите новую ссылку подключения.", + action = error.action, + ) + } catch (error: Exception) { + wdttConnectFlow = WdttConnectFlow.Failed( + error.message ?: "Не удалось активировать доступ. Получите новую ссылку подключения." + ) + } finally { + remoteDocumentRequests.remove(link.url) } } } - private fun applyWdttDeepLinkPlan(plan: WdttDeepLinkApplyPlan) { + private fun handleIncomingWdttLink( + link: String, + fromRemoteDocument: Boolean = false, + delivery: RemoteDocumentDelivery? = null, + preferredProfile: Int? = null, + existingRemoteProfile: Boolean = false, + ) { lifecycleScope.launch { val store = SettingsStore(this@MainActivity) runCatching { - store.applyWdttDeepLink(plan) + store.createWdttDeepLinkApplyPlan(link) + }.onSuccess { basePlan -> + val plan = basePlan?.let { + if (preferredProfile == null) it else it.copy( + targetProfile = preferredProfile.coerceIn(0, 2), + requiresConfirmation = false + ) + } + if (plan == null) { + if (fromRemoteDocument) { + wdttConnectFlow = WdttConnectFlow.Failed( + "Не удалось подготовить профиль из полученных данных. Получите новую ссылку." + ) + } else { + wdttDeepLinkMessage = WdttDeepLink.validate(link).userMessage() + } + } else if (delivery?.kind == RemoteDocumentKind.UPDATE) { + applyWdttDeepLinkPlan( + plan = plan, + fromRemoteDocument = true, + delivery = delivery, + isBoundUpdate = true, + existingRemoteProfile = true, + ) + } else if ( + fromRemoteDocument && + delivery != null && + delivery.requiresInitialContinuationWarning( + existingProfileHasVkHashes = existingRemoteProfile && + preferredProfile?.let { profile -> + store.tunnelProfileSnapshot(profile).vkHashes.isNotBlank() + } == true, + ) + ) { + wdttConnectFlow = WdttConnectFlow.ConfirmLimitedSetup(plan, delivery) + } else if (plan.requiresConfirmation) { + if (fromRemoteDocument && delivery != null) { + wdttConnectFlow = WdttConnectFlow.SelectProfile(plan, delivery) + } else { + pendingWdttDeepLinkPlan = plan + } + } else { + applyWdttDeepLinkPlan( + plan, + fromRemoteDocument, + delivery, + isBoundUpdate = false, + existingRemoteProfile = existingRemoteProfile, + ) + } + }.onFailure { error -> + if (fromRemoteDocument) { + wdttConnectFlow = WdttConnectFlow.Failed( + error.message ?: "Не удалось применить доступ." + ) + } else { + wdttDeepLinkMessage = error.message ?: "Не удалось применить wdtt:// ссылку." + } + } + } + } + + private fun applyWdttDeepLinkPlan( + plan: WdttDeepLinkApplyPlan, + fromRemoteDocument: Boolean = false, + delivery: RemoteDocumentDelivery? = null, + isBoundUpdate: Boolean = false, + existingRemoteProfile: Boolean = false, + ) { + lifecycleScope.launch { + if (fromRemoteDocument) { + wdttConnectFlow = WdttConnectFlow.Progress("Сохраняем настройки в выбранный VPN-профиль...") + } + val store = SettingsStore(this@MainActivity) + runCatching { + if (fromRemoteDocument && delivery != null) { + store.applyRemoteDocumentDelivery( + plan = plan, + delivery = delivery, + isBoundUpdate = isBoundUpdate, + existingProfileRedelivery = existingRemoteProfile, + ) + } else { + store.applyWdttDeepLink( + plan, + resetRemoteContinuation = !isBoundUpdate, + profileMaxWorkers = delivery?.profileMaxWorkers, + remoteManaged = if (isBoundUpdate) null else fromRemoteDocument, + preserveVkHashes = + isBoundUpdate && + delivery?.shouldPreserveLocalVkHashes() == true, + ) + } }.onSuccess { result -> - wdttDeepLinkMessage = if (result == null) { - WdttDeepLink.validate(plan.link).userMessage() + val savedProfile = result?.targetProfile ?: plan.targetProfile + if (fromRemoteDocument && result != null) { + requestTunnelProfileRuntimeUpdate(savedProfile) + } + val message = if (result == null) { + WdttDeepLink.validate(plan.link, allowMissingHashes = true).userMessage() } else { val profileLabel = vpnProfileDisplayName(result.targetProfile, store.profileNames.first()) val action = if (result.overwritten) "перезаписана" else "добавлена" val mode = if (result.storedAsLink) "сохранена в режиме ссылки" else "разобрана, поля подключения заполнены" - "Ссылка wdtt:// $action в профиль $profileLabel: $mode." + buildString { + append("Ссылка wdtt:// $action в профиль $profileLabel: $mode.") + if ( + WdttDeepLink.parse(plan.link, allowMissingHashes = true) + ?.hashes + .isNullOrBlank() + ) { + append(" Добавьте свой VK-хеш перед запуском VPN.") + } + } + } + if (fromRemoteDocument) { + val profile = result?.targetProfile ?: plan.targetProfile + if (delivery?.access?.available == true) { + lifecycleScope.launch { + AccessLifecycleCoordinator.refreshProfile( + this@MainActivity, + profile, + force = delivery.access.initialStatus == null, + ) + } + } + if (isBoundUpdate) { + val profileLabel = vpnProfileDisplayName(profile, store.profileNames.first()) + wdttConnectFlow = WdttConnectFlow.Complete( + if (result?.alreadyApplied == true) { + "Обновление профиля $profileLabel уже применено." + } else { + "Профиль $profileLabel обновлён. Новые данные уже видны в настройках туннеля." + } + ) + } else if ( + existingRemoteProfile && + store.tunnelProfileSnapshot(profile).vkHashes.isNotBlank() + ) { + val profileLabel = vpnProfileDisplayName(profile, store.profileNames.first()) + wdttConnectFlow = WdttConnectFlow.Complete( + "Удалённый профиль $profileLabel уже подключён и обновлён." + ) + } else { + val continuation = delivery?.continuation ?: RemoteContinuation( + available = false, + message = "Автоматическое заполнение для этого доступа сейчас недоступно." + ) + wdttConnectFlow = WdttConnectFlow.SelectHashes( + profile = profile, + continuation = continuation, + access = delivery?.access ?: RemoteAccessCapability.Unavailable, + ) + } + } else { + wdttDeepLinkMessage = message } }.onFailure { error -> - wdttDeepLinkMessage = error.message ?: "Не удалось применить wdtt:// ссылку." + if (fromRemoteDocument) { + wdttConnectFlow = WdttConnectFlow.Failed( + error.message ?: "Не удалось сохранить профиль." + ) + } else { + wdttDeepLinkMessage = error.message ?: "Не удалось применить wdtt:// ссылку." + } + } + } + } + + private fun startConnectAction(profile: Int, continuation: RemoteContinuation) { + connectActionJob?.cancel() + val access = (wdttConnectFlow as? WdttConnectFlow.SelectHashes) + ?.access + ?: RemoteAccessCapability.Unavailable + wdttConnectFlow = WdttConnectFlow.ExternalAction( + profile = profile, + continuation = continuation, + access = access, + message = "Подготавливаем безопасный переход в VK..." + ) + 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 + ) { + wdttConnectFlow = WdttConnectFlow.ExternalAction( + profile = profile, + continuation = continuation, + access = access, + message = "Останавливаем VPN и ждём стабильного подключения перед входом в VK..." + ) + } + val stopResult = TunnelStopCoordinator.stopAndAwait(this@MainActivity) + if (!stopResult.succeeded) { + throw IllegalStateException( + if (stopResult == TunnelStopResult.TIMED_OUT) { + "VPN не остановился за 20 секунд. Вернитесь в приложение и повторите попытку." + } else { + "Не удалось запросить остановку VPN. Остановите туннель и повторите попытку." + } + ) + } + 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( + capability = continuation, + device = settingsStore.getOrCreateConnectDeviceId() + ) + launchRemoteContinuation(target) + wdttConnectFlow = WdttConnectFlow.Complete( + if (tunnelStoppedForVk) { + "Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически. VPN оставлен выключенным." + } else { + "Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически." + } + ) + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + wdttConnectFlow = WdttConnectFlow.Failed( + error.message ?: "Не удалось автоматически получить VK-хеши." + ) + } finally { + if (connectActionJob === runningJob) { + connectActionJob = null + } + } + } + } + + private fun cancelConnectAction() { + val flow = wdttConnectFlow as? WdttConnectFlow.ExternalAction ?: return + connectActionJob?.cancel() + connectActionJob = null + wdttConnectFlow = WdttConnectFlow.SelectHashes( + profile = flow.profile, + continuation = flow.continuation, + access = flow.access, + ) + } + + private fun skipConnectHashes() { + if (wdttConnectFlow !is WdttConnectFlow.SelectHashes) return + wdttConnectFlow = WdttConnectFlow.Complete( + "Доступ добавлен. VK-хеши можно заполнить позже в настройках профиля." + ) + } + + private fun dismissWdttConnectFlow() { + connectActionJob?.cancel() + connectActionJob = null + wdttConnectFlow = null + } + + private fun saveConnectManualHashes(profile: Int, rawHashes: String) { + lifecycleScope.launch { + val hashes = rawHashes + .split(Regex("[\\s,]+")) + .map(VkJoinLink::extractHash) + .filter(VkJoinLink::isValidHash) + .distinct() + if (hashes.isEmpty()) { + wdttConnectFlow = WdttConnectFlow.Failed( + "Вставьте от 1 до 4 VK-хешей или ссылок VK Звонков." + ) + return@launch + } + runCatching { + settingsStore.saveVkHashesForProfile(profile, hashes) + }.onSuccess { + runCatching { + AccessLifecycleCoordinator.syncProfileValues( + context = this@MainActivity, + profileIndex = profile, + values = hashes, + ) + } + wdttConnectFlow = WdttConnectFlow.Complete( + "VK-хеши сохранены в новом VPN-профиле." + ) + }.onFailure { error -> + wdttConnectFlow = WdttConnectFlow.Failed( + error.message ?: "Не удалось сохранить VK-хеши." + ) + } + } + } + + private fun restoreConnectHashes(profile: Int, capability: RemoteAccessCapability) { + connectActionJob?.cancel() + wdttConnectFlow = WdttConnectFlow.Progress( + capability.exchange.message.ifBlank { + "Возвращаем сохранённые VK-хеши в этот профиль..." + } + ) + connectActionJob = lifecycleScope.launch { + val runningJob = coroutineContext[Job] + try { + AccessLifecycleCoordinator.restoreProfileValues( + context = this@MainActivity, + profileIndex = profile, + expectedCapability = capability, + ) + wdttConnectFlow = WdttConnectFlow.Complete( + "Сохранённые VK-хеши возвращены в профиль." + ) + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + wdttConnectFlow = WdttConnectFlow.Failed( + error.message ?: "Не удалось вернуть сохранённые VK-хеши." + ) + } finally { + if (connectActionJob === runningJob) { + connectActionJob = null + } } } } @@ -330,7 +915,7 @@ class MainActivity : ComponentActivity() { return } val hash = VkJoinLink.extractHash(sharedText) - if (hash.length < 16) { + if (!VkJoinLink.isValidHash(hash)) { sharedVkHashError = "В переданной ссылке не найден VK-хеш звонка." return } @@ -340,6 +925,15 @@ class MainActivity : ComponentActivity() { }.onSuccess { result -> sharedVkHashResult = result sharedVkHashError = null + lifecycleScope.launch { + runCatching { + AccessLifecycleCoordinator.syncProfileValues( + context = this@MainActivity, + profileIndex = result.profile, + values = result.hashes, + ) + } + } }.onFailure { error -> sharedVkHashError = error.message ?: "Не удалось сохранить VK-хеш." } @@ -392,7 +986,7 @@ private fun RoleSelectionScreen( RoleChoiceButton( title = "Я - юзер", - body = "Хочу подключиться к VPN, управлять подключением, исключениями и смотреть логи.", + body = "Хочу подключаться бесплатно по ссылке WDTT или вручную, управлять VPN, исключениями и смотреть логи.", icon = Icons.Filled.VpnKey, onClick = { onRoleSelected("user") } ) @@ -623,16 +1217,33 @@ private val navItems = listOf( NavItem(4, "Инфо", Icons.Filled.Info, Icons.Outlined.Info), ) +internal fun isMainTabVisible( + tabId: Int, + isAdminInterface: Boolean, + linkMode: Boolean, + remoteManagedProfile: Boolean, +): Boolean { + if (tabId != 1) return true + return isAdminInterface && !linkMode && !remoteManagedProfile +} + +internal fun effectiveInterfaceRole( + storedRole: String, + remoteManagedProfile: Boolean, +): String = if (remoteManagedProfile) "user" else storedRole + @OptIn(ExperimentalMaterial3Api::class) @Composable -fun MainScreen( +private fun MainScreen( settingsStore: SettingsStore, + onUiReadyForFirstDraw: () -> Unit = {}, sharedVkHashResult: VkHashInsertResult? = null, sharedVkHashError: String? = null, onSharedVkHashMessageShown: () -> Unit = {}, wdttDeepLinkMessage: String? = null, onWdttDeepLinkMessageShown: () -> Unit = {}, pendingWdttDeepLinkPlan: WdttDeepLinkApplyPlan? = null, + wdttConnectFlow: WdttConnectFlow? = null, pendingAdminTransfer: String? = null, onIncomingTransferContent: (String) -> Unit = {}, onAdminTransferDismissed: () -> Unit = {}, @@ -640,6 +1251,17 @@ fun MainScreen( onSelectWdttDeepLinkOverwriteProfile: (Int) -> Unit = {}, onConfirmWdttDeepLinkOverwrite: (WdttDeepLinkApplyPlan) -> Unit = {}, onCancelWdttDeepLinkOverwrite: () -> Unit = {}, + onSelectWdttConnectProfile: (Int) -> Unit = {}, + onConfirmWdttConnectProfile: (WdttDeepLinkApplyPlan) -> Unit = {}, + onContinueLimitedWdttSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit = { _, _ -> }, + onStartWdttConnectAction: (Int, RemoteContinuation) -> Unit = { _, _ -> }, + onCancelWdttConnectAction: () -> Unit = {}, + onSaveWdttConnectManualHashes: (Int, String) -> Unit = { _, _ -> }, + onRestoreWdttConnectHashes: (Int, RemoteAccessCapability) -> Unit = { _, _ -> }, + onVkHashesSaved: (Int, List) -> Unit = { _, _ -> }, + onSkipWdttConnectHashes: () -> Unit = {}, + onOpenWdttConnectFailureAction: (RemoteLaunchTarget) -> Unit = {}, + onDismissWdttConnectFlow: () -> Unit = {}, themeMode: String = "system", onThemeChange: (String) -> Unit = {}, isDynamicColor: Boolean = false, @@ -661,27 +1283,37 @@ fun MainScreen( val scope = rememberCoroutineScope() val updateCheckMutex = remember { Mutex() } val settingsReady by settingsStore.settingsReady.collectAsStateWithLifecycle(initialValue = false) - if (!settingsReady) { + val startupSettings by settingsStore.activeTunnelProfileUiSnapshot.collectAsStateWithLifecycle() + if (!settingsReady || startupSettings == null) { Box(modifier = Modifier.fillMaxSize()) { AppBackdrop(modifier = Modifier.matchParentSize()) } return } - val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0) - val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) - val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false) + val storedInterfaceRole = startupSettings!!.interfaceRole + val permissionOnboardingComplete = startupSettings!!.permissionOnboardingComplete + val activeProfile = startupSettings!!.profileIndex + val profileNames = startupSettings!!.profileNames + val wdttLinkMode = startupSettings!!.linkMode + val remoteManagedProfile = startupSettings!!.remoteManaged + val interfaceRole = effectiveInterfaceRole( + storedRole = storedInterfaceRole, + 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 interfaceRole by settingsStore.interfaceRole.collectAsStateWithLifecycle(initialValue = "") - val permissionOnboardingComplete by settingsStore.permissionOnboardingComplete.collectAsStateWithLifecycle(initialValue = false) val serverMigrationState by settingsStore.serverMigrationState.collectAsStateWithLifecycle(initialValue = null) val deviceCompatibilityCheckComplete by settingsStore.deviceCompatibilityCheckComplete.collectAsStateWithLifecycle( initialValue = true ) val isAdminInterface = interfaceRole == "admin" + LaunchedEffect(remoteManagedProfile) { + settingsStore.synchronizeInterfaceRoleForProfile(remoteManagedProfile) + } val isUpdatedInstall = remember(context) { runCatching { context.packageManager.getPackageInfo(context.packageName, 0).let { info -> @@ -696,6 +1328,7 @@ fun MainScreen( ) } var selectedTab by rememberSaveable { mutableIntStateOf(0) } + var projectSupportDialogRequest by remember { mutableIntStateOf(0) } val tunnelScrollPosition = rememberSaveable { mutableIntStateOf(0) } val deployScrollPosition = rememberSaveable { mutableIntStateOf(0) } val exceptionsFirstVisibleItemIndex = rememberSaveable { mutableIntStateOf(0) } @@ -826,20 +1459,28 @@ fun MainScreen( return } - val activeNavItems = remember(wdttLinkMode, isAdminInterface) { + val activeNavItems = remember( + wdttLinkMode, + isAdminInterface, + remoteManagedProfile, + ) { navItems.filter { item -> - val allowedByRole = isAdminInterface || item.id != 1 - val allowedByLinkMode = !wdttLinkMode || item.id != 1 - allowedByRole && allowedByLinkMode + isMainTabVisible( + tabId = item.id, + isAdminInterface = isAdminInterface, + linkMode = wdttLinkMode, + remoteManagedProfile = remoteManagedProfile, + ) } } val actionsExpanded = rememberSaveable { mutableStateOf(false) } val projectExpanded = rememberSaveable { mutableStateOf(false) } val tabStateHolder = rememberSaveableStateHolder() + var deployTabInitialized by rememberSaveable { mutableStateOf(false) } - LaunchedEffect(wdttLinkMode, interfaceRole) { + LaunchedEffect(wdttLinkMode, interfaceRole, remoteManagedProfile) { if (activeNavItems.none { it.id == selectedTab }) { selectedTab = 0 } @@ -865,6 +1506,7 @@ fun MainScreen( LaunchedEffect(selectedTab) { if (selectedTab == 3) TunnelManager.clearUnreadErrors() + if (selectedTab != 4) projectSupportDialogRequest = 0 } suspend fun runUpdateCheck( @@ -1031,14 +1673,21 @@ fun MainScreen( } } ) { - val deployVisible = selectedTab == 1 && !wdttLinkMode - val deployAvailable = activeNavItems.any { it.id == 1 } && !wdttLinkMode + val deployAvailable = + activeNavItems.any { it.id == 1 } && + !wdttLinkMode && + !remoteManagedProfile + val deployVisible = selectedTab == 1 && deployAvailable + val keepDeployTab = deployVisible || deployTabInitialized + LaunchedEffect(deployVisible) { + if (deployVisible) deployTabInitialized = true + } val deployAlpha by animateFloatAsState( targetValue = if (deployVisible) 1f else 0f, animationSpec = tween(durationMillis = if (deployVisible) 300 else 225), label = "deploy_tab_fade" ) - if (deployAvailable) { + if (keepDeployTab) { tabStateHolder.SaveableStateProvider("deploy_persistent") { DeployTab( scrollPosition = deployScrollPosition, @@ -1065,7 +1714,15 @@ fun MainScreen( tabStateHolder.SaveableStateProvider(tab) { when (tab) { -1 -> Spacer(modifier = Modifier.fillMaxSize()) - 0 -> SettingsTab(scrollPosition = tunnelScrollPosition) + 0 -> SettingsTab( + settingsStore = settingsStore, + scrollPosition = tunnelScrollPosition, + onVkHashesSaved = onVkHashesSaved, + onOpenProjectSupport = { + selectedTab = 4 + projectSupportDialogRequest += 1 + }, + ) 1 -> Spacer(modifier = Modifier.fillMaxSize()) 2 -> ExceptionsTab( firstVisibleItemIndex = exceptionsFirstVisibleItemIndex, @@ -1078,7 +1735,11 @@ fun MainScreen( 4 -> InfoTab( actionsExpandedState = actionsExpanded, projectExpandedState = projectExpanded, - scrollPosition = infoScrollPosition + scrollPosition = infoScrollPosition, + projectSupportDialogRequest = projectSupportDialogRequest, + onProjectSupportDialogRequestConsumed = { + projectSupportDialogRequest = 0 + }, ) } } @@ -1116,8 +1777,11 @@ fun MainScreen( scope.launch { settingsStore.saveProfileName(profile, name) } }, interfaceRole = interfaceRole, + adminModeAllowed = !remoteManagedProfile, onInterfaceRoleChange = { role -> - scope.launch { settingsStore.saveInterfaceRole(role) } + if (!remoteManagedProfile || role == "user") { + scope.launch { settingsStore.saveInterfaceRole(role) } + } }, currentTheme = themeMode, onThemeChange = onThemeChange, @@ -1141,13 +1805,14 @@ fun MainScreen( mainPassword = migrationMainPassword, sshPrivateKey = migrationSshPrivateKey ) - if ( + val serverMigrationPromptVisible = isAdminInterface && + !remoteManagedProfile && activeProfileManagesServer && migrationNotice?.noticeRequired == true && pendingUpdateCandidate == null && startupDeviceReport == null - ) { + if (serverMigrationPromptVisible) { AlertDialog( onDismissRequest = {}, properties = DialogProperties( @@ -1321,6 +1986,23 @@ fun MainScreen( ) } + wdttConnectFlow?.let { flow -> + WdttConnectActivationDialog( + flow = flow, + profileNames = profileNames, + onSelectProfile = onSelectWdttConnectProfile, + onConfirmProfile = onConfirmWdttConnectProfile, + onContinueLimitedSetup = onContinueLimitedWdttSetup, + onStartExternalAction = onStartWdttConnectAction, + onCancelExternalAction = onCancelWdttConnectAction, + onSaveManualHashes = onSaveWdttConnectManualHashes, + onRestoreSavedHashes = onRestoreWdttConnectHashes, + onSkipHashes = onSkipWdttConnectHashes, + onOpenFailureAction = onOpenWdttConnectFailureAction, + onDismiss = onDismissWdttConnectFlow, + ) + } + wdttDeepLinkMessage?.let { message -> AlertDialog( onDismissRequest = onWdttDeepLinkMessageShown, @@ -1372,6 +2054,325 @@ fun MainScreen( } } +@Composable +private fun WdttConnectActivationDialog( + flow: WdttConnectFlow, + profileNames: List, + onSelectProfile: (Int) -> Unit, + onConfirmProfile: (WdttDeepLinkApplyPlan) -> Unit, + onContinueLimitedSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit, + onStartExternalAction: (Int, RemoteContinuation) -> Unit, + onCancelExternalAction: () -> Unit, + onSaveManualHashes: (Int, String) -> Unit, + onRestoreSavedHashes: (Int, RemoteAccessCapability) -> Unit, + onSkipHashes: () -> Unit, + onOpenFailureAction: (RemoteLaunchTarget) -> Unit, + onDismiss: () -> Unit, +) { + var manualHashes by rememberSaveable { mutableStateOf("") } + var selectedHashMethod by rememberSaveable { mutableStateOf(null) } + var helpMethod by rememberSaveable { mutableStateOf(null) } + var unavailableAutoMessage by rememberSaveable { mutableStateOf(null) } + val canDismiss = flow is WdttConnectFlow.Complete || + flow is WdttConnectFlow.Failed + AlertDialog( + onDismissRequest = { + when { + flow is WdttConnectFlow.ExternalAction -> onCancelExternalAction() + canDismiss -> onDismiss() + } + }, + title = { Text("Подключение WDTT Plus") }, + text = { + AnimatedContent( + targetState = flow, + transitionSpec = { + (fadeIn(tween(120)) togetherWith fadeOut(tween(80))).using( + SizeTransform( + clip = false, + sizeAnimationSpec = { _, _ -> snap() }, + ) + ) + }, + contentKey = { it::class }, + label = "wdtt_connect_activation" + ) { state -> + when (state) { + is WdttConnectFlow.Progress -> { + Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { + CircularProgressIndicator() + Text(state.message) + } + } + is WdttConnectFlow.ExternalAction -> { + Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { + CircularProgressIndicator() + Text(state.message) + } + } + is WdttConnectFlow.SelectProfile -> { + val incomingName = WdttDeepLink.parse( + state.plan.link, + allowMissingHashes = true + )?.profileName.orEmpty() + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text("Свободных профилей нет. Выберите профиль для замены.") + if (incomingName.isNotBlank()) { + Text("Новый доступ: «$incomingName».") + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + repeat(3) { profile -> + FilterChip( + selected = state.plan.targetProfile == profile, + onClick = { onSelectProfile(profile) }, + label = { Text(vpnProfileDisplayName(profile, profileNames)) } + ) + } + } + Text( + "Подключение в выбранном профиле будет полностью заменено.", + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + ) + } + } + 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, + ) + } + } + is WdttConnectFlow.SelectHashes -> { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text("Выберите способ заполнения VK-хешей для нового профиля.") + 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) { + "Войти в VK при необходимости и создать ссылки" + } else { + "Недоступно — нажмите, чтобы узнать, что делать" + }, + onHelp = { helpMethod = "auto" }, + onClick = { + if (state.continuation.available) { + onStartExternalAction(state.profile, state.continuation) + } else { + unavailableAutoMessage = state.continuation.message.ifBlank { + "Автоматическое получение сейчас недоступно." + } + } + } + ) + HashMethodRow( + title = "Заполнить вручную", + body = "Вставить 1-4 хеша или ссылки VK Звонков", + onHelp = { helpMethod = "manual" }, + onClick = { selectedHashMethod = "manual" } + ) + if (selectedHashMethod == "manual") { + OutlinedTextField( + value = manualHashes, + onValueChange = { manualHashes = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text("VK-хеши или ссылки") }, + minLines = 2, + maxLines = 4 + ) + } + } + } + is WdttConnectFlow.Complete -> Text(state.message) + is WdttConnectFlow.Failed -> Text(state.message) + } + } + }, + confirmButton = { + when (flow) { + is WdttConnectFlow.SelectProfile -> { + TextButton(onClick = { onConfirmProfile(flow.plan) }) { + Text("Сохранить") + } + } + is WdttConnectFlow.ConfirmLimitedSetup -> { + TextButton( + onClick = { + onContinueLimitedSetup(flow.plan, flow.delivery) + } + ) { + Text("Продолжить") + } + } + is WdttConnectFlow.SelectHashes -> { + if (selectedHashMethod == "manual") { + TextButton( + enabled = manualHashes.isNotBlank(), + onClick = { onSaveManualHashes(flow.profile, manualHashes) } + ) { + Text("Сохранить вручную") + } + } + } + is WdttConnectFlow.Complete -> { + TextButton(onClick = onDismiss) { + Text("Готово") + } + } + is WdttConnectFlow.Failed -> { + val action = flow.action + TextButton( + onClick = { + if (action == null) onDismiss() else onOpenFailureAction(action.target) + } + ) { + Text(action?.label ?: "Готово") + } + } + is WdttConnectFlow.ExternalAction -> Unit + is WdttConnectFlow.Progress -> Unit + } + }, + dismissButton = { + when (flow) { + is WdttConnectFlow.SelectProfile -> { + TextButton(onClick = onDismiss) { + Text("Позже") + } + } + is WdttConnectFlow.ConfirmLimitedSetup -> { + TextButton(onClick = onDismiss) { + Text("Отмена") + } + } + is WdttConnectFlow.ExternalAction -> { + TextButton(onClick = onCancelExternalAction) { + Text("Назад") + } + } + is WdttConnectFlow.SelectHashes -> { + TextButton(onClick = onSkipHashes) { + Text("Пропустить") + } + } + is WdttConnectFlow.Failed -> { + if (flow.action != null) { + TextButton(onClick = onDismiss) { + Text("Закрыть") + } + } + } + else -> Unit + } + } + ) + + helpMethod?.let { method -> + AlertDialog( + onDismissRequest = { helpMethod = null }, + title = { + Text( + when (method) { + "auto" -> "Автоматически" + "restore" -> "Вернуть хеши" + else -> "Вручную" + } + ) + }, + text = { + Text( + when (method) { + "auto" -> { + "WDTT Plus откроет официальное мини-приложение VK. Если вы ещё не " + + "вошли, VK сначала покажет свою форму входа, а затем вернёт вас к " + + "созданию ссылок. Пароль VK не передаётся WDTT Plus." + } + "restore" -> { + "WDTT Plus безопасно вернёт хеши, ранее сохранённые именно для " + + "этого готового профиля. Хеши других ваших профилей не используются." + } + else -> { + "Создайте или скопируйте до четырёх ссылок-приглашений VK Звонков, " + + "либо вставьте готовые хеши. Разделяйте значения пробелом, запятой " + + "или новой строкой." + } + } + ) + }, + confirmButton = { + TextButton(onClick = { helpMethod = null }) { Text("Понятно") } + } + ) + } + + unavailableAutoMessage?.let { message -> + AlertDialog( + onDismissRequest = { unavailableAutoMessage = null }, + title = { Text("Автоматическое получение недоступно") }, + text = { + Text( + "$message\n\nСейчас можно заполнить VK-хеши вручную или пропустить этот шаг." + ) + }, + confirmButton = { + TextButton(onClick = { unavailableAutoMessage = null }) { + Text("Понятно") + } + } + ) + } +} + +@Composable +private fun HashMethodRow( + title: String, + body: String, + onHelp: () -> Unit, + onClick: () -> Unit, +) { + Surface( + onClick = onClick, + shape = RoundedCornerShape(10.dp), + color = MaterialTheme.colorScheme.surfaceVariant, + modifier = Modifier.fillMaxWidth() + ) { + Row( + modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + Column(modifier = Modifier.weight(1f)) { + Text(title, fontWeight = FontWeight.SemiBold) + Text(body, style = MaterialTheme.typography.bodySmall) + } + IconButton(onClick = onHelp) { + Icon(Icons.Filled.Info, contentDescription = "Как это работает") + } + } + } +} + @Composable private fun SharedVkHashDialog( result: VkHashInsertResult, diff --git a/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt b/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt index 7302bd6..fd3cc78 100644 --- a/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt +++ b/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt @@ -1,5 +1,6 @@ package com.wdtt.plus +import android.annotation.SuppressLint import android.app.PendingIntent import android.content.Intent import android.graphics.drawable.Icon @@ -33,9 +34,19 @@ class QuickToggleTileService : TileService() { TunnelManager.running, TrustedWifiManager.state, settingsStore.activeProfile, - settingsStore.profileNames - ) { running, trustedWifi, activeProfile, profileNames -> - TileUiState(running, trustedWifi, activeProfile, profileNames) + TunnelManager.activeTunnelProfile, + settingsStore.profileNames, + ) { running, trustedWifi, selectedProfile, activeTunnelProfile, profileNames -> + TileUiState( + running, + trustedWifi, + selectedProfile, + activeTunnelProfile, + profileNames, + AccessLifecycleUiState.Unmanaged, + ) + }.combine(settingsStore.activeAccessLifecycle) { state, accessLifecycle -> + state.copy(accessLifecycle = accessLifecycle) }.collect { uiState -> updateTile(uiState) } @@ -53,39 +64,53 @@ class QuickToggleTileService : TileService() { override fun onClick() { super.onClick() runCatching { - if (TunnelManager.running.value || TrustedWifiManager.state.value.waiting) { - // Если запущен — останавливаем. Состояние плитки изменится автоматически, - // когда TunnelManager остановит процессы и обновит статус running в false. - val stopIntent = Intent(this, TunnelService::class.java).apply { action = "STOP" } - startService(stopIntent) - return - } + when ( + tunnelToggleAction( + running = TunnelManager.running.value, + trustedWifiWaiting = TrustedWifiManager.state.value.waiting, + vpnPermissionRequired = VpnService.prepare(this) != null, + ) + ) { + TunnelToggleAction.STOP -> { + // Состояние плитки изменится после фактической остановки службы. + startService( + Intent(this, TunnelService::class.java).apply { action = "STOP" } + ) + } + TunnelToggleAction.REQUEST_VPN_PERMISSION -> { + Toast.makeText( + this, + "Откройте WDTT Plus и выдайте VPN-разрешение", + Toast.LENGTH_LONG + ).show() + openMainActivity() + } + TunnelToggleAction.START -> scope.launch { + try { + val intent = buildTunnelStartIntentFromSettings(this@QuickToggleTileService) + if (intent == null) { + Toast.makeText( + this@QuickToggleTileService, + "Заполните настройки подключения в WDTT Plus", + Toast.LENGTH_LONG + ).show() + openMainActivity() + return@launch + } - // Проверяем наличие выданного разрешения VPN перед стартом - if (VpnService.prepare(this) != null) { - Toast.makeText(this, "Откройте WDTT Plus и выдайте VPN-разрешение", Toast.LENGTH_LONG).show() - openMainActivity() - return - } - - // Запускаем старт туннеля в фоне - scope.launch { - try { - val intent = buildTunnelStartIntentFromSettings(this@QuickToggleTileService) - if (intent == null) { - Toast.makeText(this@QuickToggleTileService, "Заполните настройки подключения в WDTT Plus", Toast.LENGTH_LONG).show() - openMainActivity() - return@launch + if (Build.VERSION.SDK_INT >= 26) { + startForegroundService(intent) + } else { + startService(intent) + } + } catch (e: Exception) { + Log.e("QuickToggleTile", "Failed to start tunnel via QS tile", e) + Toast.makeText( + this@QuickToggleTileService, + "Ошибка запуска: ${e.localizedMessage}", + Toast.LENGTH_SHORT + ).show() } - - if (Build.VERSION.SDK_INT >= 26) { - startForegroundService(intent) - } else { - startService(intent) - } - } catch (e: Exception) { - Log.e("QuickToggleTile", "Failed to start tunnel via QS tile", e) - Toast.makeText(this@QuickToggleTileService, "Ошибка запуска: ${e.localizedMessage}", Toast.LENGTH_SHORT).show() } } }.onFailure { e -> @@ -102,12 +127,21 @@ class QuickToggleTileService : TileService() { runCatching { val running = uiState.running val waiting = uiState.trustedWifi.waiting - val activeProfile = uiState.activeProfile val profileNames = uiState.profileNames - val profile = activeProfile.coerceIn(0, 2) + val profile = displayedTunnelProfile( + selectedProfile = uiState.selectedProfile, + activeTunnelProfile = uiState.activeTunnelProfile, + running = running, + trustedWifiWaiting = waiting, + ) val profileLabel = vpnProfileDisplayName(profile, profileNames) val defaultProfileLabel = vpnProfileDefaultName(profile) val profileIsDefault = profileLabel == defaultProfileLabel + val accessBlocked = + uiState.accessLifecycle.managed && + !uiState.accessLifecycle.allowConnect && + !running && + !waiting qsTile?.apply { label = when { waiting -> "Ожидание" @@ -121,6 +155,8 @@ class QuickToggleTileService : TileService() { subtitle = when { waiting -> uiState.trustedWifi.ssid.ifBlank { "Wi-Fi" } running -> "" + accessBlocked -> uiState.accessLifecycle.title + .ifBlank { uiState.accessLifecycle.fallbackTitle() } else -> "Отключено" } } @@ -134,10 +170,13 @@ class QuickToggleTileService : TileService() { private data class TileUiState( val running: Boolean, val trustedWifi: TrustedWifiRuntimeState, - val activeProfile: Int, - val profileNames: List + val selectedProfile: Int, + val activeTunnelProfile: Int?, + val profileNames: List, + val accessLifecycle: AccessLifecycleUiState, ) + @SuppressLint("StartActivityAndCollapseDeprecated") private fun openMainActivity() { runCatching { val intent = Intent(this, MainActivity::class.java).apply { diff --git a/app/src/main/java/com/wdtt/plus/RemoteActionCatalog.kt b/app/src/main/java/com/wdtt/plus/RemoteActionCatalog.kt new file mode 100644 index 0000000..aa54cea --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/RemoteActionCatalog.kt @@ -0,0 +1,407 @@ +package com.wdtt.plus + +import android.content.Context +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URI +import java.net.URL +import java.util.UUID + +/** + * Provider-neutral UI action prepared by a remote service. + * + * The application does not interpret the destination or reconstruct either + * URL. It only validates the generic HTTPS boundary and opens the exact + * backend-provided target. + */ +data class RemoteUiAction( + val title: String, + val message: String, + val label: String, + val target: RemoteLaunchTarget, + val confirmationTitle: String = "", + val confirmationMessage: String = "", + val confirmationLabel: String = "", + val progressLabel: String = "", + val preparingMessage: String = "", + val stoppingMessage: String = "", + val openingMessage: String = "", + val successMessage: String = "", + val cancelledMessage: String = "", + val failureMessage: String = "", + val compactMessage: String = "", + val compactLabel: String = "", + val compactLinkText: String = "", + val compactButtonVisible: Boolean = true, + val cancelLabel: String = "", + val form: RemoteActionForm? = null, +) + +data class RemoteActionFormChoice( + val label: String, + val value: String, +) + +data class RemoteActionForm( + val token: String, + val submitUrl: String, + val title: String, + val message: String, + val choices: List, + val inputLabel: String, + val inputSuffix: String, + val initialValue: String, + val minimum: Long, + val maximum: Long, + val maxCharacters: Int, + val supportingText: String, + val invalidText: String, + val submitLabel: String, + val busyLabel: String, + val failureMessage: String, + val fallbackLabel: String, +) + +class RemoteActionExecutionException(message: String) : IllegalStateException(message) + +data class RemoteActionCatalog( + val actions: Map = emptyMap(), +) { + fun at(placement: String): RemoteUiAction? = actions[placement] + + companion object { + val Empty = RemoteActionCatalog() + } +} + +object RemoteActionCatalogGateway { + private const val CACHE_TTL_MS = 10 * 60 * 1000L + private const val MAX_RESPONSE_CHARS = 32 * 1024 + private val placements = setOf("tunnel", "profile", "about") + + @Volatile + private var cachedAt = 0L + + @Volatile + private var cachedCatalog = RemoteActionCatalog.Empty + + fun hasFreshCache(): Boolean = + System.currentTimeMillis() - cachedAt in 0 until CACHE_TTL_MS + + fun cached(): RemoteActionCatalog = + if (hasFreshCache()) cachedCatalog else RemoteActionCatalog.Empty + + suspend fun fetch(force: Boolean = false): RemoteActionCatalog { + val now = System.currentTimeMillis() + if (!force && now - cachedAt in 0 until CACHE_TTL_MS) return cachedCatalog + return withContext(Dispatchers.IO) { + val current = System.currentTimeMillis() + if (!force && current - cachedAt in 0 until CACHE_TTL_MS) { + return@withContext cachedCatalog + } + val received = runCatching { request() }.getOrDefault(RemoteActionCatalog.Empty) + cachedCatalog = received + cachedAt = current + received + } + } + + suspend fun fetchQuestionAction(): RemoteUiAction? = + withContext(Dispatchers.IO) { + runCatching { request(context = "question").at("about") }.getOrNull() + } + + suspend fun execute( + form: RemoteActionForm, + requestId: String, + value: String, + ): RemoteLaunchTarget = withContext(Dispatchers.IO) { + require(validOpaqueToken(form.token)) { "Действие устарело. Обновите экран." } + require(safeExternalUrl(form.submitUrl)) { "Получен небезопасный адрес действия." } + require(runCatching { UUID.fromString(requestId) }.isSuccess) { + "Не удалось подготовить действие." + } + require(value.length in 1..32) { form.invalidText } + var connection: HttpURLConnection? = null + try { + connection = URL(form.submitUrl).openConnection() as HttpURLConnection + connection.requestMethod = "POST" + connection.instanceFollowRedirects = false + connection.connectTimeout = 7_000 + connection.readTimeout = 12_000 + connection.doOutput = true + connection.setRequestProperty("Accept", "application/json") + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8") + val payload = JSONObject() + .put("token", form.token) + .put("request_id", requestId) + .put("value", value) + .put("client", BuildConfig.VERSION_NAME) + .put("system", android.os.Build.VERSION.RELEASE.orEmpty()) + .toString() + .toByteArray(Charsets.UTF_8) + connection.outputStream.use { it.write(payload) } + val status = connection.responseCode + val stream = if (status in 200..299) { + connection.inputStream + } else { + connection.errorStream + } + val body = stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty() + if (status !in 200..299) { + val detail = runCatching { + JSONObject(body).optString("detail").trim().take(240) + }.getOrDefault("") + throw RemoteActionExecutionException( + detail.ifBlank { form.failureMessage } + ) + } + parseExecutionTarget(body) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: RemoteActionExecutionException) { + throw error + } catch (error: Exception) { + throw RemoteActionExecutionException(form.failureMessage) + } finally { + connection?.disconnect() + } + } + + private fun request(context: String? = null): RemoteActionCatalog { + var connection: HttpURLConnection? = null + return try { + val query = buildList { + if (BuildConfig.REMOTE_ACTION_PREVIEW) add("preview=1") + if (context == "question") add("context=question") + }.joinToString("&").let { if (it.isBlank()) "" else "?$it" } + connection = URL( + "https://${BuildConfig.WDTT_PLUS_DOMAIN}/api/client/actions$query" + ).openConnection() as HttpURLConnection + connection.requestMethod = "GET" + connection.instanceFollowRedirects = false + connection.connectTimeout = 5_000 + connection.readTimeout = 6_000 + connection.setRequestProperty("Accept", "application/json") + val status = connection.responseCode + if (status !in 200..299) return RemoteActionCatalog.Empty + parse(connection.inputStream.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }) + } finally { + connection?.disconnect() + } + } + + internal fun parse(body: String): RemoteActionCatalog { + if (body.length > MAX_RESPONSE_CHARS) return RemoteActionCatalog.Empty + val root = runCatching { JSONObject(body) }.getOrNull() + ?: return RemoteActionCatalog.Empty + if (root.optInt("version", 0) != 1) return RemoteActionCatalog.Empty + val source = root.optJSONObject("actions") ?: return RemoteActionCatalog.Empty + val actions = placements.mapNotNull { placement -> + val item = source.optJSONObject(placement) ?: return@mapNotNull null + parseAction(item)?.let { placement to it } + }.toMap() + return RemoteActionCatalog(actions) + } + + private fun parseAction(item: JSONObject): RemoteUiAction? { + val title = item.optString("title").trim().take(120) + val message = item.optString("message").trim().take(400) + val label = item.optString("label").trim().take(80) + val confirmationTitle = item.optString("confirmation_title").trim().take(120) + val confirmationMessage = item.optString("confirmation_message").trim().take(1600) + val confirmationLabel = item.optString("confirmation_label").trim().take(80) + val progressLabel = item.optString("progress_label").trim().take(80) + val preparingMessage = item.optString("preparing_message").trim().take(240) + val stoppingMessage = item.optString("stopping_message").trim().take(240) + val openingMessage = item.optString("opening_message").trim().take(240) + val successMessage = item.optString("success_message").trim().take(400) + val cancelledMessage = item.optString("cancelled_message").trim().take(240) + val failureMessage = item.optString("failure_message").trim().take(240) + val compactMessage = item.optString("compact_message").trim().take(400) + val compactLabel = item.optString("compact_label").trim().take(80) + val compactLinkText = item.optString("compact_link_text").trim().take(120) + val compactButtonVisible = item.optBoolean("compact_button_visible", true) + val cancelLabel = item.optString("cancel_label").trim().take(80) + val primary = item.optString("url").trim() + val fallback = item.optString("fallback").trim() + val handler = item.optString("handler").trim() + val alternateHandlers = parseAlternateHandlers(item) ?: return null + val formSource = item.optJSONObject("form") + val form = formSource?.let(::parseForm) + if (title.isBlank() || message.isBlank() || label.isBlank()) return null + if (!safeExternalUrl(primary)) return null + if (fallback.isNotBlank() && !safeExternalUrl(fallback)) return null + if (handler.isNotBlank() && !safePackageName(handler)) return null + if (formSource != null && form == null) return null + return RemoteUiAction( + title = title, + message = message, + label = label, + confirmationTitle = confirmationTitle, + confirmationMessage = confirmationMessage, + confirmationLabel = confirmationLabel, + progressLabel = progressLabel, + preparingMessage = preparingMessage, + stoppingMessage = stoppingMessage, + openingMessage = openingMessage, + successMessage = successMessage, + cancelledMessage = cancelledMessage, + failureMessage = failureMessage, + compactMessage = compactMessage, + compactLabel = compactLabel, + compactLinkText = compactLinkText, + compactButtonVisible = compactButtonVisible, + cancelLabel = cancelLabel, + form = form, + target = RemoteLaunchTarget( + primaryUrl = primary, + fallbackUrl = fallback, + preferredHandler = handler, + alternateHandlers = alternateHandlers, + ), + ) + } + + private fun parseForm(item: JSONObject): RemoteActionForm? { + val token = item.optString("token").trim() + val submitUrl = item.optString("submit_url").trim() + val title = item.optString("title").trim().take(120) + val message = item.optString("message").trim().take(600) + val inputLabel = item.optString("input_label").trim().take(80) + val inputSuffix = item.optString("input_suffix").trim().take(16) + val initialValue = item.optString("initial_value").trim().take(32) + val minimum = item.optLong("minimum", Long.MIN_VALUE) + val maximum = item.optLong("maximum", Long.MIN_VALUE) + val maxCharacters = item.optInt("max_characters", 0) + val supportingText = item.optString("supporting_text").trim().take(160) + val invalidText = item.optString("invalid_text").trim().take(160) + val submitLabel = item.optString("submit_label").trim().take(120) + val busyLabel = item.optString("busy_label").trim().take(80) + val failureMessage = item.optString("failure_message").trim().take(240) + val fallbackLabel = item.optString("fallback_label").trim().take(80) + val choicesSource = item.optJSONArray("choices") ?: return null + if ( + !validOpaqueToken(token) || + !safeExternalUrl(submitUrl) || + title.isBlank() || + message.isBlank() || + inputLabel.isBlank() || + initialValue.isBlank() || + minimum < 0 || + maximum < minimum || + maximum > 1_000_000_000L || + maxCharacters !in 1..12 || + supportingText.isBlank() || + invalidText.isBlank() || + submitLabel.isBlank() || + busyLabel.isBlank() || + failureMessage.isBlank() || + fallbackLabel.isBlank() || + choicesSource.length() !in 1..8 + ) { + return null + } + val initialNumber = initialValue.toLongOrNull() ?: return null + if (initialNumber !in minimum..maximum) return null + val choices = (0 until choicesSource.length()).mapNotNull { index -> + val choice = choicesSource.optJSONObject(index) ?: return@mapNotNull null + val choiceLabel = choice.optString("label").trim().take(40) + val choiceValue = choice.optString("value").trim() + if (choiceLabel.isBlank() || choiceValue.length !in 1..256) { + null + } else { + RemoteActionFormChoice(choiceLabel, choiceValue) + } + } + if (choices.size != choicesSource.length()) return null + return RemoteActionForm( + token = token, + submitUrl = submitUrl, + title = title, + message = message, + choices = choices, + inputLabel = inputLabel, + inputSuffix = inputSuffix, + initialValue = initialValue, + minimum = minimum, + maximum = maximum, + maxCharacters = maxCharacters, + supportingText = supportingText, + invalidText = invalidText, + submitLabel = submitLabel, + busyLabel = busyLabel, + failureMessage = failureMessage, + fallbackLabel = fallbackLabel, + ) + } + + internal fun parseExecutionTarget(body: String): RemoteLaunchTarget { + if (body.length > MAX_RESPONSE_CHARS) { + throw RemoteActionExecutionException("Получен слишком большой ответ.") + } + val root = runCatching { JSONObject(body) }.getOrNull() + ?: throw RemoteActionExecutionException("Получен некорректный ответ.") + if (root.optInt("version", 0) != 1) { + throw RemoteActionExecutionException("Версия ответа не поддерживается.") + } + val primary = root.optString("url").trim() + val fallback = root.optString("fallback").trim() + val handler = root.optString("handler").trim() + val alternateHandlers = parseAlternateHandlers(root) + ?: throw RemoteActionExecutionException("Получены небезопасные обработчики действия.") + if ( + !safeExternalUrl(primary) || + (fallback.isNotBlank() && !safeExternalUrl(fallback)) || + (handler.isNotBlank() && !safePackageName(handler)) + ) { + throw RemoteActionExecutionException("Получен небезопасный адрес действия.") + } + return RemoteLaunchTarget( + primaryUrl = primary, + fallbackUrl = fallback, + preferredHandler = handler, + alternateHandlers = alternateHandlers, + ) + } + + private fun validOpaqueToken(value: String): Boolean = + value.length in 24..256 && Regex("^[A-Za-z0-9._-]+$").matches(value) + + private fun safeExternalUrl(value: String): Boolean { + if (value.length !in 1..2048) return false + val uri = runCatching { URI(value) }.getOrNull() ?: return false + return uri.scheme.equals("https", ignoreCase = true) && + !uri.host.isNullOrBlank() && + uri.rawUserInfo.isNullOrBlank() && + (uri.port == -1 || uri.port == 443) + } + + private fun safePackageName(value: String): Boolean = + value.length in 3..255 && + Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value) + + private fun parseAlternateHandlers(item: JSONObject): List? { + val handlers = item.optJSONArray("alternate_handlers") ?: return emptyList() + if (handlers.length() > 7) return null + return (0 until handlers.length()) + .map { index -> handlers.optString(index).trim() } + .takeIf { values -> + values.all { it.isNotBlank() && safePackageName(it) } && + values.distinct().size == values.size + } + } +} + +object RemoteUiActionLauncher { + suspend fun open(context: Context, action: RemoteUiAction): Boolean = + withContext(Dispatchers.Main.immediate) { + runCatching { + RemoteContinuationLauncher.launch(context, action.target) + true + }.getOrDefault(false) + } +} diff --git a/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt b/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt new file mode 100644 index 0000000..1288608 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt @@ -0,0 +1,276 @@ +package com.wdtt.plus + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.Uri +import androidx.activity.result.ActivityResultLauncher +import androidx.browser.auth.AuthTabIntent +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URI +import java.net.URL +import java.net.URLDecoder + +data class RemoteLaunchTarget( + val primaryUrl: String, + val fallbackUrl: String = "", + val preferredHandler: String = "", + val alternateHandlers: List = emptyList(), + val returnScheme: String = "", +) { + internal fun handlerPackages(): List = + (listOf(preferredHandler) + alternateHandlers) + .filter(String::isNotBlank) + .distinct() +} + +object RemoteContinuationLauncher { + suspend fun begin(capability: RemoteContinuation, device: String): RemoteLaunchTarget { + require(capability.available && opaqueValue(capability.key)) { + "Автоматическое заполнение недоступно для этого профиля." + } + require(safeServiceUrl(capability.url)) { "Автоматическое заполнение сейчас недоступно." } + require(validDevice(device)) { "Не удалось определить текущее устройство." } + return withContext(Dispatchers.IO) { + val payload = JSONObject() + .put("key", capability.key.trim()) + .put("device", device.trim()) + .put("return_transport", "auth_tab") + .toString() + .toByteArray(Charsets.UTF_8) + var connection: HttpURLConnection? = null + try { + connection = URL(capability.url).openConnection() as HttpURLConnection + connection.requestMethod = "POST" + connection.connectTimeout = 10_000 + connection.readTimeout = 15_000 + connection.doOutput = true + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8") + connection.setRequestProperty("Accept", "application/json") + connection.outputStream.use { it.write(payload) } + val status = connection.responseCode + val body = readBody(connection, status) + if (status !in 200..299) { + val detail = runCatching { JSONObject(body).optString("detail") }.getOrDefault("") + throw IllegalStateException( + detail.ifBlank { "Не удалось продолжить действие. Откройте свежую ссылку подключения." } + ) + } + val response = runCatching { JSONObject(body) } + .getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") } + val primary = response.optString("url").trim() + val fallback = response.optString("fallback").trim() + val handler = response.optString("handler").trim() + val alternateHandlers = parseAlternateHandlers(response) + val returnScheme = response.optString("return_scheme").trim() + require(safeExternalUrl(primary)) { + "WDTT Plus вернул повреждённый адрес продолжения." + } + require(fallback.isBlank() || safeExternalUrl(fallback)) { + "WDTT Plus вернул повреждённый резервный адрес." + } + require(handler.isBlank() || safePackageName(handler)) { + "WDTT Plus вернул повреждённый обработчик продолжения." + } + require(alternateHandlers != null) { + "WDTT Plus вернул повреждённые резервные обработчики." + } + require(returnScheme.isBlank() || returnScheme == AUTH_TAB_RETURN_SCHEME) { + "WDTT Plus вернул повреждённый способ возврата." + } + RemoteLaunchTarget( + primaryUrl = primary, + fallbackUrl = fallback, + preferredHandler = handler, + alternateHandlers = alternateHandlers, + returnScheme = returnScheme, + ) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + if (error is IllegalStateException) throw error + throw IllegalStateException( + "Не удалось связаться с WDTT Plus. Проверьте интернет и повторите попытку." + ) + } finally { + connection?.disconnect() + } + } + } + + fun launch( + context: Context, + target: RemoteLaunchTarget, + authTabLauncher: ActivityResultLauncher? = null, + ) { + require(safeExternalUrl(target.primaryUrl)) { "Адрес продолжения повреждён." } + val handlerPackages = target.handlerPackages() + require(handlerPackages.size <= MAX_HANDLER_PACKAGES) { + "Получено слишком много обработчиков продолжения." + } + handlerPackages.forEach { handler -> + require(safePackageName(handler)) { "Обработчик продолжения повреждён." } + try { + context.startActivity( + Intent(Intent.ACTION_VIEW, Uri.parse(target.primaryUrl)).apply { + addCategory(Intent.CATEGORY_BROWSABLE) + setPackage(handler) + } + ) + return + } catch (_: ActivityNotFoundException) { + // The fallback preserves the remote operation when its preferred app is unavailable. + } catch (_: SecurityException) { + // Some Android builds reject explicit package launches; use the browser below. + } + } + if (target.returnScheme == AUTH_TAB_RETURN_SCHEME && authTabLauncher != null) { + AuthTabIntent.Builder() + .build() + .launch( + authTabLauncher, + Uri.parse(authTabLaunchUrl(target)), + AUTH_TAB_RETURN_SCHEME, + ) + return + } + var lastFailure: Exception? = null + for (browserUrl in browserLaunchUrls(target)) { + try { + context.startActivity( + Intent(Intent.ACTION_VIEW, Uri.parse(browserUrl)).apply { + addCategory(Intent.CATEGORY_BROWSABLE) + } + ) + return + } catch (error: ActivityNotFoundException) { + lastFailure = error + } catch (error: SecurityException) { + lastFailure = error + } + } + throw IllegalStateException( + "Не удалось открыть VK или страницу продолжения. Проверьте приложение VK и браузер.", + lastFailure, + ) + } + + internal fun authTabLaunchUrl(target: RemoteLaunchTarget): String = + browserLaunchUrls(target).first() + + internal fun browserLaunchUrls(target: RemoteLaunchTarget): List = + ( + if (target.handlerPackages().isNotEmpty() && target.fallbackUrl.isNotBlank()) { + listOf(target.fallbackUrl, target.primaryUrl) + } else { + listOf(target.primaryUrl, target.fallbackUrl) + } + ) + .filter { it.isNotBlank() } + .onEach { + require(safeExternalUrl(it)) { "Резервный адрес продолжения повреждён." } + } + .distinct() + + internal fun callbackDocumentUri(callback: Uri?): Uri? { + val document = callbackDocumentUrl(callback?.toString().orEmpty()) ?: return null + return Uri.parse(document) + } + + internal fun isCancellationCallback(callback: Uri?): Boolean = + isCancellationCallback(callback?.toString().orEmpty()) + + internal fun isCancellationCallback(rawCallback: String): Boolean { + val uri = runCatching { URI(rawCallback.trim()) }.getOrNull() ?: return false + return uri.scheme.equals(AUTH_TAB_RETURN_SCHEME, ignoreCase = true) && + uri.host.equals("return", ignoreCase = true) && + uri.port == -1 && + uri.rawUserInfo.isNullOrBlank() && + uri.path.orEmpty().isBlank() && + uri.rawQuery.isNullOrBlank() && + uri.rawFragment.isNullOrBlank() + } + + internal fun callbackDocumentUrl(rawCallback: String): String? { + val callback = runCatching { URI(rawCallback.trim()) }.getOrNull() ?: return null + if ( + !callback.scheme.equals(AUTH_TAB_RETURN_SCHEME, ignoreCase = true) || + !callback.host.equals("return", ignoreCase = true) || + callback.port != -1 || + !callback.rawUserInfo.isNullOrBlank() || + !callback.rawFragment.isNullOrBlank() || + callback.path.orEmpty().isNotBlank() + ) { + return null + } + val documents = callback.rawQuery.orEmpty() + .split('&') + .mapNotNull { item -> + val separator = item.indexOf('=') + if (separator <= 0) return@mapNotNull null + val key = URLDecoder.decode( + item.substring(0, separator), + Charsets.UTF_8.name(), + ) + if (key != "document") return@mapNotNull null + URLDecoder.decode( + item.substring(separator + 1), + Charsets.UTF_8.name(), + ) + } + val document = documents.singleOrNull()?.trim().orEmpty() + return RemoteDocumentGateway.extractLink(document)?.url + } + + private fun safeServiceUrl(value: String): Boolean { + val uri = runCatching { URI(value) }.getOrNull() ?: return false + return uri.scheme.equals("https", ignoreCase = true) && + uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) && + uri.rawUserInfo.isNullOrBlank() && + uri.rawQuery.isNullOrBlank() && + uri.rawFragment.isNullOrBlank() && + (uri.port == -1 || uri.port == 443) + } + + private fun safeExternalUrl(value: String): Boolean { + val uri = runCatching { URI(value) }.getOrNull() ?: return false + return uri.scheme.equals("https", ignoreCase = true) && + !uri.host.isNullOrBlank() && + uri.rawUserInfo.isNullOrBlank() && + (uri.port == -1 || uri.port == 443) + } + + private fun safePackageName(value: String): Boolean = + value.length in 3..255 && + Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value) + + private fun parseAlternateHandlers(source: JSONObject): List? { + val handlers = source.optJSONArray("alternate_handlers") ?: return emptyList() + if (handlers.length() > MAX_HANDLER_PACKAGES - 1) return null + return (0 until handlers.length()) + .map { index -> handlers.optString(index).trim() } + .takeIf { values -> + values.all { it.isNotBlank() && safePackageName(it) } && + values.distinct().size == values.size + } + } + + private fun opaqueValue(value: String): Boolean = + value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value) + + private fun validDevice(value: String): Boolean = + Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim()) + + private fun readBody(connection: HttpURLConnection, status: Int): String { + val stream = if (status in 200..299) connection.inputStream else connection.errorStream + return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_BYTES) }.orEmpty() + } + + private const val AUTH_TAB_RETURN_SCHEME = "wdtt" + private const val MAX_HANDLER_PACKAGES = 8 + private const val MAX_RESPONSE_BYTES = 32 * 1024 +} diff --git a/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt b/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt new file mode 100644 index 0000000..3759bc9 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt @@ -0,0 +1,388 @@ +package com.wdtt.plus + +import android.net.Uri +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONArray +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URI +import java.net.URL +import java.util.TimeZone + +data class RemoteDocumentLink(val url: String) + +data class RemoteDocumentFailureAction( + val label: String, + val target: RemoteLaunchTarget, +) + +class RemoteDocumentFailure( + message: String, + val action: RemoteDocumentFailureAction? = null, +) : IllegalStateException(message) + +data class RemoteContinuation( + val available: Boolean, + val key: String = "", + val url: String = "", + val expiresAt: Long = 0, + val message: String = "" +) + +enum class RemoteDocumentKind { + BASE, + UPDATE +} + +data class RemoteDocumentDelivery( + val document: String, + val binding: String, + val continuation: RemoteContinuation, + val access: RemoteAccessCapability, + val kind: RemoteDocumentKind, + val profileMaxWorkers: Int = 0, + val profileRevision: Long = 0, +) + +internal fun RemoteDocumentDelivery.shouldPreserveLocalVkHashes( + existingProfileRedelivery: Boolean = false, +): Boolean { + val deliveredHashes = WdttDeepLink.parse(document, allowMissingHashes = true) + ?.hashes + .orEmpty() + return deliveredHashes.isBlank() && + ( + kind == RemoteDocumentKind.UPDATE || + (kind == RemoteDocumentKind.BASE && existingProfileRedelivery) + ) +} + +internal fun RemoteDocumentDelivery.requiresInitialContinuationWarning( + existingProfileHasVkHashes: Boolean = false, +): Boolean = + kind == RemoteDocumentKind.BASE && + !continuation.available && + !existingProfileHasVkHashes + +object RemoteDocumentGateway { + private const val MAX_RESPONSE_CHARS = 32 * 1024 + + fun extractLink(uri: Uri): RemoteDocumentLink? = extractLink(uri.toString()) + + fun extractLink(rawUri: String): RemoteDocumentLink? { + val uri = runCatching { URI(rawUri.trim()) }.getOrNull() ?: return null + val path = uri.path.orEmpty() + val code = path.takeIf { it.startsWith("/c/") } + ?.removePrefix("/c/") + ?.trim() + .orEmpty() + val navigationMarkerValid = uri.rawQuery.isNullOrBlank() || + Regex("^open=[0-9]{1,20}$").matches(uri.rawQuery) + val valid = trustedServiceUri(uri) && + navigationMarkerValid && + uri.rawFragment.isNullOrBlank() && + Regex("^[A-Za-z0-9_-]{6,64}$").matches(code) + if (!valid) return null + return RemoteDocumentLink("https://${BuildConfig.WDTT_PLUS_DOMAIN}/c/$code") + } + + suspend fun receive( + link: RemoteDocumentLink, + device: String, + label: String, + client: String, + system: String, + localBindings: Collection? = null, + ): RemoteDocumentDelivery { + require(extractLink(link.url) != null) { "Ссылка повреждена или неполна." } + require(validDevice(device)) { "Не удалось определить текущее устройство." } + return withContext(Dispatchers.IO) { + val request = JSONObject() + .put("device", device.trim()) + .put("label", label.trim().take(160)) + .put("client", client.trim().take(64)) + .put("system", system.trim().take(64)) + .put("timezone", TimeZone.getDefault().id.take(64)) + if (localBindings != null) { + val bindings = localBindings + .map(String::trim) + .filter(::opaqueValue) + .distinct() + .take(6) + request.put("bindings", JSONArray(bindings)) + } + val payload = request + .toString() + .toByteArray(Charsets.UTF_8) + var connection: HttpURLConnection? = null + try { + connection = URL(link.url).openConnection() as HttpURLConnection + connection.requestMethod = "POST" + connection.connectTimeout = 10_000 + connection.readTimeout = 12_000 + connection.doOutput = true + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8") + connection.setRequestProperty("Accept", "application/json") + connection.outputStream.use { it.write(payload) } + val status = connection.responseCode + val body = readBody(connection, status) + if (status !in 200..299) { + val failure = parseFailure(body) + throw RemoteDocumentFailure( + failure.first.ifBlank { + "Ссылка недоступна. Получите новую ссылку подключения." + }, + failure.second, + ) + } + parse(body) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + if (error is IllegalStateException) throw error + throw IllegalStateException( + "Не удалось связаться с WDTT Plus. Проверьте интернет и попробуйте ещё раз." + ) + } finally { + connection?.disconnect() + } + } + } + + internal fun parse(body: String): RemoteDocumentDelivery { + require(body.length <= MAX_RESPONSE_CHARS) { "Ответ WDTT Plus слишком большой." } + val root = runCatching { JSONObject(body) } + .getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") } + if (root.optInt("version", 0) != 1) { + throw IllegalStateException("Для этой ссылки нужна более новая версия WDTT Plus.") + } + val kind = when (root.optString("type").trim()) { + "base" -> RemoteDocumentKind.BASE + "update" -> RemoteDocumentKind.UPDATE + else -> throw IllegalStateException("WDTT Plus вернул неподдерживаемый тип данных.") + } + val document = root.optString("document").trim() + val documentParts = WdttDeepLink.parse(document, allowMissingHashes = true) + if (documentParts == null) { + throw IllegalStateException("WDTT Plus вернул неполные данные подключения.") + } + val binding = root.optString("binding").trim().takeIf(::opaqueValue).orEmpty() + val action = root.optJSONObject("continuation") + val key = action?.optString("key").orEmpty().trim() + val url = action?.optString("url").orEmpty().trim() + val available = action?.optBoolean("available", false) == true && + opaqueValue(key) && safeServiceUrl(url) + val accessSource = root.optJSONObject("access") + val accessKey = accessSource?.optString("key").orEmpty().trim() + val accessUrl = accessSource?.optString("url").orEmpty().trim() + val accessBinding = accessSource?.optString("binding").orEmpty().trim() + val accessAvailable = accessSource?.optBoolean("available", false) == true && + opaqueValue(accessKey) && + safeServiceUrl(accessUrl) && + opaqueValue(accessBinding) + val cachedAction = accessSource + ?.optJSONObject("cached_action") + ?.let(::parseCachedAction) + ?: CachedRemoteAction.Unavailable + val exchange = accessSource + ?.optJSONObject("exchange") + ?.let(::parseProfileExchange) + ?: RemoteProfileExchange.Unavailable + val initialAccessStatus = if (accessAvailable) { + accessSource + ?.optJSONObject("status") + ?.let { nested -> + AccessLifecycleGateway.parseStatus( + JSONObject(nested.toString()).put("version", 1).toString() + ) + } + } else { + null + } + when (kind) { + RemoteDocumentKind.BASE -> { + if (documentParts.hashes.isNotBlank()) { + throw IllegalStateException( + "Ссылка подключения содержит лишние данные. Получите новую ссылку." + ) + } + } + RemoteDocumentKind.UPDATE -> { + if ( + binding.isBlank() || + action != null + ) { + throw IllegalStateException( + "Обновление профиля неполное или относится к другому действию." + ) + } + } + } + val workers = root.optJSONObject("limits")?.optInt("workers", 0) + ?.takeIf { + it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS && + it % TUNNEL_WORKERS_PER_GROUP == 0 + } + ?: 0 + val profileRevision = root.optLong("profile_revision", 0L).coerceAtLeast(0) + return RemoteDocumentDelivery( + document = document, + binding = binding, + continuation = RemoteContinuation( + available = available, + key = key.takeIf { available }.orEmpty(), + url = url.takeIf { available }.orEmpty(), + expiresAt = action?.optLong("expires", 0L) ?: 0L, + message = action?.optString("message").orEmpty().trim() + ), + access = RemoteAccessCapability( + available = accessAvailable, + key = accessKey.takeIf { accessAvailable }.orEmpty(), + url = accessUrl.takeIf { accessAvailable }.orEmpty(), + binding = accessBinding.takeIf { accessAvailable }.orEmpty(), + initialStatus = initialAccessStatus.takeIf { accessAvailable }, + cachedAction = cachedAction.takeIf { accessAvailable } + ?: CachedRemoteAction.Unavailable, + exchange = exchange.takeIf { accessAvailable } + ?: RemoteProfileExchange.Unavailable, + ), + kind = kind, + profileMaxWorkers = workers, + profileRevision = profileRevision, + ) + } + + internal fun parseFailure(body: String): Pair { + if (body.length > MAX_RESPONSE_CHARS) return "" to null + val root = runCatching { JSONObject(body) }.getOrNull() ?: return "" to null + val detail = root.optString("detail").trim().take(600) + val source = root.optJSONObject("action") ?: return detail to null + if (!source.optBoolean("available", false)) return detail to null + val label = source.optString("label").trim().take(120) + val primary = source.optString("url").trim() + val fallback = source.optString("fallback").trim() + val handler = source.optString("handler").trim() + val alternatesSource = source.optJSONArray("alternate_handlers") ?: JSONArray() + if (alternatesSource.length() > 8) return detail to null + val alternates = buildList { + repeat(alternatesSource.length()) { index -> + val value = alternatesSource.optString(index).trim() + if (!safePackageName(value)) return detail to null + add(value) + } + }.distinct() + val valid = label.isNotBlank() && + safeExternalUrl(primary) && + (fallback.isBlank() || safeExternalUrl(fallback)) && + (handler.isBlank() || safePackageName(handler)) + if (!valid) return detail to null + return detail to RemoteDocumentFailureAction( + label = label, + target = RemoteLaunchTarget( + primaryUrl = primary, + fallbackUrl = fallback, + preferredHandler = handler, + alternateHandlers = alternates, + ), + ) + } + + private fun safeServiceUrl(value: String): Boolean { + val uri = runCatching { URI(value) }.getOrNull() ?: return false + return trustedServiceUri(uri) && + uri.rawQuery.isNullOrBlank() && + uri.rawFragment.isNullOrBlank() + } + + internal fun parseCachedAction(source: JSONObject): CachedRemoteAction { + val payload = source.optString("payload").trim() + val primary = source.optString("url").trim() + val fallback = source.optString("fallback").trim() + val handler = source.optString("handler").trim() + val available = source.optBoolean("available", false) && + opaquePayload(payload) && + safeExternalUrl(primary) && + (fallback.isBlank() || safeExternalUrl(fallback)) && + (handler.isBlank() || safePackageName(handler)) + if (!available) return CachedRemoteAction.Unavailable + return CachedRemoteAction( + available = true, + payload = payload, + target = RemoteLaunchTarget( + primaryUrl = primary, + fallbackUrl = fallback, + preferredHandler = handler, + ), + title = source.optString("title").trim().take(120), + message = source.optString("message").trim().take(600), + label = source.optString("label").trim().take(120), + clipboardLabel = source.optString("clipboard_label").trim().take(120), + copiedMessage = source.optString("copied_message").trim().take(240), + failedMessage = source.optString("failed_message").trim().take(240), + helpTitle = source.optString("help_title").trim().take(120), + helpIntro = source.optString("help_intro").trim().take(600), + helpSteps = source.optString("help_steps").trim().take(1200), + ) + } + + internal fun parseProfileExchange(source: JSONObject): RemoteProfileExchange { + val submit = source.optJSONObject("submit") + val action = source.optJSONObject("action") + val submitToken = submit?.optString("token").orEmpty().trim() + val actionToken = action?.optString("token").orEmpty().trim() + val submitAvailable = + submit?.optBoolean("available", false) == true && opaqueValue(submitToken) + val label = action?.optString("label").orEmpty().trim().take(80) + val message = action?.optString("message").orEmpty().trim().take(300) + val actionAvailable = + action?.optBoolean("available", false) == true && + opaqueValue(actionToken) && + label.isNotBlank() + return if (submitAvailable || opaqueValue(actionToken)) { + RemoteProfileExchange( + submitAvailable = submitAvailable, + submitToken = submitToken.takeIf { submitAvailable }.orEmpty(), + actionAvailable = actionAvailable, + actionToken = actionToken.takeIf(::opaqueValue).orEmpty(), + label = label, + message = message, + ) + } else { + RemoteProfileExchange.Unavailable + } + } + + private fun safeExternalUrl(value: String): Boolean { + val uri = runCatching { URI(value) }.getOrNull() ?: return false + return uri.scheme.equals("https", ignoreCase = true) && + !uri.host.isNullOrBlank() && + uri.rawUserInfo.isNullOrBlank() && + (uri.port == -1 || uri.port == 443) + } + + private fun safePackageName(value: String): Boolean = + value.length in 3..255 && + Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value) + + private fun opaquePayload(value: String): Boolean = + value.length in 24..512 && Regex("^[A-Za-z0-9._-]+$").matches(value) + + private fun trustedServiceUri(uri: URI): Boolean = + uri.scheme.equals("https", ignoreCase = true) && + uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) && + uri.rawUserInfo.isNullOrBlank() && + (uri.port == -1 || uri.port == 443) + + private fun opaqueValue(value: String): Boolean = + value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value) + + private fun validDevice(value: String): Boolean = + Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim()) + + private fun readBody(connection: HttpURLConnection, status: Int): String { + val stream = if (status in 200..299) connection.inputStream else connection.errorStream + return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty() + } +} diff --git a/app/src/main/java/com/wdtt/plus/SecureStringStore.kt b/app/src/main/java/com/wdtt/plus/SecureStringStore.kt index 044fe1c..0e49ab9 100644 --- a/app/src/main/java/com/wdtt/plus/SecureStringStore.kt +++ b/app/src/main/java/com/wdtt/plus/SecureStringStore.kt @@ -12,6 +12,11 @@ import javax.crypto.spec.GCMParameterSpec class SecureStringStore(context: Context) { private val appContext = context.applicationContext + private val decryptedCache = object : LinkedHashMap(32, 0.75f, true) { + override fun removeEldestEntry( + eldest: MutableMap.MutableEntry? + ): Boolean = size > 64 + } companion object { private const val KEY_ALIAS = "wdtt.settings.secrets" @@ -29,14 +34,21 @@ class SecureStringStore(context: Context) { val cipher = Cipher.getInstance(TRANSFORMATION) cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey()) val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8)) - return VERSION_PREFIX + + val encoded = VERSION_PREFIX + Base64.encodeToString(cipher.iv, Base64.NO_WRAP) + ":" + Base64.encodeToString(encrypted, Base64.NO_WRAP) + synchronized(decryptedCache) { + decryptedCache[encoded] = value + } + return encoded } fun decrypt(value: String?): String? { if (value.isNullOrBlank() || !value.startsWith(VERSION_PREFIX)) return null + synchronized(decryptedCache) { + decryptedCache[value]?.let { return it } + } val payload = value.removePrefix(VERSION_PREFIX) val parts = payload.split(":", limit = 2) if (parts.size != 2) return null @@ -47,7 +59,11 @@ class SecureStringStore(context: Context) { val cipher = Cipher.getInstance(TRANSFORMATION) cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(GCM_TAG_BITS, iv)) cipher.doFinal(encrypted).toString(Charsets.UTF_8) - }.getOrNull() + }.getOrNull()?.also { decrypted -> + synchronized(decryptedCache) { + decryptedCache[value] = decrypted + } + } } private fun getOrCreateKey(): SecretKey { diff --git a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt index 4a9de1b..b230ea8 100644 --- a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt +++ b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt @@ -21,7 +21,7 @@ data class ServerAdminProfileInfo( val vkHashes: String = "", val secondaryVkHash: String = "", val profileName: String = "", - val workersPerHash: Int = 16, + val workersPerHash: Int = 18, val protocol: String = "udp", val listenPort: Int = 9000, val sni: String = "", @@ -42,6 +42,7 @@ data class ServerAdminState( val maxPasswords: Int, val passwordCount: Int, val deviceCount: Int, + val ownerDeviceCount: Int, val expiredCount: Int, val orphanDeviceCount: Int, val orphanDevices: List, @@ -393,6 +394,13 @@ object ServerAdminClient { maxPasswords = server.optInt("max_passwords", 50), passwordCount = server.optInt("password_count", clients.size), deviceCount = server.optInt("device_count", 0), + ownerDeviceCount = server.optInt( + "owner_device_count", + server.optJSONObject("admin_profile") + ?.optJSONArray("device_ids") + ?.length() + ?: 0 + ), expiredCount = server.optInt("expired_count", 0), orphanDeviceCount = server.optInt("orphan_device_count", 0), orphanDevices = buildList { @@ -423,7 +431,7 @@ object ServerAdminClient { vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(), secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(), profileName = vpnProfileRestorableName(json?.optString("profile_name", "").orEmpty()), - workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128), + workersPerHash = (json?.optInt("workers_per_hash", 18) ?: 18).coerceIn(1, 128), protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp", listenPort = listenPort, sni = json?.optString("sni", "").orEmpty().trim(), @@ -565,7 +573,7 @@ internal fun buildAdminProfilePatchArgs(profile: ServerAdminProfileInfo): List = emptyList(), ) data class WdttLinkParts( @@ -40,20 +47,34 @@ data class WdttLinkParts( val localPort: Int, val password: String, val hashes: String, - val profileName: String = "" + val profileName: String = "", + val maxWorkers: Int = 0 ) +internal fun WdttLinkParts.hasNonStandardPorts(): Boolean = + dtlsPort != 56000 || wgPort != 56001 || localPort != 9000 + +private val supportedWdttLinkFormats = """ + Поддерживаются форматы: + • Новый: wdtt://connect?v=1&host=адрес&dtls=DTLS-порт&wg=WG-порт&local=локальный-порт&password=пароль&hashes=VK-хеши + • Старый: wdtt://адрес:DTLS-порт:WG-порт:локальный-порт:пароль:VK-хеши +""".trimIndent() + data class WdttDeepLinkValidation( val parts: WdttLinkParts?, val errors: List, val warnings: List = emptyList() ) { - val canStartVpn: Boolean = parts != null && errors.isEmpty() + val canStartVpn: Boolean = parts != null && errors.isEmpty() && parts.hashes.isNotBlank() fun userMessage(): String { - return if (canStartVpn) { + return if (parts != null && errors.isEmpty()) { buildString { - append("Ссылка wdtt:// корректна. VPN сможет использовать эти данные для подключения.") + if (parts.hashes.isBlank()) { + append("Ссылка wdtt:// распознана. Добавьте свой VK-хеш перед запуском VPN.") + } else { + append("Ссылка wdtt:// корректна. VPN сможет использовать эти данные для подключения.") + } parts?.profileName?.takeIf { it.isNotBlank() }?.let { append("\nНазвание профиля: «") append(it) @@ -68,7 +89,8 @@ data class WdttDeepLinkValidation( buildString { append("VPN не запустится по этой ссылке, потому что в ней есть ошибки:\n") append(errors.joinToString("\n") { "• $it" }) - append("\n\nПравильный вид: wdtt://адрес:DTLS-порт:WG-порт:локальный-порт:пароль:VK-хеши") + append("\n\n") + append(supportedWdttLinkFormats) } } } @@ -84,17 +106,108 @@ data class WdttDeepLinkApplyPlan( data class WdttDeepLinkApplyResult( val targetProfile: Int, val overwritten: Boolean, - val storedAsLink: Boolean + val storedAsLink: Boolean, + val alreadyApplied: Boolean = false, +) + +internal data class InterfaceRoleProfileState( + val role: String, + val rememberedRole: String?, +) + +internal fun reconcileInterfaceRoleForProfile( + storedRole: String, + rememberedRole: String?, + remoteManagedProfile: Boolean, +): InterfaceRoleProfileState { + val validStoredRole = storedRole.takeIf { it == "user" || it == "admin" }.orEmpty() + val validRememberedRole = rememberedRole?.takeIf { it == "user" || it == "admin" } + return if (remoteManagedProfile) { + InterfaceRoleProfileState( + role = "user", + rememberedRole = validRememberedRole ?: validStoredRole.takeIf { it.isNotBlank() }, + ) + } else { + InterfaceRoleProfileState( + role = validRememberedRole ?: validStoredRole, + rememberedRole = null, + ) + } +} + +data class TunnelProfileSnapshot( + val profileIndex: Int, + val remoteManaged: Boolean, + val linkMode: Boolean, + val link: String, + val peer: String, + val vkHashes: String, + val secondaryVkHash: String, + val connectionPassword: String, + val workersPerHash: Int, + val profileMaxWorkers: Int, + val manualPortsEnabled: Boolean, + val serverDtlsPort: Int, + val listenPort: Int, + val sni: String, + val protocol: String, + val vkCallsPreflight: Boolean, + val captchaMode: String, + val captchaSolveMethod: String, + val fingerprint: String, + val clientIds: String, + val customVkCredentialsEnabled: Boolean, + val customVkClientId: String, + val customVkClientSecret: String, +) + +/** + * One atomic DataStore projection for the visible Tunnel tab. + * + * Keeping these values in one snapshot prevents a profile switch from briefly combining the + * new profile index with connection fields (or interface role) emitted for the previous one. + */ +data class ActiveTunnelProfileUiSnapshot( + val profileIndex: Int, + val profileNames: List, + val interfaceRole: String, + val permissionOnboardingComplete: Boolean, + val connectionInputMethod: String, + val linkMode: Boolean, + val link: String, + val peer: String, + val vkHashes: String, + val connectionPassword: String, + val workersPerHash: Int, + val manualPortsEnabled: Boolean, + val serverDtlsPort: Int, + val serverWgPort: Int, + val listenPort: Int, + val sni: String, + val captchaMode: String, + val captchaSolveMethod: String, + val fingerprint: String, + val clientIds: String, + val customVkCredentialsEnabled: Boolean, + val customVkClientId: String, + val customVkClientSecret: String, + val vkCallsPreflight: Boolean, + val remoteActionKey: String, + val remoteActionUrl: String, + val remoteManaged: Boolean, + val cachedRemoteAction: CachedRemoteAction, + val remoteCardDismissed: Boolean, + val accessLifecycle: AccessLifecycleUiState, + val accessLifecycleDismissedSignature: String, + val profileMaxWorkers: Int, ) object WdttDeepLink { - private val expectedFormat = "wdtt://адрес:DTLS-порт:WG-порт:локальный-порт:пароль:VK-хеши" - - fun parse(value: String): WdttLinkParts? { - return validate(value).parts + fun parse(value: String, allowMissingHashes: Boolean = false): WdttLinkParts? { + return validate(value, allowMissingHashes).parts } - fun validate(value: String): WdttDeepLinkValidation { + fun validate(value: String, allowMissingHashes: Boolean = false): WdttDeepLinkValidation { val clean = WdttTransferCodec.extractWdttLink(value) ?: value.trim() val errors = mutableListOf() val warnings = mutableListOf() @@ -102,7 +215,7 @@ object WdttDeepLink { if (clean.isBlank()) { return WdttDeepLinkValidation( parts = null, - errors = listOf("Ссылка пустая. Нужен вид: $expectedFormat.") + errors = listOf("Ссылка пустая. Вставьте ссылку WDTT нового или старого формата.") ) } @@ -132,7 +245,7 @@ object WdttDeepLink { } return WdttDeepLinkValidation( parts = null, - errors = listOf("В ссылке должно быть 6 полей после wdtt://, сейчас $found: $detail.") + errors = listOf("В старой ссылке должно быть 6 полей после wdtt://, сейчас $found: $detail.") ) } @@ -152,20 +265,26 @@ object WdttDeepLink { val rawHashes = (modernParts?.hashes ?: parts[5]).split(",") val hashes = rawHashes - .map { VkJoinLink.extractHash(it) } - .filter { it.isNotBlank() && it.length >= 16 } + .mapNotNull { VkJoinLink.normalizeHashes(it)?.takeIf(String::isNotBlank) } .distinct() .joinToString(",") if (hashes.isBlank()) { - errors += "Нет рабочего VK-хеша. Нужен хотя бы один хеш длиной от 16 символов или ссылка VK-звонка." + val invalidHashesProvided = rawHashes.any { it.isNotBlank() } + if (invalidHashesProvided) { + errors += "VK-хеш содержит недопустимые символы. Используйте латинские буквы, цифры, _ и - либо ссылку VK-звонка." + } else if (allowMissingHashes) { + warnings += "VK-хеши ещё не заполнены. Добавьте их в WDTT Plus перед запуском VPN." + } else { + errors += "Нет рабочего VK-хеша. Нужен хеш из латинских букв, цифр, _ или - либо ссылка VK-звонка." + } } else { val invalidHashes = rawHashes .map { it.trim() } .filter { it.isNotBlank() } - .count { VkJoinLink.extractHash(it).length < 16 } + .count { !VkJoinLink.isValidInput(it) } if (invalidHashes > 0) { - warnings += "$invalidHashes ${hashWord(invalidHashes)} короче 16 символов и будет пропущено." + warnings += "$invalidHashes ${hashWord(invalidHashes)} содержит недопустимые символы и будет пропущено." } } @@ -177,7 +296,8 @@ object WdttDeepLink { localPort = localPort, password = password, hashes = hashes, - profileName = normalizeVpnProfileName(modernParts?.profileName.orEmpty()) + profileName = normalizeVpnProfileName(modernParts?.profileName.orEmpty()), + maxWorkers = modernParts?.maxWorkers ?: 0 ) } else null @@ -235,39 +355,117 @@ object WdttDeepLink { class SettingsStore(context: Context) { private val appContext = context.applicationContext - private val storeScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - private val preferencesState: StateFlow = appContext.dataStore.data.stateIn( - storeScope, - SharingStarted.Eagerly, - null - ) + private val sharedPreferences = obtainSharedPreferences(appContext) + private val storeScope = sharedPreferences.scope + private val preferencesState: StateFlow = sharedPreferences.state private val preferencesFlow: Flow = preferencesState.filterNotNull() private val _settingsReady = MutableStateFlow(false) val settingsReady: StateFlow = _settingsReady.asStateFlow() - init { - storeScope.launch { - preferencesFlow.first() - _settingsReady.value = true - } - } - companion object { private val Context.dataStore by preferencesDataStore("settings") + private data class SharedPreferences( + val scope: CoroutineScope, + val state: StateFlow, + ) + + @Volatile + private var sharedPreferences: SharedPreferences? = null + + private fun obtainSharedPreferences(context: Context): SharedPreferences = + sharedPreferences ?: synchronized(this) { + sharedPreferences ?: run { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + SharedPreferences( + scope = scope, + state = context.dataStore.data.stateIn( + scope, + SharingStarted.Eagerly, + null, + ), + ).also { sharedPreferences = it } + } + } private val ACTIVE_PROFILE = intPreferencesKey("active_profile") + private val ACTIVE_TUNNEL_PROFILE = intPreferencesKey("active_tunnel_profile") private val PROFILE_NAME = stringPreferencesKey("profile_name") private val SHOW_SYSTEM_APPS = booleanPreferencesKey("show_system_apps") private val LOGGING_ENABLED = booleanPreferencesKey("logging_enabled") + private val FLOATING_TOOLBAR_Y_FRACTION = floatPreferencesKey("floating_toolbar_y_fraction") private val TRUSTED_WIFI_ENABLED = booleanPreferencesKey("trusted_wifi_enabled") private val TRUSTED_WIFI_SSIDS = stringPreferencesKey("trusted_wifi_ssids") private val TRUSTED_WIFI_WAITING = booleanPreferencesKey("trusted_wifi_waiting") private val TRUSTED_WIFI_WAITING_SSID = stringPreferencesKey("trusted_wifi_waiting_ssid") private val WDTT_LINK = stringPreferencesKey("wdtt_link") 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 TUNNEL_DEVICE_ID = stringPreferencesKey("tunnel_device_id") private val PEER = stringPreferencesKey("peer") private val VK_HASHES = stringPreferencesKey("vk_hashes") private val SECONDARY_VK_HASH = stringPreferencesKey("secondary_vk_hash") + private val PROFILE_VALUES_SYNC_PENDING = + booleanPreferencesKey("profile_values_sync_pending") + private val REMOTE_ACTION_KEY = stringPreferencesKey("remote_action_key") + private val REMOTE_ACTION_KEY_ENCRYPTED = + stringPreferencesKey("remote_action_key_encrypted") + private val REMOTE_ACTION_URL = stringPreferencesKey("remote_action_url") + private val REMOTE_DOCUMENT_BINDING = stringPreferencesKey("remote_document_binding") + private val REMOTE_MANAGED_PROFILE = booleanPreferencesKey("remote_managed_profile") + private val REMOTE_CARD_DISMISSED = booleanPreferencesKey("remote_card_dismissed") + private val ACCESS_LIFECYCLE_DISMISSED_SIGNATURE = + stringPreferencesKey("access_lifecycle_dismissed_signature") + private val ACCESS_LIFECYCLE_KEY_ENCRYPTED = + stringPreferencesKey("access_lifecycle_key_encrypted") + private val ACCESS_LIFECYCLE_URL = stringPreferencesKey("access_lifecycle_url") + private val ACCESS_LIFECYCLE_BINDING = stringPreferencesKey("access_lifecycle_binding") + private val PROFILE_EXCHANGE_SUBMIT_TOKEN_ENCRYPTED = + stringPreferencesKey("profile_exchange_submit_token_encrypted") + private val PROFILE_EXCHANGE_ACTION_TOKEN_ENCRYPTED = + stringPreferencesKey("profile_exchange_action_token_encrypted") + private val PROFILE_EXCHANGE_ACTION_LABEL = + stringPreferencesKey("profile_exchange_action_label") + private val PROFILE_EXCHANGE_ACTION_MESSAGE = + stringPreferencesKey("profile_exchange_action_message") + private val PROFILE_EXCHANGE_ACTION_AVAILABLE = + booleanPreferencesKey("profile_exchange_action_available") + private val CACHED_ACTION_PAYLOAD_ENCRYPTED = + stringPreferencesKey("cached_action_payload_encrypted") + private val CACHED_ACTION_URL = stringPreferencesKey("cached_action_url") + private val CACHED_ACTION_FALLBACK = stringPreferencesKey("cached_action_fallback") + private val CACHED_ACTION_HANDLER = stringPreferencesKey("cached_action_handler") + private val CACHED_ACTION_TITLE = stringPreferencesKey("cached_action_title") + private val CACHED_ACTION_MESSAGE = stringPreferencesKey("cached_action_message") + private val CACHED_ACTION_LABEL = stringPreferencesKey("cached_action_label") + private val CACHED_ACTION_CLIPBOARD_LABEL = + stringPreferencesKey("cached_action_clipboard_label") + private val CACHED_ACTION_COPIED_MESSAGE = + stringPreferencesKey("cached_action_copied_message") + private val CACHED_ACTION_FAILED_MESSAGE = + stringPreferencesKey("cached_action_failed_message") + private val CACHED_ACTION_HELP_TITLE = + stringPreferencesKey("cached_action_help_title") + private val CACHED_ACTION_HELP_INTRO = + stringPreferencesKey("cached_action_help_intro") + private val CACHED_ACTION_HELP_STEPS = + stringPreferencesKey("cached_action_help_steps") + private val ACCESS_ACTION_LABEL = stringPreferencesKey("access_action_label") + 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 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") + private val ACCESS_SEVERITY = stringPreferencesKey("access_severity") + private val ACCESS_ALLOW_CONNECT = booleanPreferencesKey("access_allow_connect") + private val ACCESS_ACTION_AVAILABLE = booleanPreferencesKey("access_action_available") + private val ACCESS_CHECKED_AT = longPreferencesKey("access_checked_at") + private val ACCESS_LAST_ATTEMPT_AT = longPreferencesKey("access_last_attempt_at") + private val ACCESS_PROFILE_REVISION = longPreferencesKey("access_profile_revision") + private val ACCESS_ACTION_LAUNCHED_AT = + longPreferencesKey("access_action_launched_at") + private val PROFILE_MAX_WORKERS = intPreferencesKey("profile_max_workers") private val VK_HASH_NEXT_SLOT = intPreferencesKey("vk_hash_next_slot") private val WORKERS_PER_HASH = intPreferencesKey("workers_per_hash") private val PROTOCOL = stringPreferencesKey("protocol") @@ -336,6 +534,11 @@ class SettingsStore(context: Context) { // ═══ Fingerprint & Client IDs ═══ private val SELECTED_FINGERPRINT = stringPreferencesKey("selected_fingerprint") private val ACTIVE_CLIENT_IDS = stringPreferencesKey("active_client_ids") + private val CUSTOM_VK_CREDENTIALS_ENABLED = booleanPreferencesKey("custom_vk_credentials_enabled") + private val CUSTOM_VK_CLIENT_ID = stringPreferencesKey("custom_vk_client_id") + private val CUSTOM_VK_CLIENT_SECRET = stringPreferencesKey("custom_vk_client_secret") + private val CUSTOM_VK_CLIENT_SECRET_ENCRYPTED = + stringPreferencesKey("custom_vk_client_secret_encrypted") private val UPDATE_LAST_CHECK_AT = longPreferencesKey("update_last_check_at") private val UPDATE_LATEST_VERSION = stringPreferencesKey("update_latest_version") @@ -363,17 +566,138 @@ class SettingsStore(context: Context) { private val CLIENT_ID_CHECK_RESULTS = stringPreferencesKey("client_id_check_results") private val INTERFACE_ROLE = stringPreferencesKey("interface_role") + private val INTERFACE_ROLE_BEFORE_REMOTE_PROFILE = + stringPreferencesKey("interface_role_before_remote_profile") private val PERMISSION_ONBOARDING_COMPLETE = booleanPreferencesKey("permission_onboarding_complete") private const val VPN_PROFILE_COUNT = 3 + private val PROFILE_STRING_KEYS = listOf( + PROFILE_NAME, + PEER, + VK_HASHES, + SECONDARY_VK_HASH, + REMOTE_ACTION_KEY, + REMOTE_ACTION_KEY_ENCRYPTED, + REMOTE_ACTION_URL, + REMOTE_DOCUMENT_BINDING, + ACCESS_LIFECYCLE_KEY_ENCRYPTED, + ACCESS_LIFECYCLE_URL, + ACCESS_LIFECYCLE_BINDING, + PROFILE_EXCHANGE_SUBMIT_TOKEN_ENCRYPTED, + PROFILE_EXCHANGE_ACTION_TOKEN_ENCRYPTED, + PROFILE_EXCHANGE_ACTION_LABEL, + PROFILE_EXCHANGE_ACTION_MESSAGE, + CACHED_ACTION_PAYLOAD_ENCRYPTED, + CACHED_ACTION_URL, + CACHED_ACTION_FALLBACK, + CACHED_ACTION_HANDLER, + CACHED_ACTION_TITLE, + CACHED_ACTION_MESSAGE, + CACHED_ACTION_LABEL, + CACHED_ACTION_CLIPBOARD_LABEL, + CACHED_ACTION_COPIED_MESSAGE, + CACHED_ACTION_FAILED_MESSAGE, + CACHED_ACTION_HELP_TITLE, + CACHED_ACTION_HELP_INTRO, + CACHED_ACTION_HELP_STEPS, + ACCESS_ACTION_LABEL, + ACCESS_ACTION_MESSAGE, + ACCESS_TITLE, + ACCESS_MESSAGE, + ACCESS_DETAIL_LABEL, + ACCESS_DETAIL_VALUE, + ACCESS_ACTION_ICON, + ACCESS_SEVERITY, + ACCESS_LIFECYCLE_DISMISSED_SIGNATURE, + PROTOCOL, + SNI, + USER_AGENT, + DEPLOY_IP, + DEPLOY_LOGIN, + DEPLOY_PASSWORD, + DEPLOY_PASSWORD_ENCRYPTED, + DEPLOY_SSH_PRIVATE_KEY, + DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, + DEPLOY_SSH_KEY_PASSPHRASE, + DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, + DEPLOY_SSH_AUTH_MODE, + WG_EXIT_SSH_PRIVATE_KEY, + WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, + WG_EXIT_SSH_KEY_PASSPHRASE, + WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED, + WG_EXIT_SSH_AUTH_MODE, + DEPLOY_SSH_PORT, + DEPLOY_DNS1, + DEPLOY_DNS2, + EXCLUDED_APPS, + BLACKLIST_APPS, + WHITELIST_APPS, + CONNECTION_PASSWORD, + CONNECTION_PASSWORD_ENCRYPTED, + DEPLOY_MAIN_PASSWORD, + DEPLOY_MAIN_PASSWORD_ENCRYPTED, + DEPLOY_ADMIN_ID, + DEPLOY_ADMIN_ID_ENCRYPTED, + DEPLOY_BOT_TOKEN, + DEPLOY_BOT_TOKEN_ENCRYPTED, + PROXY_MODE, + PROXY_HOST, + CAPTCHA_MODE, + CAPTCHA_SOLVE_METHOD, + CAPTCHA_WBV_SOLVE_METHOD, + WDTT_LINK, + CONNECTION_INPUT_METHOD, + SELECTED_FINGERPRINT, + ACTIVE_CLIENT_IDS, + CUSTOM_VK_CLIENT_ID, + CUSTOM_VK_CLIENT_SECRET, + CUSTOM_VK_CLIENT_SECRET_ENCRYPTED + ) + private val PROFILE_INT_KEYS = listOf( + WORKERS_PER_HASH, + PROFILE_MAX_WORKERS, + VK_HASH_NEXT_SLOT, + LISTEN_PORT, + SERVER_DTLS_PORT, + SERVER_WG_PORT, + PROXY_PORT + ) + private val PROFILE_LONG_KEYS = listOf( + ACCESS_CHECKED_AT, + ACCESS_LAST_ATTEMPT_AT, + ACCESS_PROFILE_REVISION, + ACCESS_ACTION_LAUNCHED_AT, + ) + private val PROFILE_BOOLEAN_KEYS = listOf( + MANUAL_PORTS_ENABLED, + NO_DTLS, + NO_DNS, + IS_WHITELIST, + WDTT_LINK_MODE, + REMOTE_MANAGED_PROFILE, + REMOTE_CARD_DISMISSED, + VKCALLS_PREFLIGHT, + DETAILED_LOGS, + CUSTOM_VK_CREDENTIALS_ENABLED, + ACCESS_ALLOW_CONNECT, + ACCESS_ACTION_AVAILABLE, + PROFILE_VALUES_SYNC_PENDING, + PROFILE_EXCHANGE_ACTION_AVAILABLE, + ) + + internal fun resettableProfilePreferenceNames(): Set = + (PROFILE_STRING_KEYS + PROFILE_INT_KEYS + PROFILE_LONG_KEYS + PROFILE_BOOLEAN_KEYS) + .mapTo(linkedSetOf()) { it.name } + private fun getProfileKey(baseKey: Preferences.Key, profile: Int): Preferences.Key { if (profile == 0) return baseKey val newName = "${baseKey.name}_$profile" @Suppress("UNCHECKED_CAST") - return when (baseKey) { - PROFILE_NAME, PEER, VK_HASHES, SECONDARY_VK_HASH, PROTOCOL, SNI, USER_AGENT, DEPLOY_IP, DEPLOY_LOGIN, DEPLOY_PASSWORD, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_KEY_PASSPHRASE, DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, DEPLOY_SSH_AUTH_MODE, WG_EXIT_SSH_PRIVATE_KEY, WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, WG_EXIT_SSH_KEY_PASSPHRASE, WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED, WG_EXIT_SSH_AUTH_MODE, DEPLOY_SSH_PORT, DEPLOY_DNS1, DEPLOY_DNS2, EXCLUDED_APPS, BLACKLIST_APPS, WHITELIST_APPS, CONNECTION_PASSWORD, CONNECTION_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_ADMIN_ID, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_BOT_TOKEN, DEPLOY_BOT_TOKEN_ENCRYPTED, PROXY_MODE, PROXY_HOST, CAPTCHA_MODE, CAPTCHA_SOLVE_METHOD, CAPTCHA_WBV_SOLVE_METHOD, WDTT_LINK, SELECTED_FINGERPRINT, ACTIVE_CLIENT_IDS -> stringPreferencesKey(newName) as Preferences.Key - WORKERS_PER_HASH, VK_HASH_NEXT_SLOT, LISTEN_PORT, SERVER_DTLS_PORT, SERVER_WG_PORT, PROXY_PORT -> intPreferencesKey(newName) as Preferences.Key - MANUAL_PORTS_ENABLED, NO_DTLS, NO_DNS, IS_WHITELIST, WDTT_LINK_MODE, VKCALLS_PREFLIGHT, DETAILED_LOGS -> booleanPreferencesKey(newName) as Preferences.Key + return when { + PROFILE_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}") } } @@ -381,16 +705,124 @@ class SettingsStore(context: Context) { private val dataStore = appContext.dataStore private val secureStore = SecureStringStore(appContext) + // Keep the selected profile responsive while the DataStore write is being flushed. The + // snapshot still falls back to the persisted value for every other caller. + private val activeProfileOverride = MutableStateFlow(null) + + val activeProfile: Flow = preferencesFlow.map { it[ACTIVE_PROFILE] ?: 0 } + val activeTunnelProfileUiSnapshot: StateFlow = + combine(preferencesState, activeProfileOverride) { prefs, requestedProfile -> + prefs?.let { + val persistedProfile = (it[ACTIVE_PROFILE] ?: 0) + .coerceIn(0, VPN_PROFILE_COUNT - 1) + if (requestedProfile != null && requestedProfile == persistedProfile) { + // The DataStore emission has caught up. Clearing the override here keeps + // the same snapshot (distinctUntilChanged prevents a visual bounce). + activeProfileOverride.compareAndSet(requestedProfile, null) + } + val profile = + (requestedProfile ?: persistedProfile) + .coerceIn(0, VPN_PROFILE_COUNT - 1) + ActiveTunnelProfileUiSnapshot( + profileIndex = profile, + profileNames = (0 until VPN_PROFILE_COUNT).map { index -> + it[getProfileKey(PROFILE_NAME, index)].orEmpty() + }, + interfaceRole = it[INTERFACE_ROLE].orEmpty(), + permissionOnboardingComplete = + it[PERMISSION_ONBOARDING_COMPLETE] ?: !it[INTERFACE_ROLE].isNullOrBlank(), + connectionInputMethod = it[getProfileKey(CONNECTION_INPUT_METHOD, profile)] + ?.takeIf { method -> method == "link" || method == "manual" } + .orEmpty(), + linkMode = it[getProfileKey(WDTT_LINK_MODE, profile)] ?: false, + link = it[getProfileKey(WDTT_LINK, profile)].orEmpty(), + peer = it[getProfileKey(PEER, profile)].orEmpty(), + vkHashes = it[getProfileKey(VK_HASHES, profile)].orEmpty(), + connectionPassword = readSecret( + it, + CONNECTION_PASSWORD_ENCRYPTED, + CONNECTION_PASSWORD, + profile + ), + workersPerHash = it[getProfileKey(WORKERS_PER_HASH, profile)] ?: 18, + manualPortsEnabled = it[getProfileKey(MANUAL_PORTS_ENABLED, profile)] ?: false, + serverDtlsPort = it[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000, + serverWgPort = it[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001, + listenPort = it[getProfileKey(LISTEN_PORT, profile)] ?: 9000, + sni = it[getProfileKey(SNI, profile)].orEmpty(), + captchaMode = it[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto", + captchaSolveMethod = it[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto", + fingerprint = it[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox", + clientIds = it[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: DEFAULT_VK_CLIENT_IDS, + customVkCredentialsEnabled = + it[getProfileKey(CUSTOM_VK_CREDENTIALS_ENABLED, profile)] ?: false, + customVkClientId = normalizeVkClientId( + it[getProfileKey(CUSTOM_VK_CLIENT_ID, profile)].orEmpty() + ), + customVkClientSecret = readSecret( + it, + CUSTOM_VK_CLIENT_SECRET_ENCRYPTED, + CUSTOM_VK_CLIENT_SECRET, + profile + ), + vkCallsPreflight = it[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true, + remoteActionKey = readSecret( + it, + REMOTE_ACTION_KEY_ENCRYPTED, + REMOTE_ACTION_KEY, + profile + ), + remoteActionUrl = it[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty(), + remoteManaged = + it[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true || + it[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty().isNotBlank() || + it[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty().isNotBlank() || + it[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].orEmpty().isNotBlank(), + cachedRemoteAction = readCachedRemoteAction(it, profile), + remoteCardDismissed = + it[getProfileKey(REMOTE_CARD_DISMISSED, profile)] ?: false, + accessLifecycle = readAccessLifecycleUiState(it, profile), + accessLifecycleDismissedSignature = + it[getProfileKey(ACCESS_LIFECYCLE_DISMISSED_SIGNATURE, profile)].orEmpty(), + profileMaxWorkers = + (it[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0) + .coerceIn(0, APP_MAX_WORKERS), + ) + } + }.distinctUntilChanged() + .flowOn(Dispatchers.IO) + .stateIn(storeScope, SharingStarted.Eagerly, null) init { - CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { + storeScope.launch { + preferencesFlow.first() migrateSecretsToKeystore() + prewarmTunnelProfileSecrets(preferencesFlow.first()) migrateWireGuardExitSshAuthMode() migrateVpnAppLists() + repairInvalidLinkModes() + _settingsReady.value = true } } - val activeProfile: Flow = preferencesFlow.map { it[ACTIVE_PROFILE] ?: 0 } + private fun prewarmTunnelProfileSecrets(prefs: Preferences) { + for (profile in 0 until VPN_PROFILE_COUNT) { + readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile) + readSecret( + prefs, + CUSTOM_VK_CLIENT_SECRET_ENCRYPTED, + CUSTOM_VK_CLIENT_SECRET, + profile, + ) + readSecret(prefs, REMOTE_ACTION_KEY_ENCRYPTED, REMOTE_ACTION_KEY, profile) + readProtectedSecret(prefs, ACCESS_LIFECYCLE_KEY_ENCRYPTED, profile) + readProtectedSecret(prefs, CACHED_ACTION_PAYLOAD_ENCRYPTED, profile) + } + } + + val activeTunnelProfile: Flow = preferencesFlow.map { prefs -> + prefs[ACTIVE_TUNNEL_PROFILE]?.takeIf { it in 0 until VPN_PROFILE_COUNT } + } val profileNames: Flow> = preferencesFlow.map { prefs -> (0 until VPN_PROFILE_COUNT).map { profile -> prefs[getProfileKey(PROFILE_NAME, profile)].orEmpty() @@ -398,6 +830,9 @@ 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 + } val trustedWifiEnabled: Flow = preferencesFlow.map { it[TRUSTED_WIFI_ENABLED] ?: false } val trustedWifiSsids: Flow> = preferencesFlow.map { prefs -> parseTrustedWifiSsids(prefs[TRUSTED_WIFI_SSIDS].orEmpty()) @@ -414,6 +849,12 @@ class SettingsStore(context: Context) { val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(WDTT_LINK_MODE, profile)] ?: false } + val connectionInputMethod: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] + ?.takeIf { it == "link" || it == "manual" } + .orEmpty() + } val peer: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 @@ -427,9 +868,32 @@ class SettingsStore(context: Context) { val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(SECONDARY_VK_HASH, profile)] ?: "" } + val remoteActionKey: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + readSecret(prefs, REMOTE_ACTION_KEY_ENCRYPTED, REMOTE_ACTION_KEY, profile) + } + val remoteActionUrl: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty() + } + val remoteManagedProfile: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true || + prefs[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty().isNotBlank() || + prefs[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty().isNotBlank() || + prefs[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].orEmpty().isNotBlank() + } + val activeAccessLifecycle: Flow = preferencesFlow.map { prefs -> + val profile = (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1) + readAccessLifecycleUiState(prefs, profile) + }.distinctUntilChanged().flowOn(Dispatchers.IO) + val profileMaxWorkers: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + (prefs[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0).coerceIn(0, APP_MAX_WORKERS) + } val workersPerHash: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 - prefs[getProfileKey(WORKERS_PER_HASH, profile)] ?: 16 + prefs[getProfileKey(WORKERS_PER_HASH, profile)] ?: 18 } val protocol: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 @@ -475,35 +939,35 @@ class SettingsStore(context: Context) { val deployPassword: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 readSecret(prefs, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile) - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val deploySshPrivateKey: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 readSecret(prefs, DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, profile) - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val deploySshKeyPassphrase: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 readSecret(prefs, DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, DEPLOY_SSH_KEY_PASSPHRASE, profile) - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val deploySshAuthMode: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] ?.takeIf { it == "password" || it == "key" } ?: if (readSecret(prefs, DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, profile).isNotBlank()) "key" else "password" - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val wireGuardExitSshPrivateKey: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 readSecret(prefs, WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, WG_EXIT_SSH_PRIVATE_KEY, profile) - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val wireGuardExitSshKeyPassphrase: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 readSecret(prefs, WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED, WG_EXIT_SSH_KEY_PASSPHRASE, profile) - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val wireGuardExitSshAuthMode: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(WG_EXIT_SSH_AUTH_MODE, profile)] ?.takeIf { it == "password" || it == "key" } ?: if (readSecret(prefs, WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, WG_EXIT_SSH_PRIVATE_KEY, profile).isNotBlank()) "key" else "password" - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val deploySshPort: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] ?: "" @@ -535,19 +999,19 @@ class SettingsStore(context: Context) { val connectionPassword: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile) - } + }.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) - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val deployAdminId: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile) - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) val deployBotToken: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 readSecret(prefs, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile) - } + }.distinctUntilChanged().flowOn(Dispatchers.IO) // ═══ Proxy Mode ═══ val proxyMode: Flow = preferencesFlow.map { prefs -> @@ -599,7 +1063,35 @@ class SettingsStore(context: Context) { } val activeClientIds: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 - prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: "6287487,8202606" + prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: DEFAULT_VK_CLIENT_IDS + } + val customVkCredentialsEnabled: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(CUSTOM_VK_CREDENTIALS_ENABLED, profile)] ?: false + } + val customVkClientId: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + normalizeVkClientId(prefs[getProfileKey(CUSTOM_VK_CLIENT_ID, profile)].orEmpty()) + } + val customVkClientSecret: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + readSecret( + prefs, + CUSTOM_VK_CLIENT_SECRET_ENCRYPTED, + CUSTOM_VK_CLIENT_SECRET, + profile + ) + } + val customVkCredentialsComplete: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + val clientId = prefs[getProfileKey(CUSTOM_VK_CLIENT_ID, profile)].orEmpty() + val clientSecret = readSecret( + prefs, + CUSTOM_VK_CLIENT_SECRET_ENCRYPTED, + CUSTOM_VK_CLIENT_SECRET, + profile + ) + isValidVkClientId(clientId) && clientSecret.isNotBlank() } val clientIdCheckResults: Flow = preferencesFlow.map { prefs -> prefs[CLIENT_ID_CHECK_RESULTS] ?: "{}" @@ -642,17 +1134,50 @@ class SettingsStore(context: Context) { } suspend fun saveInterfaceRole(role: String) { + require(role == "user" || role == "admin") { "Неизвестный режим интерфейса" } dataStore.edit { prefs -> - val profile = prefs[ACTIVE_PROFILE] ?: 0 val hadRole = !prefs[INTERFACE_ROLE].isNullOrBlank() prefs[INTERFACE_ROLE] = role - prefs[getProfileKey(WDTT_LINK_MODE, profile)] = role == "user" + prefs.remove(INTERFACE_ROLE_BEFORE_REMOTE_PROFILE) if (!hadRole && !prefs.contains(PERMISSION_ONBOARDING_COMPLETE)) { prefs[PERMISSION_ONBOARDING_COMPLETE] = false } } } + suspend fun synchronizeInterfaceRoleForProfile(remoteManagedProfile: Boolean) { + dataStore.edit { prefs -> + val hadRole = !prefs[INTERFACE_ROLE].isNullOrBlank() + val state = reconcileInterfaceRoleForProfile( + storedRole = prefs[INTERFACE_ROLE].orEmpty(), + rememberedRole = prefs[INTERFACE_ROLE_BEFORE_REMOTE_PROFILE], + remoteManagedProfile = remoteManagedProfile, + ) + if (state.role.isBlank()) { + prefs.remove(INTERFACE_ROLE) + } else { + prefs[INTERFACE_ROLE] = state.role + } + state.rememberedRole?.let { rememberedRole -> + prefs[INTERFACE_ROLE_BEFORE_REMOTE_PROFILE] = rememberedRole + } ?: prefs.remove(INTERFACE_ROLE_BEFORE_REMOTE_PROFILE) + if (!hadRole && state.role.isNotBlank() && !prefs.contains(PERMISSION_ONBOARDING_COMPLETE)) { + prefs[PERMISSION_ONBOARDING_COMPLETE] = false + } + } + } + + suspend fun useUserInterfaceForRemoteActivationIfUnset() { + dataStore.edit { prefs -> + if (prefs[INTERFACE_ROLE].isNullOrBlank()) { + prefs[INTERFACE_ROLE] = "user" + if (!prefs.contains(PERMISSION_ONBOARDING_COMPLETE)) { + prefs[PERMISSION_ONBOARDING_COMPLETE] = false + } + } + } + } + suspend fun savePermissionOnboardingComplete(complete: Boolean) { dataStore.edit { prefs -> prefs[PERMISSION_ONBOARDING_COMPLETE] = complete @@ -691,6 +1216,30 @@ class SettingsStore(context: Context) { } } + suspend fun saveCustomVkCredentialsEnabled(enabled: Boolean) { + dataStore.edit { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(CUSTOM_VK_CREDENTIALS_ENABLED, profile)] = enabled + } + } + + suspend fun saveCustomVkCredentials(clientId: String, clientSecret: String) { + val normalizedId = normalizeVkClientId(clientId) + val normalizedSecret = normalizeVkClientSecret(clientSecret) + require(isValidVkClientId(normalizedId)) { "Client ID должен состоять из цифр" } + require(normalizedSecret.isNotBlank()) { "Client secret не может быть пустым" } + dataStore.edit { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(CUSTOM_VK_CLIENT_ID, profile)] = normalizedId + prefs.putSecret( + CUSTOM_VK_CLIENT_SECRET_ENCRYPTED, + CUSTOM_VK_CLIENT_SECRET, + normalizedSecret, + profile + ) + } + } + suspend fun saveClientIdCheckResults(resultsJson: String) { dataStore.edit { prefs -> prefs[CLIENT_ID_CHECK_RESULTS] = resultsJson @@ -803,8 +1352,26 @@ class SettingsStore(context: Context) { } suspend fun saveActiveProfile(profile: Int) { + val normalized = profile.coerceIn(0, VPN_PROFILE_COUNT - 1) + activeProfileOverride.value = normalized dataStore.edit { prefs -> - prefs[ACTIVE_PROFILE] = profile + prefs[ACTIVE_PROFILE] = normalized + } + } + + suspend fun saveFloatingToolbarYFraction(fraction: Float) { + dataStore.edit { prefs -> + prefs[FLOATING_TOOLBAR_Y_FRACTION] = fraction.coerceIn(0f, 1f) + } + } + + suspend fun saveActiveTunnelProfile(profile: Int?) { + dataStore.edit { prefs -> + if (profile == null) { + prefs.remove(ACTIVE_TUNNEL_PROFILE) + } else { + prefs[ACTIVE_TUNNEL_PROFILE] = profile.coerceIn(0, VPN_PROFILE_COUNT - 1) + } } } @@ -821,6 +1388,53 @@ class SettingsStore(context: Context) { } } + suspend fun saveRemoteCardDismissed(profile: Int, dismissed: Boolean) { + dataStore.edit { prefs -> + val key = getProfileKey( + REMOTE_CARD_DISMISSED, + profile.coerceIn(0, VPN_PROFILE_COUNT - 1) + ) + if (dismissed) { + prefs[key] = true + } else { + prefs.remove(key) + } + } + } + + suspend fun saveAccessLifecycleDismissedSignature(profile: Int, signature: String) { + dataStore.edit { prefs -> + val key = getProfileKey( + ACCESS_LIFECYCLE_DISMISSED_SIGNATURE, + profile.coerceIn(0, VPN_PROFILE_COUNT - 1) + ) + if (signature.isBlank()) { + prefs.remove(key) + } else { + prefs[key] = signature + } + } + } + + 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)) + } + } + suspend fun saveShowSystemApps(enabled: Boolean) { dataStore.edit { prefs -> prefs[SHOW_SYSTEM_APPS] = enabled @@ -893,7 +1507,7 @@ class SettingsStore(context: Context) { } suspend fun createWdttDeepLinkApplyPlan(link: String): WdttDeepLinkApplyPlan? { - WdttDeepLink.parse(link) ?: return null + WdttDeepLink.parse(link, allowMissingHashes = true) ?: return null val cleanLink = link.trim() return appContext.dataStore.data.map { prefs -> val activeProfile = (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1) @@ -909,6 +1523,51 @@ class SettingsStore(context: Context) { }.first() } + suspend fun tunnelProfileSnapshot(profileIndex: Int? = null): TunnelProfileSnapshot = + preferencesFlow.map { prefs -> + val profile = (profileIndex ?: prefs[ACTIVE_PROFILE] ?: 0) + .coerceIn(0, VPN_PROFILE_COUNT - 1) + TunnelProfileSnapshot( + profileIndex = profile, + remoteManaged = prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true, + linkMode = prefs[getProfileKey(WDTT_LINK_MODE, profile)] ?: false, + link = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty(), + peer = prefs[getProfileKey(PEER, profile)].orEmpty(), + vkHashes = prefs[getProfileKey(VK_HASHES, profile)].orEmpty(), + secondaryVkHash = prefs[getProfileKey(SECONDARY_VK_HASH, profile)].orEmpty(), + connectionPassword = readSecret( + prefs, + CONNECTION_PASSWORD_ENCRYPTED, + CONNECTION_PASSWORD, + profile + ), + workersPerHash = prefs[getProfileKey(WORKERS_PER_HASH, profile)] ?: 18, + profileMaxWorkers = (prefs[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0) + .coerceIn(0, APP_MAX_WORKERS), + manualPortsEnabled = prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] ?: false, + serverDtlsPort = prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000, + listenPort = prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000, + sni = prefs[getProfileKey(SNI, profile)].orEmpty(), + protocol = prefs[getProfileKey(PROTOCOL, profile)] ?: "udp", + vkCallsPreflight = prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true, + captchaMode = prefs[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto", + captchaSolveMethod = prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto", + fingerprint = prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox", + clientIds = prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: DEFAULT_VK_CLIENT_IDS, + customVkCredentialsEnabled = + prefs[getProfileKey(CUSTOM_VK_CREDENTIALS_ENABLED, profile)] ?: false, + customVkClientId = normalizeVkClientId( + prefs[getProfileKey(CUSTOM_VK_CLIENT_ID, profile)].orEmpty() + ), + customVkClientSecret = readSecret( + prefs, + CUSTOM_VK_CLIENT_SECRET_ENCRYPTED, + CUSTOM_VK_CLIENT_SECRET, + profile + ), + ) + }.first() + suspend fun connectionLinkForProfile(profileIndex: Int): String { val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) return appContext.dataStore.data.map { prefs -> @@ -920,14 +1579,18 @@ class SettingsStore(context: Context) { wgPort = prefs[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001, localPort = prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000, password = readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile), - hashes = prefs[getProfileKey(VK_HASHES, profile)].orEmpty() + hashes = prefs[getProfileKey(VK_HASHES, profile)].orEmpty(), + maxWorkers = prefs[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0 ) val names = (0 until VPN_PROFILE_COUNT).map { index -> prefs[getProfileKey(PROFILE_NAME, index)].orEmpty() } val profileLabel = vpnProfileDisplayName(profile, names) val link = WdttTransferCodec.buildConnectionLink( - parts.copy(profileName = vpnProfileTransferName(profile, names)) + parts.copy( + profileName = vpnProfileTransferName(profile, names), + maxWorkers = prefs[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0 + ) ) val validation = WdttDeepLink.validate(link) require(validation.canStartVpn) { @@ -943,10 +1606,17 @@ class SettingsStore(context: Context) { profiles.put(JSONObject().apply { put("wdttLink", prefs[getProfileKey(WDTT_LINK, profile)].orEmpty()) put("wdttLinkMode", prefs[getProfileKey(WDTT_LINK_MODE, profile)] ?: false) + put( + "connectionInputMethod", + prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] + ?.takeIf { it == "link" || it == "manual" } + .orEmpty() + ) put("peer", prefs[getProfileKey(PEER, profile)].orEmpty()) put("vkHashes", prefs[getProfileKey(VK_HASHES, profile)].orEmpty()) put("secondaryVkHash", prefs[getProfileKey(SECONDARY_VK_HASH, profile)].orEmpty()) - put("workersPerHash", prefs[getProfileKey(WORKERS_PER_HASH, profile)] ?: 16) + put("workersPerHash", prefs[getProfileKey(WORKERS_PER_HASH, profile)] ?: 18) + put("profileMaxWorkers", prefs[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0) put("protocol", prefs[getProfileKey(PROTOCOL, profile)] ?: "udp") put("listenPort", prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000) put("manualPortsEnabled", prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] ?: false) @@ -1003,6 +1673,7 @@ class SettingsStore(context: Context) { }.first() suspend fun importAdminSettings(settingsJson: String) { + activeProfileOverride.value = null val root = runCatching { JSONObject(settingsJson) } .getOrElse { throw IllegalArgumentException("Расшифрованные настройки повреждены.") } require(root.optString("format") == "wdtt-plus-admin-settings" && root.optInt("version") == 1) { @@ -1015,14 +1686,51 @@ class SettingsStore(context: Context) { dataStore.edit { prefs -> repeat(VPN_PROFILE_COUNT) { profile -> val item = profiles.getJSONObject(profile) - prefs[getProfileKey(WDTT_LINK, profile)] = item.optString("wdttLink") - prefs[getProfileKey(WDTT_LINK_MODE, profile)] = item.optBoolean("wdttLinkMode") - prefs[getProfileKey(PEER, profile)] = item.optString("peer") + prefs.putSecret( + REMOTE_ACTION_KEY_ENCRYPTED, + REMOTE_ACTION_KEY, + "", + profile, + ) + prefs.remove(getProfileKey(REMOTE_ACTION_URL, profile)) + prefs.remove(getProfileKey(REMOTE_DOCUMENT_BINDING, profile)) + prefs.remove(getProfileKey(REMOTE_MANAGED_PROFILE, profile)) + prefs.clearAccessLifecycle(profile) + val importedLink = item.optString("wdttLink") + val importedLinkMode = item.optBoolean("wdttLinkMode") + val importedPeer = item.optString("peer") + val importedConnectionPassword = item.optString("connectionPassword") + val importedMethod = item.optString("connectionInputMethod") + .takeIf { it == "link" || it == "manual" } + ?: when { + importedLinkMode && + WdttDeepLink.parse(importedLink, allowMissingHashes = true) != null -> "link" + importedPeer.isNotBlank() && importedConnectionPassword.isNotBlank() -> "manual" + else -> "" + } + prefs[getProfileKey(WDTT_LINK, profile)] = importedLink + prefs[getProfileKey(WDTT_LINK_MODE, profile)] = importedLinkMode + val connectionInputMethodKey = getProfileKey(CONNECTION_INPUT_METHOD, profile) + if (importedMethod.isBlank()) { + prefs.remove(connectionInputMethodKey) + } else { + prefs[connectionInputMethodKey] = importedMethod + } + prefs[getProfileKey(PEER, profile)] = importedPeer prefs[getProfileKey(VK_HASHES, profile)] = item.optString("vkHashes") prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = item.optString("secondaryVkHash") prefs[getProfileKey(VK_HASH_NEXT_SLOT, profile)] = 0 prefs.remove(getProfileKey(EXCLUDED_APPS, profile)) - prefs[getProfileKey(WORKERS_PER_HASH, profile)] = item.optInt("workersPerHash", 16).coerceIn(1, 128) + prefs[getProfileKey(WORKERS_PER_HASH, profile)] = item.optInt("workersPerHash", 18).coerceIn(1, 128) + val importedProfileMaxWorkers = item.optInt("profileMaxWorkers", 0) + if ( + importedProfileMaxWorkers in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS && + importedProfileMaxWorkers % TUNNEL_WORKERS_PER_GROUP == 0 + ) { + prefs[getProfileKey(PROFILE_MAX_WORKERS, profile)] = importedProfileMaxWorkers + } else { + prefs.remove(getProfileKey(PROFILE_MAX_WORKERS, profile)) + } prefs[getProfileKey(PROTOCOL, profile)] = item.optString("protocol", "udp").takeIf { it in setOf("udp", "tcp") } ?: "udp" prefs[getProfileKey(LISTEN_PORT, profile)] = item.safePort("listenPort", 9000) prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = item.optBoolean("manualPortsEnabled") @@ -1032,7 +1740,12 @@ class SettingsStore(context: Context) { prefs[getProfileKey(NO_DTLS, profile)] = item.optBoolean("noDtls") prefs[getProfileKey(NO_DNS, profile)] = item.optBoolean("noDns") prefs[getProfileKey(USER_AGENT, profile)] = item.optString("userAgent") - prefs.putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, item.optString("connectionPassword"), profile) + prefs.putSecret( + CONNECTION_PASSWORD_ENCRYPTED, + CONNECTION_PASSWORD, + importedConnectionPassword, + profile + ) prefs[getProfileKey(DEPLOY_IP, profile)] = item.optString("deployIp") prefs[getProfileKey(DEPLOY_LOGIN, profile)] = item.optString("deployLogin") prefs.putSecret(DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, item.optString("deployPassword"), profile) @@ -1085,34 +1798,29 @@ class SettingsStore(context: Context) { prefs[UPDATE_CHECK_INTERVAL_MINUTES] = updateIntervalMinutes prefs[INTERFACE_ROLE] = "admin" } + activeProfileOverride.value = null importSharedPreferences("wdtt_outbound_forms", root.optJSONObject("outbound") ?: JSONObject()) } - suspend fun applyWdttDeepLink(plan: WdttDeepLinkApplyPlan): WdttDeepLinkApplyResult? { - val parts = WdttDeepLink.parse(plan.link) ?: return null + suspend fun applyWdttDeepLink( + plan: WdttDeepLinkApplyPlan, + resetRemoteContinuation: Boolean = false, + profileMaxWorkers: Int? = null, + remoteManaged: Boolean? = null, + preserveVkHashes: Boolean = false, + ): WdttDeepLinkApplyResult? { + val parts = WdttDeepLink.parse(plan.link, allowMissingHashes = true) ?: return null val profile = plan.targetProfile.coerceIn(0, VPN_PROFILE_COUNT - 1) dataStore.edit { prefs -> - prefs[ACTIVE_PROFILE] = profile - val importedProfileName = vpnProfileRestorableName(parts.profileName) - if (importedProfileName.isNotBlank()) { - val profileNameKey = getProfileKey(PROFILE_NAME, profile) - prefs[profileNameKey] = importedProfileName - } - prefs[getProfileKey(WDTT_LINK_MODE, profile)] = plan.storeAsLink - if (plan.storeAsLink) { - prefs[getProfileKey(WDTT_LINK, profile)] = plan.link - prefs.clearManualTunnelFields(profile) - } else { - prefs.remove(getProfileKey(WDTT_LINK, profile)) - prefs[getProfileKey(PEER, profile)] = parts.host - prefs[getProfileKey(SERVER_DTLS_PORT, profile)] = parts.dtlsPort - prefs[getProfileKey(SERVER_WG_PORT, profile)] = parts.wgPort - prefs[getProfileKey(LISTEN_PORT, profile)] = parts.localPort - prefs.putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, parts.password, profile) - prefs[getProfileKey(VK_HASHES, profile)] = parts.hashes - prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = "" - prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = true - } + prefs.applyWdttDeepLinkParts( + plan = plan, + parts = parts, + profile = profile, + resetRemoteContinuation = resetRemoteContinuation, + profileMaxWorkers = profileMaxWorkers, + remoteManaged = remoteManaged, + preserveVkHashes = preserveVkHashes, + ) } return WdttDeepLinkApplyResult( targetProfile = profile, @@ -1121,6 +1829,144 @@ class SettingsStore(context: Context) { ) } + /** + * Applies a remote profile document as one DataStore transaction. + * + * A remote import changes the tunnel, protected capabilities, lifecycle status and UI role + * together. Publishing each part separately makes Compose rebuild the whole Tunnel tab + * several times and briefly exposes incomplete combinations of those values. + */ + suspend fun applyRemoteDocumentDelivery( + plan: WdttDeepLinkApplyPlan, + delivery: RemoteDocumentDelivery, + isBoundUpdate: Boolean, + existingProfileRedelivery: Boolean = false, + ): WdttDeepLinkApplyResult? { + val parts = WdttDeepLink.parse(plan.link, allowMissingHashes = true) ?: return null + val profile = plan.targetProfile.coerceIn(0, VPN_PROFILE_COUNT - 1) + var alreadyApplied = false + dataStore.edit { prefs -> + if ( + isBoundUpdate && + delivery.profileRevision > 0 && + (prefs[getProfileKey(ACCESS_PROFILE_REVISION, profile)] ?: 0L) >= + delivery.profileRevision + ) { + alreadyApplied = true + return@edit + } + prefs.applyWdttDeepLinkParts( + plan = plan, + parts = parts, + profile = profile, + resetRemoteContinuation = !isBoundUpdate, + profileMaxWorkers = delivery.profileMaxWorkers, + remoteManaged = if (isBoundUpdate) null else true, + preserveVkHashes = delivery.shouldPreserveLocalVkHashes( + existingProfileRedelivery = existingProfileRedelivery, + ), + ) + if (prefs[INTERFACE_ROLE].isNullOrBlank()) { + prefs[INTERFACE_ROLE] = "user" + if (!prefs.contains(PERMISSION_ONBOARDING_COMPLETE)) { + prefs[PERMISSION_ONBOARDING_COMPLETE] = false + } + } + if (delivery.access.available) { + prefs.putRemoteAccessCapability(delivery.access, profile) + delivery.access.initialStatus?.let { status -> + prefs.putAccessLifecycleStatus(profile, status) + } + } + if ( + !isBoundUpdate && + (delivery.binding.isNotBlank() || + delivery.continuation.available || + delivery.access.available) + ) { + prefs.putRemoteContinuation( + continuation = delivery.continuation, + binding = delivery.binding, + profile = profile, + ) + } + if ( + isBoundUpdate && + delivery.profileRevision > 0 + ) { + prefs[getProfileKey(ACCESS_PROFILE_REVISION, profile)] = + delivery.profileRevision + } + } + return WdttDeepLinkApplyResult( + targetProfile = profile, + overwritten = plan.requiresConfirmation, + storedAsLink = plan.storeAsLink, + alreadyApplied = alreadyApplied, + ) + } + + private fun MutablePreferences.applyWdttDeepLinkParts( + plan: WdttDeepLinkApplyPlan, + parts: WdttLinkParts, + profile: Int, + resetRemoteContinuation: Boolean, + profileMaxWorkers: Int?, + remoteManaged: Boolean?, + preserveVkHashes: Boolean, + ) { + this[ACTIVE_PROFILE] = profile + if (resetRemoteContinuation) { + putSecret( + REMOTE_ACTION_KEY_ENCRYPTED, + REMOTE_ACTION_KEY, + "", + profile, + ) + remove(getProfileKey(REMOTE_ACTION_URL, profile)) + remove(getProfileKey(REMOTE_DOCUMENT_BINDING, profile)) + remove(getProfileKey(REMOTE_MANAGED_PROFILE, profile)) + clearAccessLifecycle(profile) + } + remoteManaged?.let { managed -> + val key = getProfileKey(REMOTE_MANAGED_PROFILE, profile) + if (managed) this[key] = true else remove(key) + } + val requestedLimit = profileMaxWorkers + ?.takeIf { it >= TUNNEL_WORKERS_PER_GROUP } + ?: parts.maxWorkers + val normalizedLimit = (requestedLimit / TUNNEL_WORKERS_PER_GROUP) * + TUNNEL_WORKERS_PER_GROUP + if (normalizedLimit >= TUNNEL_WORKERS_PER_GROUP) { + this[getProfileKey(PROFILE_MAX_WORKERS, profile)] = + normalizedLimit.coerceAtMost(APP_MAX_WORKERS) + } else { + remove(getProfileKey(PROFILE_MAX_WORKERS, profile)) + } + val importedProfileName = vpnProfileRestorableName(parts.profileName) + if (importedProfileName.isNotBlank()) { + this[getProfileKey(PROFILE_NAME, profile)] = importedProfileName + } + this[getProfileKey(WDTT_LINK_MODE, profile)] = plan.storeAsLink + this[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = "link" + if (plan.storeAsLink) { + this[getProfileKey(WDTT_LINK, profile)] = plan.link + clearManualTunnelFields(profile) + } else { + remove(getProfileKey(WDTT_LINK, profile)) + this[getProfileKey(PEER, profile)] = parts.host + this[getProfileKey(SERVER_DTLS_PORT, profile)] = parts.dtlsPort + this[getProfileKey(SERVER_WG_PORT, profile)] = parts.wgPort + this[getProfileKey(LISTEN_PORT, profile)] = parts.localPort + putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, parts.password, profile) + if (!preserveVkHashes) { + this[getProfileKey(VK_HASHES, profile)] = parts.hashes + this[getProfileKey(SECONDARY_VK_HASH, profile)] = "" + } + this[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = parts.hasNonStandardPorts() + } + } + suspend fun saveWdttLinkMode(enabled: Boolean) { dataStore.edit { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 @@ -1128,6 +1974,44 @@ class SettingsStore(context: Context) { } } + suspend fun materializeActiveLinkProfile(): WdttLinkParts? { + val snapshot = dataStore.data.first() + val profile = (snapshot[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1) + if (snapshot[getProfileKey(WDTT_LINK_MODE, profile)] != true) return null + val storedLink = snapshot[getProfileKey(WDTT_LINK, profile)].orEmpty() + val parts = WdttDeepLink.parse(storedLink, allowMissingHashes = true) ?: return null + var applied = false + dataStore.edit { prefs -> + if ( + (prefs[ACTIVE_PROFILE] ?: 0) != profile || + prefs[getProfileKey(WDTT_LINK, profile)].orEmpty() != storedLink + ) { + return@edit + } + prefs[getProfileKey(WDTT_LINK_MODE, profile)] = false + prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = "link" + prefs.remove(getProfileKey(WDTT_LINK, profile)) + prefs[getProfileKey(PEER, profile)] = parts.host + prefs[getProfileKey(SERVER_DTLS_PORT, profile)] = parts.dtlsPort + prefs[getProfileKey(SERVER_WG_PORT, profile)] = parts.wgPort + prefs[getProfileKey(LISTEN_PORT, profile)] = parts.localPort + prefs.putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, parts.password, profile) + prefs[getProfileKey(VK_HASHES, profile)] = parts.hashes + prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = "" + prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = parts.hasNonStandardPorts() + if (parts.maxWorkers >= TUNNEL_WORKERS_PER_GROUP) { + prefs[getProfileKey(PROFILE_MAX_WORKERS, profile)] = + parts.maxWorkers.coerceAtMost(APP_MAX_WORKERS) + } + val importedProfileName = vpnProfileRestorableName(parts.profileName) + if (importedProfileName.isNotBlank()) { + prefs[getProfileKey(PROFILE_NAME, profile)] = importedProfileName + } + applied = true + } + return parts.takeIf { applied } + } + suspend fun save( peer: String, vkHashes: String, @@ -1158,9 +2042,307 @@ class SettingsStore(context: Context) { } } + suspend fun saveRemoteContinuation( + continuation: RemoteContinuation, + binding: String, + profileIndex: Int? = null + ) { + dataStore.edit { prefs -> + val profile = (profileIndex ?: prefs[ACTIVE_PROFILE] ?: 0) + .coerceIn(0, VPN_PROFILE_COUNT - 1) + prefs.putRemoteContinuation(continuation, binding, profile) + } + } + + suspend fun saveRemoteAccessCapability( + capability: RemoteAccessCapability, + profileIndex: Int, + ) { + if (!capability.available) return + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + prefs.putRemoteAccessCapability(capability, profile) + } + } + + suspend fun accessLifecycleForProfile(profileIndex: Int): StoredAccessLifecycle { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + return preferencesFlow.map { prefs -> + readStoredAccessLifecycle(prefs, profile) + }.first() + } + + suspend fun accessLifecycleProfiles(): List = preferencesFlow.map { prefs -> + (0 until VPN_PROFILE_COUNT).filter { profile -> + readStoredAccessLifecycle(prefs, profile).capability.available + } + }.first() + + suspend fun saveAccessLifecycleAttempt(profileIndex: Int, attemptedAtMillis: Long) { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + prefs[getProfileKey(ACCESS_LAST_ATTEMPT_AT, profile)] = + attemptedAtMillis.coerceAtLeast(0) + } + } + + suspend fun saveAccessLifecycleStatus( + profileIndex: Int, + status: AccessLifecycleStatus, + expectedCapability: RemoteAccessCapability? = null, + ): Boolean { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + var saved = false + dataStore.edit { prefs -> + if ( + expectedCapability != null && + readStoredAccessLifecycle(prefs, profile).capability != expectedCapability + ) { + return@edit + } + prefs.putAccessLifecycleStatus(profile, status) + saved = true + } + return saved + } + + suspend fun markAccessLifecycleDenied(profileIndex: Int) { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + if (prefs[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].isNullOrBlank()) return@edit + prefs[getProfileKey(ACCESS_ALLOW_CONNECT, profile)] = false + prefs[getProfileKey(ACCESS_TITLE, profile)] = "Профиль недоступен" + prefs[getProfileKey(ACCESS_MESSAGE, profile)] = + "Откройте профиль, чтобы обновить его состояние." + prefs[getProfileKey(ACCESS_SEVERITY, profile)] = "error" + prefs[getProfileKey(ACCESS_CHECKED_AT, profile)] = System.currentTimeMillis() + } + } + + suspend fun saveAppliedAccessProfileRevision(profileIndex: Int, revision: Long) { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + prefs[getProfileKey(ACCESS_PROFILE_REVISION, profile)] = revision.coerceAtLeast(0) + } + } + + suspend fun markAccessLifecycleActionLaunched( + profileIndex: Int, + launchedAtMillis: Long = System.currentTimeMillis(), + ) { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + prefs[getProfileKey(ACCESS_ACTION_LAUNCHED_AT, profile)] = + launchedAtMillis.coerceAtLeast(0) + } + } + + suspend fun takeAccessLifecycleActionProfiles(): Set { + val profiles = mutableSetOf() + dataStore.edit { prefs -> + repeat(VPN_PROFILE_COUNT) { profile -> + val key = getProfileKey(ACCESS_ACTION_LAUNCHED_AT, profile) + if ((prefs[key] ?: 0) > 0) profiles += profile + prefs.remove(key) + } + } + return profiles + } + + suspend fun remoteBindingForProfile(profileIndex: Int): String { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + return preferencesFlow.map { prefs -> + prefs[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty() + }.first() + } + + suspend fun remoteAccessBindingForProfile(profileIndex: Int): String { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + return preferencesFlow.map { prefs -> + prefs[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)].orEmpty() + }.first() + } + + suspend fun remoteDocumentBindings(): List = + appContext.dataStore.data.map { prefs -> + buildList { + repeat(VPN_PROFILE_COUNT) { profile -> + add(prefs[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty()) + add(prefs[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)].orEmpty()) + } + } + .map(String::trim) + .filter(String::isNotBlank) + .distinct() + }.first() + + suspend fun remoteContinuationForProfile(profileIndex: Int): RemoteContinuation { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + return appContext.dataStore.data.map { prefs -> + val key = readSecret( + prefs, + REMOTE_ACTION_KEY_ENCRYPTED, + REMOTE_ACTION_KEY, + profile + ) + val url = prefs[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty() + RemoteContinuation( + available = key.isNotBlank() && url.isNotBlank(), + key = key, + url = url + ) + }.first() + } + + suspend fun profileForRemoteBinding(binding: String): Int? { + val expected = binding.trim() + if (expected.isBlank()) return null + return appContext.dataStore.data.map { prefs -> + (0 until VPN_PROFILE_COUNT).firstOrNull { profile -> + prefs[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)] == expected || + prefs[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)] == expected + } + }.first() + } + + /** + * Finds an already imported copy of the same connection when an optional setup-device + * binding was rotated. The access password is unique to the connection; matching it together + * with the remote endpoint avoids treating another profile on the same server as the same + * connection. + */ + suspend fun profileForConnectionDocument(document: String): Int? { + val expected = WdttDeepLink.parse(document, allowMissingHashes = true) ?: return null + if (expected.host.isBlank() || expected.password.isBlank()) return null + return appContext.dataStore.data.map { prefs -> + (0 until VPN_PROFILE_COUNT).firstOrNull { profile -> + val stored = if (prefs[getProfileKey(WDTT_LINK_MODE, profile)] == true) { + WdttDeepLink.parse( + prefs[getProfileKey(WDTT_LINK, profile)].orEmpty(), + allowMissingHashes = true, + ) + } else { + null + } + val host = stored?.host + ?: prefs[getProfileKey(PEER, profile)].orEmpty().trim() + val dtlsPort = stored?.dtlsPort + ?: prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000 + val wgPort = stored?.wgPort + ?: prefs[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001 + val password = stored?.password + ?: readSecret( + prefs, + CONNECTION_PASSWORD_ENCRYPTED, + CONNECTION_PASSWORD, + profile, + ) + host.equals(expected.host, ignoreCase = true) && + dtlsPort == expected.dtlsPort && + wgPort == expected.wgPort && + password == expected.password + } + }.first() + } + + suspend fun saveVkHashesForProfile(profile: Int, hashes: List) { + val cleaned = hashes + .map(VkJoinLink::extractHash) + .filter(VkJoinLink::isValidHash) + .distinct() + require(cleaned.size in 1..4) { "Добавьте от 1 до 4 корректных VK-хешей." } + dataStore.edit { prefs -> + val safeProfile = profile.coerceIn(0, VPN_PROFILE_COUNT - 1) + prefs[getProfileKey(VK_HASHES, safeProfile)] = cleaned.joinToString(",") + prefs[getProfileKey(SECONDARY_VK_HASH, safeProfile)] = "" + prefs[getProfileKey(PROFILE_VALUES_SYNC_PENDING, safeProfile)] = true + } + } + + suspend fun markProfileValuesSyncPending(profileIndex: Int) { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + prefs[getProfileKey(PROFILE_VALUES_SYNC_PENDING, profile)] = true + } + } + + suspend fun clearProfileValuesSyncPending(profileIndex: Int) { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + prefs.remove(getProfileKey(PROFILE_VALUES_SYNC_PENDING, profile)) + } + } + + suspend fun profileValuesSyncPending(profileIndex: Int): Boolean { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + return preferencesFlow.map { prefs -> + prefs[getProfileKey(PROFILE_VALUES_SYNC_PENDING, profile)] == true + }.first() + } + + suspend fun mergeVkHashesForProfile(profile: Int, hashes: List): Int { + val cleaned = hashes + .map(VkJoinLink::extractHash) + .filter(VkJoinLink::isValidHash) + .distinct() + .take(4) + if (cleaned.isEmpty()) return 0 + var added = 0 + dataStore.edit { prefs -> + val safeProfile = profile.coerceIn(0, VPN_PROFILE_COUNT - 1) + val key = getProfileKey(VK_HASHES, safeProfile) + val slots = parseVkHashSlots(prefs[key].orEmpty()) + cleaned.forEach { hash -> + if (hash !in slots) { + val empty = slots.indexOfFirst { it.isBlank() } + if (empty >= 0) { + slots[empty] = hash + added += 1 + } + } + } + if (added > 0) { + prefs[key] = slots.joinToString(",") + prefs[getProfileKey(SECONDARY_VK_HASH, safeProfile)] = "" + } + } + return added + } + + suspend fun getOrCreateConnectDeviceId(): String { + val tunnelDeviceId = getOrCreateTunnelDeviceId() + var resolved = "" + dataStore.edit { prefs -> + resolved = DeviceIdentity.resolve( + existing = prefs[CONNECT_DEVICE_ID], + platformId = tunnelDeviceId, + generatedId = "android-${UUID.randomUUID()}", + ) + prefs[CONNECT_DEVICE_ID] = resolved + } + return resolved + } + + suspend fun getOrCreateTunnelDeviceId(): String { + val platformId = android.provider.Settings.Secure.getString( + appContext.contentResolver, + android.provider.Settings.Secure.ANDROID_ID, + ) + var resolved = "" + dataStore.edit { prefs -> + resolved = DeviceIdentity.resolve( + existing = prefs[TUNNEL_DEVICE_ID], + platformId = platformId, + generatedId = "android-${UUID.randomUUID()}", + ) + prefs[TUNNEL_DEVICE_ID] = resolved + } + return resolved + } + suspend fun insertVkHashFromShare(hash: String): VkHashInsertResult { val cleanedHash = VkJoinLink.extractHash(hash) - require(cleanedHash.length >= 16) { "VK-хеш слишком короткий" } + require(VkJoinLink.isValidHash(cleanedHash)) { "VK-хеш имеет неверный формат" } var result = VkHashInsertResult(slot = 1, hash = cleanedHash, previousHash = "") dataStore.edit { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 @@ -1179,7 +2361,14 @@ class SettingsStore(context: Context) { prefs[hashesKey] = slots.joinToString(",") prefs[nextSlotKey] = (slotIndex + 1) % 4 - result = VkHashInsertResult(slot = slotIndex + 1, hash = cleanedHash, previousHash = previous) + prefs[getProfileKey(PROFILE_VALUES_SYNC_PENDING, profile)] = true + result = VkHashInsertResult( + slot = slotIndex + 1, + hash = cleanedHash, + previousHash = previous, + profile = profile, + hashes = slots.filter { it.isNotBlank() }, + ) } return result } @@ -1191,7 +2380,7 @@ class SettingsStore(context: Context) { raw.split(Regex("[\\s\\n]+")) } val slots = tokens - .map { VkJoinLink.extractHash(it) } + .map { VkJoinLink.extractValidHash(it) } .take(4) .toMutableList() while (slots.size < 4) { @@ -1332,6 +2521,33 @@ class SettingsStore(context: Context) { prefs.putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, password, profile) } } + + suspend fun saveManualTunnelConnection( + peer: String, + password: String, + manualPortsEnabled: Boolean, + serverDtlsPort: Int, + serverWgPort: Int, + listenPort: Int, + ) { + dataStore.edit { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(WDTT_LINK_MODE, profile)] = false + prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = "manual" + prefs.remove(getProfileKey(WDTT_LINK, profile)) + prefs[getProfileKey(PEER, profile)] = peer.trim() + prefs.putSecret( + CONNECTION_PASSWORD_ENCRYPTED, + CONNECTION_PASSWORD, + password, + profile + ) + prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = manualPortsEnabled + prefs[getProfileKey(SERVER_DTLS_PORT, profile)] = serverDtlsPort + prefs[getProfileKey(SERVER_WG_PORT, profile)] = serverWgPort + prefs[getProfileKey(LISTEN_PORT, profile)] = listenPort + } + } // ═══ Сохранение секретов деплоя ═══ suspend fun saveDeploySecrets(mainPass: String, adminId: String, botToken: String, sshPort: String) { @@ -1369,6 +2585,20 @@ class SettingsStore(context: Context) { } } + suspend fun saveCaptchaPreference(autoEnabled: Boolean) { + dataStore.edit { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + if (autoEnabled) { + prefs[getProfileKey(CAPTCHA_MODE, profile)] = "auto" + prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] = "auto" + } else { + prefs[getProfileKey(CAPTCHA_MODE, profile)] = "wv" + prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] = "manual" + prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] = "manual" + } + } + } + suspend fun saveCaptchaSolveMethod(method: String) { dataStore.edit { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 @@ -1406,6 +2636,14 @@ class SettingsStore(context: Context) { prefs.migrateSecret(getProfileKey(DEPLOY_MAIN_PASSWORD_ENCRYPTED, profile), getProfileKey(DEPLOY_MAIN_PASSWORD, profile)) prefs.migrateSecret(getProfileKey(DEPLOY_ADMIN_ID_ENCRYPTED, profile), getProfileKey(DEPLOY_ADMIN_ID, profile)) prefs.migrateSecret(getProfileKey(DEPLOY_BOT_TOKEN_ENCRYPTED, profile), getProfileKey(DEPLOY_BOT_TOKEN, profile)) + prefs.migrateSecret( + getProfileKey(REMOTE_ACTION_KEY_ENCRYPTED, profile), + getProfileKey(REMOTE_ACTION_KEY, profile) + ) + prefs.migrateSecret( + getProfileKey(CUSTOM_VK_CLIENT_SECRET_ENCRYPTED, profile), + getProfileKey(CUSTOM_VK_CLIENT_SECRET, profile) + ) } } } @@ -1445,6 +2683,326 @@ class SettingsStore(context: Context) { } } + private suspend fun repairInvalidLinkModes() { + dataStore.edit { prefs -> + for (profile in 0 until VPN_PROFILE_COUNT) { + val modeKey = getProfileKey(WDTT_LINK_MODE, profile) + val storedLink = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty() + val hasStoredLink = + WdttDeepLink.parse(storedLink, allowMissingHashes = true) != null + val hasManualConnection = prefs[getProfileKey(PEER, profile)].orEmpty().isNotBlank() && + readSecret( + prefs, + CONNECTION_PASSWORD_ENCRYPTED, + CONNECTION_PASSWORD, + profile + ).isNotBlank() + var linkMode = prefs[modeKey] == true + if (linkMode && !hasStoredLink && hasManualConnection) { + prefs[modeKey] = false + linkMode = false + } + + val methodKey = getProfileKey(CONNECTION_INPUT_METHOD, profile) + if (prefs[methodKey] != "link" && prefs[methodKey] != "manual") { + when { + linkMode && hasStoredLink -> prefs[methodKey] = "link" + hasManualConnection -> prefs[methodKey] = "manual" + else -> prefs.remove(methodKey) + } + } + } + } + } + + private fun readAccessLifecycleUiState( + prefs: Preferences, + profile: Int, + ): AccessLifecycleUiState = readStoredAccessLifecycle(prefs, profile).toUiState() + + private fun MutablePreferences.putRemoteContinuation( + continuation: RemoteContinuation, + binding: String, + profile: Int, + ) { + putSecret( + REMOTE_ACTION_KEY_ENCRYPTED, + REMOTE_ACTION_KEY, + continuation.key.trim(), + profile, + ) + this[getProfileKey(REMOTE_ACTION_URL, profile)] = continuation.url.trim() + if (binding.isBlank()) { + remove(getProfileKey(REMOTE_DOCUMENT_BINDING, profile)) + } else { + this[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)] = binding.trim() + } + if (binding.isNotBlank() || continuation.available) { + this[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] = true + } + } + + private fun MutablePreferences.putRemoteAccessCapability( + capability: RemoteAccessCapability, + profile: Int, + ) { + val previousKey = readProtectedSecret( + this, + ACCESS_LIFECYCLE_KEY_ENCRYPTED, + profile, + ) + val previousUrl = this[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].orEmpty() + val previousBinding = + this[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)].orEmpty() + if ( + previousKey != capability.key || + previousUrl != capability.url || + previousBinding != capability.binding + ) { + clearAccessLifecycleStatus(profile) + } + putProtectedSecret( + ACCESS_LIFECYCLE_KEY_ENCRYPTED, + capability.key.trim(), + profile, + ) + this[getProfileKey(ACCESS_LIFECYCLE_URL, profile)] = capability.url.trim() + this[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)] = capability.binding.trim() + putCachedRemoteAction(capability.cachedAction, profile) + putProfileExchange(capability.exchange, profile) + this[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] = true + } + + private fun MutablePreferences.putCachedRemoteAction( + action: CachedRemoteAction, + profile: Int, + ) { + putProtectedSecret( + CACHED_ACTION_PAYLOAD_ENCRYPTED, + action.payload.takeIf { action.available }.orEmpty(), + profile, + ) + val values = listOf( + kotlin.Pair(CACHED_ACTION_URL, action.target.primaryUrl), + kotlin.Pair(CACHED_ACTION_FALLBACK, action.target.fallbackUrl), + kotlin.Pair(CACHED_ACTION_HANDLER, action.target.preferredHandler), + kotlin.Pair(CACHED_ACTION_TITLE, action.title), + kotlin.Pair(CACHED_ACTION_MESSAGE, action.message), + kotlin.Pair(CACHED_ACTION_LABEL, action.label), + kotlin.Pair(CACHED_ACTION_CLIPBOARD_LABEL, action.clipboardLabel), + kotlin.Pair(CACHED_ACTION_COPIED_MESSAGE, action.copiedMessage), + kotlin.Pair(CACHED_ACTION_FAILED_MESSAGE, action.failedMessage), + kotlin.Pair(CACHED_ACTION_HELP_TITLE, action.helpTitle), + kotlin.Pair(CACHED_ACTION_HELP_INTRO, action.helpIntro), + kotlin.Pair(CACHED_ACTION_HELP_STEPS, action.helpSteps), + ) + values.forEach { (key, value) -> + val profileKey = getProfileKey(key, profile) + if (action.available && value.isNotBlank()) { + this[profileKey] = value + } else { + remove(profileKey) + } + } + } + + private fun MutablePreferences.putProfileExchange( + exchange: RemoteProfileExchange, + profile: Int, + ) { + putProtectedSecret( + PROFILE_EXCHANGE_SUBMIT_TOKEN_ENCRYPTED, + exchange.submitToken.takeIf { exchange.submitAvailable }.orEmpty(), + profile, + ) + putProtectedSecret( + PROFILE_EXCHANGE_ACTION_TOKEN_ENCRYPTED, + exchange.actionToken, + profile, + ) + this[getProfileKey(PROFILE_EXCHANGE_ACTION_AVAILABLE, profile)] = + exchange.actionAvailable + this[getProfileKey(PROFILE_EXCHANGE_ACTION_LABEL, profile)] = exchange.label + this[getProfileKey(PROFILE_EXCHANGE_ACTION_MESSAGE, profile)] = exchange.message + } + + private fun MutablePreferences.putAccessLifecycleStatus( + profile: Int, + status: AccessLifecycleStatus, + ) { + if (status.cachedAction.available) { + putCachedRemoteAction(status.cachedAction, profile) + } + status.exchange?.let { putProfileExchange(it, profile) } + 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 + this[getProfileKey(ACCESS_ACTION_LABEL, profile)] = status.actionLabel + this[getProfileKey(ACCESS_ACTION_MESSAGE, profile)] = status.actionMessage + this[getProfileKey(ACCESS_TITLE, profile)] = status.title + this[getProfileKey(ACCESS_MESSAGE, profile)] = status.message + this[getProfileKey(ACCESS_DETAIL_LABEL, profile)] = status.detailLabel + this[getProfileKey(ACCESS_DETAIL_VALUE, profile)] = status.detailValue + this[getProfileKey(ACCESS_ACTION_ICON, profile)] = status.actionIcon + this[getProfileKey(ACCESS_SEVERITY, profile)] = status.severity.name.lowercase() + } + + private fun readStoredAccessLifecycle( + prefs: Preferences, + profile: Int, + ): StoredAccessLifecycle { + val key = readProtectedSecret(prefs, ACCESS_LIFECYCLE_KEY_ENCRYPTED, profile) + val url = prefs[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].orEmpty() + val binding = prefs[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)].orEmpty() + val capability = RemoteAccessCapability( + available = key.isNotBlank() && url.isNotBlank() && binding.isNotBlank(), + key = key, + url = url, + binding = binding, + cachedAction = readCachedRemoteAction(prefs, profile), + exchange = readProfileExchange(prefs, profile), + ) + val hasStatus = (prefs[getProfileKey(ACCESS_CHECKED_AT, profile)] ?: 0) > 0 + val status = if (hasStatus) { + val allowConnect = prefs[getProfileKey(ACCESS_ALLOW_CONNECT, profile)] ?: false + AccessLifecycleStatus( + allowConnect = allowConnect, + actionAvailable = + prefs[getProfileKey(ACCESS_ACTION_AVAILABLE, profile)] ?: false, + actionLabel = prefs[getProfileKey(ACCESS_ACTION_LABEL, profile)].orEmpty(), + actionMessage = prefs[getProfileKey(ACCESS_ACTION_MESSAGE, profile)].orEmpty(), + title = prefs[getProfileKey(ACCESS_TITLE, profile)].orEmpty(), + message = prefs[getProfileKey(ACCESS_MESSAGE, profile)].orEmpty(), + detailLabel = + prefs[getProfileKey(ACCESS_DETAIL_LABEL, profile)].orEmpty(), + detailValue = + prefs[getProfileKey(ACCESS_DETAIL_VALUE, profile)].orEmpty(), + actionIcon = + prefs[getProfileKey(ACCESS_ACTION_ICON, profile)].orEmpty(), + severity = AccessLifecycleSeverity.parse( + prefs[getProfileKey(ACCESS_SEVERITY, profile)].orEmpty(), + allowConnect, + ), + checkedAtMillis = prefs[getProfileKey(ACCESS_CHECKED_AT, profile)] ?: 0, + profileRevision = + prefs[getProfileKey(ACCESS_PROFILE_REVISION, profile)] ?: 0, + ) + } else { + null + } + return StoredAccessLifecycle( + managed = capability.available, + capability = capability, + status = status, + appliedProfileRevision = + prefs[getProfileKey(ACCESS_PROFILE_REVISION, profile)] ?: 0, + lastAttemptAtMillis = + prefs[getProfileKey(ACCESS_LAST_ATTEMPT_AT, profile)] ?: 0, + ) + } + + private fun readCachedRemoteAction( + prefs: Preferences, + profile: Int, + ): CachedRemoteAction { + val payload = readProtectedSecret(prefs, CACHED_ACTION_PAYLOAD_ENCRYPTED, profile) + val primary = prefs[getProfileKey(CACHED_ACTION_URL, profile)].orEmpty() + if (payload.isBlank() || primary.isBlank()) return CachedRemoteAction.Unavailable + return CachedRemoteAction( + available = true, + payload = payload, + target = RemoteLaunchTarget( + primaryUrl = primary, + fallbackUrl = prefs[getProfileKey(CACHED_ACTION_FALLBACK, profile)].orEmpty(), + preferredHandler = prefs[getProfileKey(CACHED_ACTION_HANDLER, profile)].orEmpty(), + ), + title = prefs[getProfileKey(CACHED_ACTION_TITLE, profile)].orEmpty(), + message = prefs[getProfileKey(CACHED_ACTION_MESSAGE, profile)].orEmpty(), + label = prefs[getProfileKey(CACHED_ACTION_LABEL, profile)].orEmpty(), + clipboardLabel = + prefs[getProfileKey(CACHED_ACTION_CLIPBOARD_LABEL, profile)].orEmpty(), + copiedMessage = + prefs[getProfileKey(CACHED_ACTION_COPIED_MESSAGE, profile)].orEmpty(), + failedMessage = + prefs[getProfileKey(CACHED_ACTION_FAILED_MESSAGE, profile)].orEmpty(), + helpTitle = prefs[getProfileKey(CACHED_ACTION_HELP_TITLE, profile)].orEmpty(), + helpIntro = prefs[getProfileKey(CACHED_ACTION_HELP_INTRO, profile)].orEmpty(), + helpSteps = prefs[getProfileKey(CACHED_ACTION_HELP_STEPS, profile)].orEmpty(), + ) + } + + private fun readProfileExchange( + prefs: Preferences, + profile: Int, + ): RemoteProfileExchange { + val submitToken = readProtectedSecret( + prefs, + PROFILE_EXCHANGE_SUBMIT_TOKEN_ENCRYPTED, + profile, + ) + val actionToken = readProtectedSecret( + prefs, + PROFILE_EXCHANGE_ACTION_TOKEN_ENCRYPTED, + profile, + ) + return if (submitToken.isNotBlank() || actionToken.isNotBlank()) { + RemoteProfileExchange( + submitAvailable = submitToken.isNotBlank(), + submitToken = submitToken, + actionAvailable = + prefs[getProfileKey(PROFILE_EXCHANGE_ACTION_AVAILABLE, profile)] == true && + actionToken.isNotBlank(), + actionToken = actionToken, + label = + prefs[getProfileKey(PROFILE_EXCHANGE_ACTION_LABEL, profile)].orEmpty(), + message = + prefs[getProfileKey(PROFILE_EXCHANGE_ACTION_MESSAGE, profile)].orEmpty(), + ) + } else { + RemoteProfileExchange.Unavailable + } + } + + private fun readProtectedSecret( + prefs: Preferences, + encryptedKey: Preferences.Key, + profile: Int, + ): String = secureStore.decrypt(prefs[getProfileKey(encryptedKey, profile)]).orEmpty() + + private fun MutablePreferences.putProtectedSecret( + encryptedKey: Preferences.Key, + value: String, + profile: Int, + ) { + val key = getProfileKey(encryptedKey, profile) + if (value.isBlank()) remove(key) else this[key] = secureStore.encrypt(value) + } + + private fun MutablePreferences.clearAccessLifecycleStatus(profile: Int) { + remove(getProfileKey(ACCESS_ALLOW_CONNECT, profile)) + remove(getProfileKey(ACCESS_ACTION_AVAILABLE, profile)) + remove(getProfileKey(ACCESS_ACTION_LABEL, profile)) + remove(getProfileKey(ACCESS_ACTION_MESSAGE, profile)) + remove(getProfileKey(ACCESS_TITLE, profile)) + remove(getProfileKey(ACCESS_MESSAGE, profile)) + remove(getProfileKey(ACCESS_DETAIL_LABEL, profile)) + remove(getProfileKey(ACCESS_DETAIL_VALUE, profile)) + remove(getProfileKey(ACCESS_ACTION_ICON, profile)) + remove(getProfileKey(ACCESS_SEVERITY, profile)) + remove(getProfileKey(ACCESS_CHECKED_AT, profile)) + remove(getProfileKey(ACCESS_LAST_ATTEMPT_AT, profile)) + remove(getProfileKey(ACCESS_ACTION_LAUNCHED_AT, profile)) + } + + private fun MutablePreferences.clearAccessLifecycle(profile: Int) { + remove(getProfileKey(ACCESS_LIFECYCLE_KEY_ENCRYPTED, profile)) + remove(getProfileKey(ACCESS_LIFECYCLE_URL, profile)) + remove(getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)) + remove(getProfileKey(ACCESS_PROFILE_REVISION, profile)) + putCachedRemoteAction(CachedRemoteAction.Unavailable, profile) + clearAccessLifecycleStatus(profile) + } + private fun readSecret( prefs: Preferences, encryptedKey: Preferences.Key, @@ -1515,6 +3073,12 @@ class SettingsStore(context: Context) { private fun exportSharedPreferences(name: String): JSONObject { val result = JSONObject() appContext.getSharedPreferences(name, Context.MODE_PRIVATE).all.forEach { (key, value) -> + if (name == "wdtt_outbound_forms" && key.endsWith("_encrypted") && value is String) { + secureStore.decrypt(value)?.let { decrypted -> + result.put(key.removeSuffix("_encrypted"), decrypted) + } + return@forEach + } when (value) { is String, is Boolean, is Int, is Long, is Float -> result.put(key, value) is Set<*> -> result.put(key, JSONArray(value.filterIsInstance())) @@ -1529,7 +3093,15 @@ class SettingsStore(context: Context) { while (keys.hasNext()) { val key = keys.next() when (val value = json.get(key)) { - is String -> editor.putString(key, value) + is String -> { + if (name == "wdtt_outbound_forms" && isOutboundPreferenceSecretKey(key)) { + if (value.isNotBlank()) { + editor.putString("${key}_encrypted", secureStore.encrypt(value)) + } + } else { + editor.putString(key, value) + } + } is Boolean -> editor.putBoolean(key, value) is Int -> editor.putInt(key, value) is Long -> editor.putLong(key, value) @@ -1543,6 +3115,14 @@ class SettingsStore(context: Context) { editor.apply() } + private fun isOutboundPreferenceSecretKey(key: String): Boolean = + listOf( + "local_proxy_password", + "external_proxy_password", + "wg_exit_password", + "imported_wg_config", + ).any { secretName -> key == secretName || key.endsWith("_$secretName") } + private fun JSONObject.safePort(name: String, fallback: Int): Int = optInt(name, fallback).takeIf { it in 1..65535 } ?: fallback } diff --git a/app/src/main/java/com/wdtt/plus/TransferCodec.kt b/app/src/main/java/com/wdtt/plus/TransferCodec.kt index 048c4d9..98c8275 100644 --- a/app/src/main/java/com/wdtt/plus/TransferCodec.kt +++ b/app/src/main/java/com/wdtt/plus/TransferCodec.kt @@ -45,6 +45,12 @@ object WdttTransferCodec { normalizeVpnProfileName(parts.profileName) .takeIf { it.isNotBlank() } ?.let { values["name"] = it } + parts.maxWorkers + .takeIf { + it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS && + it % TUNNEL_WORKERS_PER_GROUP == 0 + } + ?.let { values["max_workers"] = it.toString() } return "wdtt://connect?" + values.entries.joinToString("&") { (key, value) -> "${encode(key)}=${encode(value)}" } @@ -66,6 +72,12 @@ object WdttTransferCodec { } .toMap() if (values["v"] != "1") return null + val maxWorkers = values["max_workers"]?.takeIf { it.isNotBlank() }?.let { raw -> + raw.toIntOrNull()?.takeIf { + it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS && + it % TUNNEL_WORKERS_PER_GROUP == 0 + } ?: return null + } ?: 0 return WdttLinkParts( host = values["host"].orEmpty(), dtlsPort = values["dtls"]?.toIntOrNull() ?: return null, @@ -73,7 +85,8 @@ object WdttTransferCodec { localPort = values["local"]?.toIntOrNull() ?: return null, password = values["password"].orEmpty(), hashes = values["hashes"].orEmpty(), - profileName = values["name"].orEmpty() + profileName = values["name"].orEmpty(), + maxWorkers = maxWorkers ) } diff --git a/app/src/main/java/com/wdtt/plus/TrustedWifi.kt b/app/src/main/java/com/wdtt/plus/TrustedWifi.kt index 58822bd..c9c590d 100644 --- a/app/src/main/java/com/wdtt/plus/TrustedWifi.kt +++ b/app/src/main/java/com/wdtt/plus/TrustedWifi.kt @@ -13,6 +13,7 @@ import android.provider.Settings import androidx.core.content.ContextCompat import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow +import java.util.concurrent.ConcurrentHashMap private const val UNKNOWN_WIFI_SSID = "" private const val BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION" @@ -23,6 +24,50 @@ data class TrustedWifiRuntimeState( val status: String = "" ) +internal data class TrustedWifiResumeRetryPlan( + val delayMs: Long, + val keepCpuAwake: Boolean +) + +internal fun trustedWifiResumeRetryPlan(retryCount: Int): TrustedWifiResumeRetryPlan = + if (retryCount.coerceAtLeast(0) < 12) { + TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true) + } else { + TrustedWifiResumeRetryPlan(delayMs = 30_000L, keepCpuAwake = false) + } + +internal class TrustedWifiValidatedNetworkTracker { + private val validatedNetworks = ConcurrentHashMap.newKeySet() + private val wifiNetworks = ConcurrentHashMap.newKeySet() + + @Synchronized + fun update(network: T, validated: Boolean, wifi: Boolean) { + if (validated) validatedNetworks.add(network) else validatedNetworks.remove(network) + if (wifi) wifiNetworks.add(network) else wifiNetworks.remove(network) + } + + @Synchronized + fun lost(network: T) { + validatedNetworks.remove(network) + wifiNetworks.remove(network) + } + + @Synchronized + fun forgetWifi() { + wifiNetworks.forEach { network -> validatedNetworks.remove(network) } + wifiNetworks.clear() + } + + @Synchronized + fun hasUsableNetwork(): Boolean = validatedNetworks.isNotEmpty() + + @Synchronized + fun clear() { + validatedNetworks.clear() + wifiNetworks.clear() + } +} + object TrustedWifiManager { private val _state = MutableStateFlow(TrustedWifiRuntimeState()) val state = _state.asStateFlow() diff --git a/app/src/main/java/com/wdtt/plus/TunnelManager.kt b/app/src/main/java/com/wdtt/plus/TunnelManager.kt index 4986462..6a02f48 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelManager.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelManager.kt @@ -40,19 +40,35 @@ data class LogEntry( val isError: Boolean get() = severity == LogSeverity.Error } +@Stable +enum class ConnectionIssueKind { + GENERAL, + ACCESS, +} + @Stable data class ConnectionIssue( val title: String, val action: String, - val isError: Boolean = true + val isError: Boolean = true, + val kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL, ) +internal val ConnectionIssue.isStandaloneUiIssue: Boolean + get() = kind != ConnectionIssueKind.ACCESS + enum class NetworkRecoveryAction { SoftRestart, RecreateVpn, StopVpn } +internal fun stableNetworkRecoveryAction(completedAttempts: Int): NetworkRecoveryAction = when { + completedAttempts <= 0 -> NetworkRecoveryAction.SoftRestart + completedAttempts == 1 -> NetworkRecoveryAction.RecreateVpn + else -> NetworkRecoveryAction.StopVpn +} + enum class TunnelStopReason(val displayText: String) { User("отключено пользователем"), VpnSlotTransferred("VPN-слот передан другому приложению"), @@ -64,7 +80,14 @@ enum class TunnelStopReason(val displayText: String) { CaptchaCancelled("проверка отменена пользователем"), TrustedWifi("подключена доверенная сеть Wi-Fi"), RestoreFailed("не удалось восстановить VPN"), - ServiceDestroyed("служба VPN остановлена системой") + ServiceDestroyed("служба VPN остановлена системой"), + AccessExpired("срок доступа закончился") +} + +enum class TunnelTransition { + IDLE, + STARTING, + STOPPING, } private val stoppedStatsTrafficPairRegex = Regex( @@ -121,6 +144,13 @@ internal fun classifyRecoverableWorkerRetry( } } +internal fun isExpiredAccessAuthFailure(line: String): Boolean = + line.contains("DENIED:expired", ignoreCase = true) || + line.contains("срок действия пароля истёк", ignoreCase = true) + +internal const val WRAP_HANDSHAKE_RETRY_MESSAGE = + "[WRAP] Отдельные каналы не ответили, выполняется повтор" + const val AMNEZIA_STYLE_RECOVERY = true private const val RECOVERABLE_NETWORK_GRACE_MS = 90_000L private const val HARD_NETWORK_GRACE_MS = 30_000L @@ -177,6 +207,8 @@ object TunnelManager { var isLoggingEnabled = true val running = MutableStateFlow(false) + val transition = MutableStateFlow(TunnelTransition.IDLE) + val activeTunnelProfile = MutableStateFlow(null) val logs = MutableStateFlow>(emptyList()) val unreadErrorCount = MutableStateFlow(0) val config = MutableStateFlow(null) @@ -192,16 +224,45 @@ object TunnelManager { unreadErrorCount.value = 0 } - fun clearConnectionIssue() { - connectionIssue.value = null + fun noteStartRequested() { + transition.value = TunnelTransition.STARTING } - private fun setConnectionIssue(title: String, action: String, isError: Boolean = true) { - connectionIssue.value = ConnectionIssue(title = title, action = action, isError = isError) + fun noteStopRequested() { + transition.value = TunnelTransition.STOPPING } - fun reportConnectionIssue(title: String, action: String, isError: Boolean = true) { - setConnectionIssue(title, action, isError) + fun clearTransition() { + transition.value = TunnelTransition.IDLE + } + + fun clearConnectionIssue(kind: ConnectionIssueKind? = null) { + if (kind == null || connectionIssue.value?.kind == kind) { + connectionIssue.value = null + } + } + + private fun setConnectionIssue( + title: String, + action: String, + isError: Boolean = true, + kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL, + ) { + connectionIssue.value = ConnectionIssue( + title = title, + action = action, + isError = isError, + kind = kind, + ) + } + + fun reportConnectionIssue( + title: String, + action: String, + isError: Boolean = true, + kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL, + ) { + setConnectionIssue(title, action, isError, kind) } fun isCaptchaInProgress(): Boolean = @@ -427,12 +488,23 @@ object TunnelManager { if (now - lastRecoveryAtMs < STABLE_RECOVERY_RETRY_MS) return null lastRecoveryAtMs = now + val action = stableNetworkRecoveryAction(recoveryAttempts) recoveryAttempts++ - setConnectionIssue( - "Восстанавливаю транспорт", - "Сеть долго не подаёт признаков жизни. Выполняется одна мягкая попытка без пересоздания VPN." - ) - return NetworkRecoveryAction.SoftRestart + when (action) { + NetworkRecoveryAction.SoftRestart -> setConnectionIssue( + "Восстанавливаю транспорт", + "Сеть долго не подаёт признаков жизни. Выполняется тихая попытка без пересоздания VPN." + ) + NetworkRecoveryAction.RecreateVpn -> setConnectionIssue( + "Пересоздаю VPN", + "Тихое восстановление не помогло. Системный VPN-интерфейс будет пересоздан один раз." + ) + NetworkRecoveryAction.StopVpn -> setConnectionIssue( + "VPN остановлен, чтобы вернуть интернет", + "Пересоздание VPN не восстановило связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета." + ) + } + return action } private fun buildDeviceInfoJson(context: Context): String { @@ -461,6 +533,7 @@ object TunnelManager { } private var observersInitialized = false + private var accessRefreshRequestedForProcess = false fun initObservers(context: Context) { if (observersInitialized) return @@ -494,6 +567,26 @@ object TunnelManager { updateLog("deploy_ok_$hash", message, 2, false) } + fun noteTrustedWifiEvent(key: String, message: String, warning: Boolean = false) { + val logKey = "trusted_wifi_$key" + val text = "[ДОВЕРЕННЫЙ WI-FI] $message" + if (warning) { + updateWarningLog(logKey, text, 2) + } else { + updateLog(logKey, text, 2, false) + } + } + + fun noteAccessLifecycleEvent(key: String, message: String, warning: Boolean = false) { + val logKey = "access_$key" + val text = "[ДОСТУП] $message" + if (warning) { + updateWarningLog(logKey, text, 20) + } else { + updateLog(logKey, text, 20, false) + } + } + private fun updateLog(key: String, message: String, priority: Int, isError: Boolean = false) { if (!isLoggingEnabled) return val severity = if (isError) LogSeverity.Error else LogSeverity.Info @@ -546,16 +639,25 @@ object TunnelManager { } } - fun start(context: Context, params: TunnelParams, isSwitching: Boolean = false) { + fun start( + context: Context, + params: TunnelParams, + isSwitching: Boolean = false, + preserveLogs: Boolean = false + ) { + if (!isSwitching) noteStartRequested() scope.launch { startStopMutex.lock() try { - if (running.value && !isSwitching) return@launch + if (running.value && !isSwitching) { + clearTransition() + return@launch + } val appContext = context.applicationContext // Защита от Memory Leak if (!isSwitching) { - clearLogs() + if (!preserveLogs) clearLogs() config.value = null stats.value = "Ожидание данных..." floodCount = 0 @@ -573,6 +675,7 @@ object TunnelManager { activeHashIndex = 0 currentParams = params lastContext = appContext + accessRefreshRequestedForProcess = false forceRegenerateUA = false currentCaptchaMode = params.captchaMode currentCaptchaSolveMethod = params.captchaSolveMethod @@ -581,6 +684,22 @@ object TunnelManager { wgHelper = WireGuardHelper(appContext) val targetHash = if (activeHashIndex == 0) params.vkHashes else params.secondaryVkHash + + val customCredentials = CustomVkClientCredentials( + enabled = params.customVkCredentialsEnabled, + clientId = params.customVkClientId, + clientSecret = params.customVkClientSecret + ) + customVkCredentialsError(customCredentials)?.let { error -> + updateLog("custom_vk_credentials_error", "Ошибка: пользовательские реквизиты VK не заполнены", 99, true) + setConnectionIssue( + "Не заполнены реквизиты VK", + "$error Откройте «Настройки → Клиент ID» или выключите пользовательский режим." + ) + running.value = false + currentParams = null + return@launch + } // Robust hash parsing: split by comma, newline, or whitespace val hashList = targetHash @@ -607,7 +726,10 @@ object TunnelManager { } val hashCount = hashList.size.coerceIn(1, 4) - val totalWorkers = params.workersPerHash.coerceIn(1, 128) + val totalWorkers = normalizeTunnelWorkerCount( + requested = params.workersPerHash, + profileMaxWorkers = params.profileMaxWorkers + ) val hashMode = if (activeHashIndex == 0) "Основной" else "Запасной" updateLog("config_info", "[$hashMode] Хешей=$hashCount, Потоков=$totalWorkers", 1) @@ -644,7 +766,7 @@ object TunnelManager { // stops flag.Parse and silently drops every argument after it. cmd.add("-vkcalls-preflight=${params.vkCallsPreflight}") - val androidId = android.provider.Settings.Secure.getString(context.contentResolver, android.provider.Settings.Secure.ANDROID_ID) ?: "unknown" + val androidId = SettingsStore(appContext).getOrCreateTunnelDeviceId() cmd.add("-device-id") cmd.add(androidId) cmd.add("-device-info") @@ -653,6 +775,15 @@ object TunnelManager { cmd.add("-password") cmd.add(params.connectionPassword) + if ( + params.managedConfigFirstStart && + params.profileMaxWorkers == TUNNEL_WORKERS_PER_GROUP && + totalWorkers == TUNNEL_WORKERS_PER_GROUP + ) { + cmd.add("-config-first-start=true") + cmd.add("-hash-fallback=true") + } + cmd.add("-captcha-mode") cmd.add(params.captchaMode) @@ -662,12 +793,20 @@ object TunnelManager { val env = pb.environment() env["LD_LIBRARY_PATH"] = context.applicationInfo.nativeLibraryDir + if (params.customVkCredentialsEnabled) { + env["WDTT_CUSTOM_VK_CLIENT_ID"] = params.customVkClientId + env["WDTT_CUSTOM_VK_CLIENT_SECRET"] = params.customVkClientSecret + } else { + env.remove("WDTT_CUSTOM_VK_CLIENT_ID") + env.remove("WDTT_CUSTOM_VK_CLIENT_SECRET") + } process = pb.start() processStartedAtMs = System.currentTimeMillis() wrapAuthTimeoutCount = 0 resetStatsLivenessState() running.value = true + clearTransition() startLogReader() startWatchdog(appContext, params) @@ -678,7 +817,9 @@ object TunnelManager { e.printStackTrace() running.value = false currentParams = null + clearTransition() } finally { + if (!isSwitching) clearTransition() startStopMutex.unlock() } } @@ -707,6 +848,26 @@ object TunnelManager { val msgPrefixReplaced = line.replace(Regex("^\\d{4}/\\d{2}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?\\s"), "") val lineTrim = msgPrefixReplaced.trim() + if (lineTrim.contains("[МОЩНОСТЬ] Лимит временно занят", true)) { + updateLog( + "worker_policy_wait", + "[МОЩНОСТЬ] Свободные потоки этого профиля временно заняты; повторяем подключение автоматически", + 20, + false + ) + return@forEachLine + } + + if (lineTrim.contains("[МОЩНОСТЬ] Сервер остановил лишний поток", true)) { + updateLog( + "worker_policy_limit", + "[МОЩНОСТЬ] Лишние потоки остановлены согласно ограничению этого доступа; подключение продолжает работать", + 20, + false + ) + return@forEachLine + } + val isCaptchaV2FallbackStatus = lineTrim.contains("[КАПЧА] v2", true) && ( lineTrim.contains("fallback продолжит", true) || @@ -719,7 +880,8 @@ object TunnelManager { ( lineTrim.contains("preflight не сработал", true) || lineTrim.contains("временно ограничил", true) || - lineTrim.contains("временно пропущен", true) + lineTrim.contains("временно пропущен", true) || + lineTrim.contains("пробуем совместимый резерв", true) ) val isError = !isCaptchaV2FallbackStatus && !isCaptchaProtocolResult && !isVkCallsFallback && ( lineTrim.contains("Ошибка", true) || @@ -739,7 +901,7 @@ object TunnelManager { wrapAuthTimeoutCount = 0 updateLog( "wrap_timeout_recovered", - "[WRAP] Один поток не прошёл handshake, активных=${activeWorkers.value}; повторяем", + WRAP_HANDSHAKE_RETRY_MESSAGE, 20, false ) @@ -747,31 +909,68 @@ object TunnelManager { wrapAuthTimeoutCount++ updateWarningLog( "wrap_timeout_wait", - "[WRAP] Handshake не подтвердился, проверяем пароль/сеть ($wrapAuthTimeoutCount)", + WRAP_HANDSHAKE_RETRY_MESSAGE, 50 ) } return@forEachLine } + val accessExpired = isExpiredAccessAuthFailure(lineTrim) val reason = when { lineTrim.contains("неверный пароль") -> "Неверный пароль подключения" - lineTrim.contains("истёк") -> "Срок действия пароля истёк" + accessExpired -> "Срок действия пароля истёк" lineTrim.contains("другому устройству") -> "Пароль привязан к другому устройству" else -> "Ошибка авторизации" } val action = when { lineTrim.contains("неверный пароль") -> "Проверьте пароль в «Секретах» или вставьте актуальную wdtt:// ссылку." - lineTrim.contains("истёк") -> - "Создайте новый пароль у администратора или продлите текущий в Telegram-боте." + accessExpired -> + "Откройте профиль, чтобы проверить срок и доступные действия." lineTrim.contains("другому устройству") -> - "Этот пароль уже закреплён за другим устройством. Отвяжите устройство в Telegram-боте или создайте новый пароль." + ( + "Этот пароль уже закреплён за другим устройством. " + + "Запросите отвязку или новый профиль у поставщика." + ) else -> "Проверьте пароль, VK-хеш и состояние сервера, затем попробуйте подключиться снова." } - setConnectionIssue(reason, action) - handleCriticalError("\uD83D\uDD12 $reason. Воркеры остановлены.") + setConnectionIssue( + reason, + action, + kind = if (accessExpired) { + ConnectionIssueKind.ACCESS + } else { + ConnectionIssueKind.GENERAL + }, + ) + if (accessExpired) { + updateLog( + "access_expired", + "[ДОСТУП] Срок действия профиля закончился. Откройте вкладку «Туннель», чтобы проверить доступные действия.", + 20, + true, + ) + val accessContext = lastContext + val accessProfile = currentParams?.profileIndex + if (accessContext != null && accessProfile != null) { + scope.launch { + AccessLifecycleCoordinator.noteServerDenied( + accessContext, + accessProfile, + ) + } + } + } + handleCriticalError( + "\uD83D\uDD12 $reason. Воркеры остановлены.", + if (accessExpired) { + TunnelStopReason.AccessExpired + } else { + TunnelStopReason.CriticalError + }, + ) return@forEachLine } @@ -802,7 +1001,7 @@ object TunnelManager { wrapAuthTimeoutCount = 0 updateLog( "wrap_timeout_recovered", - "[WRAP] Один поток не прошёл handshake, активных=${activeWorkers.value}; повторяем", + WRAP_HANDSHAKE_RETRY_MESSAGE, 20, false ) @@ -810,7 +1009,7 @@ object TunnelManager { wrapAuthTimeoutCount++ updateWarningLog( "wrap_timeout_wait", - "[WRAP] Handshake не подтвердился, проверяем пароль/сеть ($wrapAuthTimeoutCount)", + WRAP_HANDSHAKE_RETRY_MESSAGE, 50 ) } @@ -827,7 +1026,7 @@ object TunnelManager { val redirectUri = parts[2] val sessionToken = parts[3] scope.launch { - handleCaptchaSolve(requestId, requestMode, redirectUri, sessionToken) + handleCaptchaSolve(observedProcess, requestId, requestMode, redirectUri, sessionToken) } } 3 -> { @@ -835,18 +1034,18 @@ object TunnelManager { val redirectUri = parts[1] val sessionToken = parts[2] scope.launch { - handleCaptchaSolve("", requestMode, redirectUri, sessionToken) + handleCaptchaSolve(observedProcess, "", requestMode, redirectUri, sessionToken) } } 2 -> { val redirectUri = parts[0] val sessionToken = parts[1] scope.launch { - handleCaptchaSolve("", "selected", redirectUri, sessionToken) + handleCaptchaSolve(observedProcess, "", "selected", redirectUri, sessionToken) } } else -> { - writeCaptchaResult("", "error:invalid CAPTCHA_SOLVE format") + writeCaptchaResult(observedProcess, "", "error:invalid CAPTCHA_SOLVE format") } } return@forEachLine @@ -912,6 +1111,19 @@ object TunnelManager { } if (active > 0) { + if (!accessRefreshRequestedForProcess) { + accessRefreshRequestedForProcess = true + val accessContext = lastContext + val accessProfile = currentParams?.profileIndex + if (accessContext != null && accessProfile != null) { + scope.launch { + AccessLifecycleCoordinator.refreshAfterSuccessfulConnect( + accessContext, + accessProfile, + ) + } + } + } lastActiveAtMs = now wrapAuthTimeoutCount = 0 @@ -944,8 +1156,21 @@ object TunnelManager { val workerRetry = classifyRecoverableWorkerRetry(lineTrim, activeWorkers.value) when { - workerRetry != null -> + workerRetry != null -> { + if (activeWorkers.value <= 0) { + when (workerRetry.first) { + "worker_turn_allocate_retry" -> noteRecoverableNetworkIssue( + "TURN/UDP не отвечает", + "VK API выдал TURN-данные, но TURN Allocate не получил ответ. WDTT Plus попробует другие TURN-пути и повторы; если ошибка повторяется, оператор может ограничивать UDP/TURN." + ) + "worker_dtls_retry" -> noteRecoverableNetworkIssue( + "VPS не отвечает на DTLS", + "TURN Allocate прошёл, но рукопожатие DTLS до сервера не завершилось. Проверьте порт сервера, доступность VPS и пароль подключения." + ) + } + } updateWarningLog(workerRetry.first, workerRetry.second, 20) + } lineTrim.contains("[ВОРКЕР #", true) && lineTrim.contains("Невосстановимая TURN/STUN ошибка", true) -> updateWarningLog( @@ -953,22 +1178,100 @@ object TunnelManager { "[TURN] Отдельные каналы завершили попытки подключения; остальные продолжают работу", 50 ) + lineTrim.contains("[DNS]", true) -> { + val text = lineTrim.substringAfter("[DNS]").trim() + when { + text.contains("Прямой DNS клиента недоступен", true) && + text.contains("системный DNS", true) -> { + noteRecoverableNetworkIssue( + "Прямой DNS клиента недоступен", + "Оператор не ответил на прямые DNS-запросы клиента. WDTT Plus использует системный DNS устройства для этого запуска." + ) + updateWarningLog( + "dns_system_fallback", + "[DNS] Прямой DNS клиента недоступен, используем системный DNS устройства", + 20 + ) + } + text.contains("DNS до VK недоступен", true) -> { + noteRecoverableNetworkIssue( + "DNS до VK недоступен", + "Прямой DNS клиента и системный DNS устройства не ответили. Проверьте Private DNS, сеть оператора или попробуйте другую сеть." + ) + updateWarningLog("dns_vk_unavailable", "[DNS] DNS до VK недоступен", 99) + } + else -> updateLog("dns_status", "[DNS] $text", 2, false) + } + } lineTrim.contains("[VKCalls]", true) -> { when { lineTrim.contains("TURN credentials получены", true) -> - updateLog("vkcalls_ok", "[VKCalls] Анонимные TURN-данные получены ✓", 2, false) + updateLog("vkcalls_ok", "[VKCalls] Основной бескапчевый провайдер сработал ✓", 2, false) lineTrim.contains("preflight не сработал", true) || lineTrim.contains("временно ограничил", true) || lineTrim.contains("временно пропущен", true) -> - updateLog("vkcalls_fallback", "[VKCalls] Анонимный вход временно недоступен — используется капча", 20, false) + updateLog("vkcalls_fallback", "[VKCalls] Основной провайдер временно недоступен — пробуем legacy-резерв", 20, false) + lineTrim.contains("пробуем совместимый резерв", true) -> + updateLog("vkcalls_api_fallback", "[VKCalls] Основной API-домен не ответил — пробуем совместимый резерв", 20, false) lineTrim.endsWith("[VKCalls] preflight", true) -> - updateLog("vkcalls_start", "[VKCalls] Пробуем анонимный вход...", 2, false) + updateLog("vkcalls_start", "[VKCalls] Пробуем основной бескапчевый провайдер...", 2, false) else -> { if (isError) updateWarningLog("vkcalls_status", lineTrim, 20) else updateLog("vkcalls_status", lineTrim, 20, false) } } } + lineTrim.contains("[VK Provider]", true) -> { + when { + lineTrim.contains("TURN-данные сохранены", true) -> { + val lifetime = lineTrim.substringAfter("сохранены на", "").trim() + updateLog( + "vk_provider_cache", + "[ВК] TURN-данные сохранены${lifetime.takeIf(String::isNotBlank)?.let { " на $it" }.orEmpty()}", + 2, + false + ) + } + lineTrim.contains("legacy-custom", true) && lineTrim.contains("успешно", true) -> + updateLog("vk_provider_custom", "[ВК] Собственный legacy Client ID сработал ✓", 5, false) + lineTrim.contains("legacy-custom", true) && lineTrim.contains("пробуем", true) -> + updateLog("vk_provider_custom", "[ВК] Пробуем собственный legacy Client ID...", 5, false) + lineTrim.contains("legacy-custom", true) && lineTrim.contains("CAPTCHA_WAIT_REQUIRED", true) -> + updateLog("vk_provider_custom_wait", "[КАПЧА] Собственный legacy-провайдер ждёт следующую безопасную попытку", 20, false) + lineTrim.contains("legacy-custom", true) && lineTrim.contains("не сработал", true) -> + updateLog("vk_provider_custom_fallback", "[ВК] Собственный legacy Client ID не сработал — пробуем встроенный резерв", 20, false) + lineTrim.contains("legacy-built-in", true) && lineTrim.contains("успешно", true) -> + updateLog("vk_provider_builtin", "[ВК] Встроенный legacy Client ID сработал ✓", 5, false) + lineTrim.contains("legacy-built-in", true) && lineTrim.contains("пробуем", true) -> + updateLog("vk_provider_builtin", "[ВК] Пробуем встроенный legacy Client ID...", 5, false) + lineTrim.contains("legacy-built-in", true) && lineTrim.contains("CAPTCHA_WAIT_REQUIRED", true) -> + updateLog("vk_provider_builtin_wait", "[КАПЧА] Встроенный legacy-провайдер ждёт следующую безопасную попытку", 20, false) + lineTrim.contains("legacy-built-in", true) && lineTrim.contains("не сработал", true) -> + updateLog("vk_provider_builtin_fallback", "[ВК] Этот встроенный Client ID не сработал — пробуем следующий", 20, false) + lineTrim.contains("modern-vkcalls", true) && lineTrim.contains("успешно", true) -> + updateLog("vk_provider_modern", "[ВК] Используется современный VKCalls ✓", 2, false) + else -> updateLog("vk_provider_status", lineTrim, 20, false) + } + } + lineTrim.contains("[VK Auth]", true) -> { + when { + lineTrim.contains("Using cached credentials", true) -> + updateLog("vk_credentials_cache", "[ВК] Используются ранее полученные TURN-данные", 2, false) + lineTrim.contains("Throttling", true) -> + updateLog("vk_credentials_throttle", "[ВК] Безопасная пауза между запросами к VK", 20, false) + lineTrim.contains("Credentials cache invalidated", true) -> + updateLog("vk_credentials_refresh", "[ВК] TURN-данные устарели — получаем свежие", 5, false) + lineTrim.contains("getCallPreview failed", true) -> + updateLog("vk_preview_optional", "[ВК] Предпросмотр legacy-звонка недоступен, продолжаем получение TURN-данных", 20, false) + lineTrim.contains("Rate limit detected", true) -> + updateLog("vk_legacy_rate_limit", "[ВК] Этот legacy Client ID временно ограничен — пробуем следующий", 20, false) + lineTrim.contains("Все legacy-провайдеры", true) -> + updateLog("vk_legacy_retry", "[ВК] Legacy-провайдеры временно не ответили — выполняется безопасный повтор", 20, false) + else -> { + if (isError) updateWarningLog("vk_auth_status", lineTrim, 20) + } + } + } lineTrim.contains("[КАПЧА] AUTO:") -> { var text = lineTrim.substringAfter("[КАПЧА] AUTO:").trim() text = text.replace(Regex("\\s*\\([^)]+\\)\\s*"), " ").trim() @@ -1109,15 +1412,26 @@ object TunnelManager { val errorKey = when { isHardNetworkFailure(lineTrim) -> "err_hard_network" isLocalDnsRefused(lineTrim) -> "err_local_dns_refused" - lineTrim.contains("lookup login.vk.ru", true) -> "err_vk_dns" + lineTrim.contains("lookup ", true) && + ( + lineTrim.contains("login.vk.ru", true) || + lineTrim.contains("api.vk.ru", true) || + lineTrim.contains("api.vk.me", true) || + lineTrim.contains("calls.okcdn.ru", true) + ) -> "err_vk_dns" + lineTrim.contains("VK HTTPS", true) -> "err_vk_https" lineTrim.contains("connection refused") -> "err_conn_refused" lineTrim.contains("timeout") -> "err_timeout" lineTrim.contains("кредов") -> "err_creds" lineTrim.contains("DTLS") -> "err_dtls" else -> "general_error_" + lineTrim.take(15).hashCode() } + val failedVkHost = listOf("login.vk.ru", "api.vk.ru", "api.vk.me", "calls.okcdn.ru") + .firstOrNull { lineTrim.contains(it, true) } val errorMessage = if (errorKey == "err_vk_dns") { - "[СЕТЬ] DNS до VK недоступен: login.vk.ru" + "[СЕТЬ] DNS до VK недоступен: ${failedVkHost ?: "VK/OK"}" + } else if (errorKey == "err_vk_https") { + "[VK] HTTPS до VK/OK не отвечает" } else { lineTrim } @@ -1138,6 +1452,11 @@ object TunnelManager { "DNS до VK недоступен", "WDTT Plus попробует восстановить транспорт автоматически. Если не восстановится, проверьте интернет без VPN и DNS на устройстве." ) + } else if (errorKey == "err_vk_https") { + noteRecoverableNetworkIssue( + "HTTPS до VK/OK не отвечает", + "DNS сработал, но HTTPS-запрос к VK/OK не завершился. WDTT Plus попробует восстановить транспорт; если повторяется, проверьте ограничения сети оператора." + ) } else if (errorKey == "err_timeout" || errorKey == "err_conn_refused") { noteRecoverableNetworkIssue( "Транспорт не отвечает", @@ -1148,6 +1467,7 @@ object TunnelManager { "err_hard_network", "err_local_dns_refused", "err_vk_dns", + "err_vk_https", "err_conn_refused", "err_timeout", "err_creds" @@ -1205,12 +1525,15 @@ object TunnelManager { } } - private fun handleCriticalError(message: String) { + private fun handleCriticalError( + message: String, + stopReason: TunnelStopReason = TunnelStopReason.CriticalError, + ) { if (connectionIssue.value == null) { setConnectionIssue("Подключение остановлено", "$message Проверьте настройки и попробуйте снова.") } updateLog("circuit_breaker", "[СТОП] $message", -1, true) - stop(TunnelStopReason.CriticalError) + stop(stopReason) } private fun handleHashError() { @@ -1332,14 +1655,78 @@ object TunnelManager { updateLog("network_restart", reason, 50, false) activeWorkers.value = 0 resetStatsLivenessState() - killProcess() + val restartDelayMs = transportRecoveryPolicy( + params.managedConfigFirstStart + ).processRestartDelayMs scope.launch { - delay(2500) - start(context, params, isSwitching = true) + killProcess() + delay(restartDelayMs) + if (currentParams === params && running.value) { + start(context, params, isSwitching = true) + } } return true } + internal fun applyUpdatedProfileConfiguration( + context: Context, + params: TunnelParams, + restartTransport: Boolean, + ): TunnelProfileRuntimeApplyResult { + val previous = currentParams ?: return TunnelProfileRuntimeApplyResult.INACTIVE + if (!running.value || previous.profileIndex != params.profileIndex) { + return TunnelProfileRuntimeApplyResult.INACTIVE + } + if (!tunnelProfileRuntimeConfigurationChanged(previous, params)) { + return TunnelProfileRuntimeApplyResult.UNCHANGED + } + + val appContext = context.applicationContext + currentParams = params + lastContext = appContext + activeHashIndex = 0 + currentHashErrorCount = 0 + wrapAuthTimeoutCount = 0 + currentCaptchaMode = params.captchaMode + currentCaptchaSolveMethod = params.captchaSolveMethod + accessRefreshRequestedForProcess = false + resetNetworkRecoveryState() + resetStatsLivenessState() + clearConnectionIssue(ConnectionIssueKind.GENERAL) + activeWorkers.value = 0 + + if (!restartTransport) { + updateLog( + "profile_runtime_update_pending", + "[ПРОФИЛЬ] Новые параметры сохранены и будут применены при возобновлении VPN.", + 20, + false, + ) + return TunnelProfileRuntimeApplyResult.STORED_FOR_RESUME + } + + updateLog( + "profile_runtime_update", + "[ПРОФИЛЬ] Параметры активного подключения обновлены. Мягко переподключаю транспорт.", + 20, + false, + ) + scope.launch { + startStopMutex.lock() + try { + if (currentParams !== params || !running.value) return@launch + killProcess() + delay(250L) + } finally { + startStopMutex.unlock() + } + if (currentParams === params && running.value) { + start(appContext, params, isSwitching = true, preserveLogs = true) + } + } + return TunnelProfileRuntimeApplyResult.RESTARTED + } + fun noteUnderlyingNetworkChanged( reason: String, graceMs: Long = RECOVERABLE_NETWORK_GRACE_MS, @@ -1503,8 +1890,15 @@ object TunnelManager { val proc = process process = null if (proc != null) { - try { proc.destroy() } catch (_: Exception) {} - try { proc.waitFor(500, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {} + try { + proc.outputStream.write("STOP\n".toByteArray(Charsets.UTF_8)) + proc.outputStream.flush() + } catch (_: Exception) {} + try { proc.waitFor(1500, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {} + if (proc.isAlive) { + try { proc.destroy() } catch (_: Exception) {} + try { proc.waitFor(750, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {} + } if (proc.isAlive) { try { proc.destroyForcibly() } catch (_: Exception) {} try { proc.waitFor(1000, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {} @@ -1525,6 +1919,7 @@ object TunnelManager { } fun onWireGuardStoppedExternally() { + noteStopRequested() scope.launch { startStopMutex.lock() try { @@ -1542,12 +1937,14 @@ object TunnelManager { currentParams = null ManlCaptchaWebViewManager.cancelCaptcha() } finally { + clearTransition() startStopMutex.unlock() } } } fun stop(reason: TunnelStopReason = TunnelStopReason.User) { + noteStopRequested() scope.launch { startStopMutex.lock() try { @@ -1563,28 +1960,45 @@ object TunnelManager { resetNetworkRecoveryState() ManlCaptchaWebViewManager.cancelCaptcha() } finally { + if (reason == TunnelStopReason.User) { + startCooldown(1500L) + } + clearTransition() startStopMutex.unlock() } } } - suspend fun stopAndWait(reason: TunnelStopReason = TunnelStopReason.User) { + suspend fun stopAndWait( + reason: TunnelStopReason = TunnelStopReason.User, + context: Context? = null, + forceVpnRelease: Boolean = false, + ) { + noteStopRequested() startStopMutex.lock() try { - if (!running.value && currentParams == null) return + val hadManagedSession = running.value || currentParams != null || process != null + if (!hadManagedSession && !forceVpnRelease) return + val stopHelper = wgHelper ?: context?.applicationContext?.let(::WireGuardHelper) withContext(Dispatchers.Main) { - wgHelper?.stopTunnel() + stopHelper?.stopTunnel() } withContext(Dispatchers.IO) { killProcess() running.value = false - markLogSessionStopped(reason) + if (hadManagedSession) { + markLogSessionStopped(reason) + } resetStatsLivenessState() currentParams = null resetNetworkRecoveryState() ManlCaptchaWebViewManager.cancelCaptcha() } } finally { + if (reason == TunnelStopReason.User) { + startCooldown(1500L) + } + clearTransition() startStopMutex.unlock() } } @@ -1597,9 +2011,15 @@ object TunnelManager { } } - private suspend fun handleCaptchaSolve(requestId: String, requestMode: String, redirectUri: String, sessionToken: String) { + private suspend fun handleCaptchaSolve( + expectedProcess: Process, + requestId: String, + requestMode: String, + redirectUri: String, + sessionToken: String + ) { val ctx = lastContext ?: run { - writeCaptchaResult(requestId, "error:context is null") + writeCaptchaResult(expectedProcess, requestId, "error:context is null") return } val mode = requestMode.lowercase() @@ -1622,7 +2042,7 @@ object TunnelManager { } } updateLog("captcha_wv_step_4", "[КАПЧА WBV] Капча решена ✓", 5, false) - writeCaptchaResult(requestId, token) + writeCaptchaResult(expectedProcess, requestId, token) } catch (e: IllegalStateException) { val errorMsg = e.message ?: "WV state error" val autoFallback = mode == "auto" && ( @@ -1636,23 +2056,23 @@ object TunnelManager { } else { updateWarningLog("captcha_wv_err", "[КАПЧА WBV] $errorMsg", 5) } - writeCaptchaResult(requestId, "error:$errorMsg") + writeCaptchaResult(expectedProcess, requestId, "error:$errorMsg") } catch (e: kotlinx.coroutines.TimeoutCancellationException) { if (mode == "auto") { updateLog("captcha_wv_timeout", "[КАПЧА WBV] Авто WebView не успел, идём дальше", 5, false) } else { updateWarningLog("captcha_wv_err", "[КАПЧА WBV] WebView не ответил вовремя", 5) } - writeCaptchaResult(requestId, "error:timeout") + writeCaptchaResult(expectedProcess, requestId, "error:timeout") } catch (e: kotlin.coroutines.cancellation.CancellationException) { updateWarningLog("captcha_wv_err", "[КАПЧА WBV] Проверка отменена", 5) - writeCaptchaResult(requestId, "error:cancelled") + writeCaptchaResult(expectedProcess, requestId, "error:cancelled") } catch (e: Exception) { val errorMsg = e.message ?: "${e::class.simpleName}" if (errorMsg != "tunnel stopped") { updateWarningLog("captcha_wv_err", "[КАПЧА WBV] Текущая попытка не выполнена — $errorMsg", 5) } - writeCaptchaResult(requestId, "error:$errorMsg") + writeCaptchaResult(expectedProcess, requestId, "error:$errorMsg") } finally { updateLog("captcha_wv_step_6", "[КАПЧА WBV] WebView уничтожен", 5, false) endCaptchaSolve(captchaRequestId) @@ -1701,16 +2121,23 @@ object TunnelManager { return ManlCaptchaWebViewManager.solveCaptchaAsync(ctx, redirectUri, sessionToken) } - private fun writeCaptchaResult(requestId: String, result: String) { - val proc = process - if (proc == null || !proc.isAlive) return + private fun writeCaptchaResult(expectedProcess: Process, requestId: String, result: String) { + if (process !== expectedProcess || !expectedProcess.isAlive) return try { val payload = if (requestId.isBlank()) result else "$requestId|$result" val line = "CAPTCHA_RESULT|$payload\n" - proc.outputStream.write(line.toByteArray(Charsets.UTF_8)) - proc.outputStream.flush() + expectedProcess.outputStream.write(line.toByteArray(Charsets.UTF_8)) + expectedProcess.outputStream.flush() } catch (e: Exception) { - updateLog("captcha_write_err", "[КАПЧА] Ошибка записи: ${e.message}", 200, true) + // Остановка туннеля может закрыть stdin между проверкой isAlive и записью. + // Это штатная гонка завершения, а не ошибка подключения пользователя. + if (process === expectedProcess && expectedProcess.isAlive) { + updateWarningLog( + "captcha_write_err", + "[КАПЧА] Нативный клиент не принял результат: ${e.message ?: e::class.simpleName}", + 5 + ) + } } } @@ -1749,5 +2176,18 @@ data class TunnelParams( val captchaMode: String = "auto", val captchaSolveMethod: String = "auto", val fingerprint: String = "firefox", - val clientIds: String = "6287487,8202606" + val clientIds: String = DEFAULT_VK_CLIENT_IDS, + val customVkCredentialsEnabled: Boolean = false, + val customVkClientId: String = "", + val customVkClientSecret: String = "", + val profileMaxWorkers: Int = 0, + val managedConfigFirstStart: Boolean = false, + val profileIndex: Int = 0, ) + +internal enum class TunnelProfileRuntimeApplyResult { + INACTIVE, + UNCHANGED, + STORED_FOR_RESUME, + RESTARTED, +} diff --git a/app/src/main/java/com/wdtt/plus/TunnelProfileRuntimeUpdate.kt b/app/src/main/java/com/wdtt/plus/TunnelProfileRuntimeUpdate.kt new file mode 100644 index 0000000..38b0b33 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/TunnelProfileRuntimeUpdate.kt @@ -0,0 +1,51 @@ +package com.wdtt.plus + +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.asSharedFlow + +internal object TunnelProfileRuntimeUpdateBus { + private val mutableRequests = MutableSharedFlow( + extraBufferCapacity = 3, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + val requests = mutableRequests.asSharedFlow() + + fun request(profileIndex: Int) { + if (profileIndex in 0..2) { + mutableRequests.tryEmit(profileIndex) + } + } +} + +internal fun shouldRequestTunnelProfileRuntimeUpdate( + updatedProfile: Int, + activeTunnelProfile: Int?, + tunnelRunning: Boolean, + trustedWifiWaiting: Boolean, +): Boolean = + updatedProfile in 0..2 && + activeTunnelProfile == updatedProfile && + (tunnelRunning || trustedWifiWaiting) + +internal fun tunnelProfileRuntimeConfigurationChanged( + current: TunnelParams, + updated: TunnelParams, +): Boolean = + current.profileIndex == updated.profileIndex && + current != updated + +internal fun requestTunnelProfileRuntimeUpdate(profileIndex: Int) { + if (profileIndex !in 0..2) return + if ( + !shouldRequestTunnelProfileRuntimeUpdate( + updatedProfile = profileIndex, + activeTunnelProfile = TunnelManager.activeTunnelProfile.value, + tunnelRunning = TunnelManager.running.value, + trustedWifiWaiting = TrustedWifiManager.state.value.waiting, + ) + ) { + return + } + TunnelProfileRuntimeUpdateBus.request(profileIndex) +} diff --git a/app/src/main/java/com/wdtt/plus/TunnelService.kt b/app/src/main/java/com/wdtt/plus/TunnelService.kt index 0ceb5f0..61cd13f 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelService.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelService.kt @@ -23,14 +23,18 @@ import androidx.core.app.NotificationCompat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.first import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext +import java.util.concurrent.ConcurrentHashMap private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4" private const val TUNNEL_ALERT_CHANNEL_ID = "wdtt_tunnel_alert_v1" @@ -39,33 +43,42 @@ private const val TUNNEL_ALERT_NOTIFICATION_ID = 2 private const val NETWORK_CHANGE_SETTLE_MS = 90_000L private const val NETWORK_RETURN_SETTLE_MS = 45_000L private const val NETWORK_LOSS_GRACE_MS = 2 * 60_000L -private const val STABLE_NETWORK_RECONNECT_DELAY_MS = 15_000L -private const val STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS = 2 * 60_000L private const val WAKE_RESCUE_GRACE_MS = 60_000L private const val WAKE_RESCUE_FAIL_OPEN_MS = 2 * 60_000L +private const val ACTIVE_PROFILE_REFRESH_INTERVAL_MS = 2 * 60_000L private const val INITIAL_VPN_START_GRACE_MS = 90_000L private const val TRUSTED_WIFI_ENTER_DELAY_MS = 2_000L private const val TRUSTED_WIFI_EXIT_DELAY_MS = 5_000L -private const val TRUSTED_WIFI_FAST_RESUME_RETRY_COUNT = 12 -private const val TRUSTED_WIFI_SLOW_RESUME_RETRY_MS = 30_000L private const val TRUSTED_WIFI_RESUME_START_TIMEOUT_MS = 30_000L +private const val TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS = 75_000L class TunnelService : Service() { + private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val startRequestGate = TunnelStartRequestGate() + private var pendingStartJob: Job? = null + private var profileRuntimeUpdateJob: Job? = null + private var activeProfileRefreshJob: Job? = null private var wakeLock: PowerManager.WakeLock? = null private var wifiLock: WifiManager.WifiLock? = null + private var trustedWifiTransitionWakeLock: PowerManager.WakeLock? = null private var updateJob: Job? = null private var profileNameJob: Job? = null private var networkChangeJob: Job? = null private var lastNotificationTitle: String? = null private var lastNotificationText: String? = null private var notificationProfileTitle: String = "WDTT Plus" + private var connectionProfileIndex: Int? = null + private var profileStateJob: Job? = null private var requestedStopReason: TunnelStopReason? = null + private var stopSequenceJob: Job? = null + private var intentionalStopCompleted = false // Network Monitoring private var connectivityManager: ConnectivityManager? = null private var networkCallback: ConnectivityManager.NetworkCallback? = null private var lastNetworkChangeTime = 0L - private val activeNetworks = mutableSetOf() + private val activeNetworks = ConcurrentHashMap.newKeySet() + private val trustedWifiValidatedNetworks = TrustedWifiValidatedNetworkTracker() private var isTunnelPaused = false private var lastValidatedNetwork: Network? = null private var lastStableNetworkReconnectAt = 0L @@ -79,11 +92,15 @@ class TunnelService : Service() { private val trustedWifiEvaluationScheduleLock = Any() private var trustedWifiPendingEvaluationDelayMs: Long? = null private var trustedWifiResumeRetryJob: Job? = null + private val trustedWifiResumeRetryLock = Any() private var trustedWifiResumeRetryCount = 0 + @Volatile private var trustedWifiResumeInProgress = false private var trustedWifiResumeStartedAt = 0L private val trustedWifiTransitionMutex = Mutex() + @Volatile private var trustedWifiWaiting = false + @Volatile private var trustedWifiWaitingSsid = "" private var lastStartParams: TunnelParams? = null @@ -96,6 +113,9 @@ class TunnelService : Service() { setupTrustedWifiMonitoring() registerScreenStateReceiver() registerTrustedWifiStateReceiver() + serviceScope.launch { + TunnelProfileRuntimeUpdateBus.requests.collect(::applyUpdatedTunnelProfile) + } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { @@ -113,7 +133,7 @@ class TunnelService : Service() { peer = intent.getStringExtra("peer") ?: "", vkHashes = intent.getStringExtra("vk_hashes") ?: "", secondaryVkHash = intent.getStringExtra("secondary_vk_hash") ?: "", - workersPerHash = intent.getIntExtra("workers_per_hash", 16), + workersPerHash = intent.getIntExtra("workers_per_hash", 18), port = intent.getIntExtra("port", 9000), sni = intent.getStringExtra("sni") ?: "", connectionPassword = intent.getStringExtra("connection_password") ?: "", @@ -122,12 +142,16 @@ class TunnelService : Service() { captchaMode = sanitizeCaptchaMode(intent.getStringExtra("captcha_mode")), captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto", fingerprint = intent.getStringExtra("fingerprint") ?: "firefox", - clientIds = intent.getStringExtra("client_ids") ?: "6287487,8202606" + clientIds = intent.getStringExtra("client_ids") ?: DEFAULT_VK_CLIENT_IDS, + customVkCredentialsEnabled = intent.getBooleanExtra("custom_vk_credentials_enabled", false), + customVkClientId = intent.getStringExtra("custom_vk_client_id") ?: "", + customVkClientSecret = intent.getStringExtra("custom_vk_client_secret") ?: "", + profileMaxWorkers = intent.getIntExtra("profile_max_workers", 0), + managedConfigFirstStart = + intent.getBooleanExtra(MANAGED_CONFIG_FIRST_START_EXTRA, false), + profileIndex = intent.getIntExtra(TUNNEL_PROFILE_INDEX_EXTRA, 0).coerceIn(0, 2), ) - lastStartParams = params - TunnelManager.scope.launch(Dispatchers.Main) { - startOrWaitForTrustedWifi(params) - } + requestTunnelStart(params) } "STOP" -> stopTunnel(TunnelStopReason.User) "DEPLOY_START" -> { @@ -161,6 +185,9 @@ class TunnelService : Service() { startPersistentForeground(createNotification("Проверка доверенной Wi-Fi сети...")) startNotificationProfileWatcher() startStatsUpdater() + acquireTrustedWifiTransitionWakeLock() + releaseWakeLock() + releaseWifiLock() } scheduleTrustedWifiEvaluation(delayMs = 0L) } @@ -171,44 +198,165 @@ class TunnelService : Service() { private fun restoreTunnel() { val notification = createNotification("Восстановление соединения...") startPersistentForeground(notification) - + val appContext = applicationContext - TunnelManager.scope.launch { + val generation = startRequestGate.next() + pendingStartJob?.cancel() + pendingStartJob = serviceScope.launch { try { val store = SettingsStore(appContext) - val params = buildTunnelParamsFromSettings(appContext) + val savedTunnelProfile = store.activeTunnelProfile.first() + val params = buildTunnelParamsFromSettings(appContext, savedTunnelProfile) + if (!startRequestGate.isCurrent(generation)) return@launch if (params != null) { - launch(Dispatchers.Main) { - lastStartParams = params - val restoreWaiting = store.trustedWifiEnabled.first() && store.trustedWifiWaiting.first() - if (restoreWaiting) { - trustedWifiWaiting = true - trustedWifiWaitingSsid = store.trustedWifiWaitingSsid.first() - TrustedWifiManager.setWaiting(trustedWifiWaitingSsid) - startNotificationProfileWatcher() - startStatsUpdater() - scheduleTrustedWifiEvaluation(delayMs = 0L) - } else { - startOrWaitForTrustedWifi(params) - } + val access = AccessLifecycleCoordinator.prepareStart( + appContext, + params.profileIndex, + ) + if (!startRequestGate.isCurrent(generation)) return@launch + if (access is AccessStartDecision.Denied) { + reportAccessDenied(access.status) + stopTunnel(TunnelStopReason.AccessExpired) + return@launch + } + val refreshedParams = buildTunnelParamsFromSettings( + appContext, + params.profileIndex, + ) + if (refreshedParams == null) { + stopTunnel(TunnelStopReason.RestoreFailed) + return@launch + } + rememberConnectionProfile( + refreshedParams.profileIndex, + persist = savedTunnelProfile == null + ) + lastStartParams = refreshedParams + val restoreWaiting = store.trustedWifiEnabled.first() && + store.trustedWifiWaiting.first() + if (!startRequestGate.isCurrent(generation)) return@launch + if (restoreWaiting) { + trustedWifiWaiting = true + trustedWifiWaitingSsid = store.trustedWifiWaitingSsid.first() + if (!startRequestGate.isCurrent(generation)) return@launch + TrustedWifiManager.setWaiting(trustedWifiWaitingSsid) + TunnelManager.noteTrustedWifiEvent( + "waiting_restored", + "Android восстановил службу ожидания; проверяем текущую сеть." + ) + startNotificationProfileWatcher() + startStatsUpdater() + acquireTrustedWifiTransitionWakeLock() + releaseWakeLock() + releaseWifiLock() + scheduleTrustedWifiEvaluation(delayMs = 0L) + } else { + startOrWaitForTrustedWifi(refreshedParams) } } else { - launch(Dispatchers.Main) { - stopTunnel(TunnelStopReason.RestoreFailed) - } + stopTunnel(TunnelStopReason.RestoreFailed) } } catch (e: Exception) { - launch(Dispatchers.Main) { + if (startRequestGate.isCurrent(generation)) { stopTunnel(TunnelStopReason.RestoreFailed) } } } } + private fun requestTunnelStart(params: TunnelParams) { + val generation = startRequestGate.next() + pendingStartJob?.cancel() + pendingStartJob = serviceScope.launch { + val access = withContext(Dispatchers.IO) { + AccessLifecycleCoordinator.prepareStart( + applicationContext, + params.profileIndex, + ) + } + if (!startRequestGate.isCurrent(generation)) return@launch + when (access) { + AccessStartDecision.Allowed -> { + val refreshedParams = withContext(Dispatchers.IO) { + buildTunnelParamsFromSettings( + applicationContext, + params.profileIndex, + ) + } + if (refreshedParams == null) { + stopTunnel(TunnelStopReason.RestoreFailed) + return@launch + } + rememberConnectionProfile(refreshedParams.profileIndex) + lastStartParams = refreshedParams + startOrWaitForTrustedWifi(refreshedParams) + } + is AccessStartDecision.Denied -> { + reportAccessDenied(access.status) + stopTunnel(TunnelStopReason.AccessExpired) + } + } + } + } + + private fun applyUpdatedTunnelProfile(profileIndex: Int) { + if (profileIndex !in 0..2) return + val activeProfile = connectionProfileIndex + ?: TunnelManager.activeTunnelProfile.value + ?: return + if (activeProfile != profileIndex) return + + profileRuntimeUpdateJob?.cancel() + profileRuntimeUpdateJob = serviceScope.launch { + val refreshedParams = withContext(Dispatchers.IO) { + buildTunnelParamsFromSettings( + applicationContext, + profileIndex, + ) + } + if (refreshedParams == null) { + TunnelManager.noteAccessLifecycleEvent( + key = "profile_${profileIndex}_runtime_update_invalid", + message = "Новые параметры профиля пока не удалось применить", + warning = true, + ) + return@launch + } + lastStartParams = refreshedParams + if (trustedWifiWaiting) { + TunnelManager.noteAccessLifecycleEvent( + key = "profile_${profileIndex}_runtime_update_waiting", + message = "Новые параметры будут применены после выхода из доверенной сети", + warning = false, + ) + return@launch + } + + when ( + TunnelManager.applyUpdatedProfileConfiguration( + context = applicationContext, + params = refreshedParams, + restartTransport = !isTunnelPaused, + ) + ) { + TunnelProfileRuntimeApplyResult.RESTARTED -> + updateNotification("Обновление подключения...") + TunnelProfileRuntimeApplyResult.STORED_FOR_RESUME -> + updateNotification("Ожидание сети") + TunnelProfileRuntimeApplyResult.INACTIVE, + TunnelProfileRuntimeApplyResult.UNCHANGED -> Unit + } + } + } + + private fun invalidatePendingStart() { + startRequestGate.invalidate() + pendingStartJob?.cancel() + pendingStartJob = null + } + private fun startTunnel(params: TunnelParams, fromTrustedWifiResume: Boolean = false) { - trustedWifiResumeRetryJob?.cancel() - trustedWifiResumeRetryJob = null - trustedWifiResumeRetryCount = 0 + cancelTrustedWifiResumeRetry(resetCount = !fromTrustedWifiResume) trustedWifiResumeInProgress = fromTrustedWifiResume trustedWifiResumeStartedAt = if (fromTrustedWifiResume) System.currentTimeMillis() else 0L trustedWifiWaiting = false @@ -222,35 +370,48 @@ class TunnelService : Service() { updateNotification("Подключение...") acquireWakeLock() acquireWifiLock() + releaseTrustedWifiTransitionWakeLock() // Подготавливаем CaptchaWebViewManager (не создаёт WebView — просто сохраняет контекст) // Вызываем всегда — дёшево, а WebView создаётся на лету при каждом запросе капчи CaptchaWebViewManager.onTunnelStart(applicationContext) - TunnelManager.start(this, params) + if (fromTrustedWifiResume) { + TunnelManager.noteTrustedWifiEvent( + "resume_start", + "Рабочая сеть подтверждена — запускаем VPN после доверенной Wi-Fi." + ) + } + TunnelManager.start(this, params, preserveLogs = fromTrustedWifiResume) startNotificationProfileWatcher() startStatsUpdater() + startActiveProfileRefresh(params.profileIndex) } private fun stopTunnel(reason: TunnelStopReason = TunnelStopReason.User) { + TunnelManager.noteStopRequested() + if (stopSequenceJob?.isActive == true) return + invalidatePendingStart() val effectiveReason = requestedStopReason ?: reason requestedStopReason = effectiveReason updateJob?.cancel() profileNameJob?.cancel() + activeProfileRefreshJob?.cancel() networkChangeJob?.cancel() wakeRescueJob?.cancel() - trustedWifiResumeRetryJob?.cancel() + cancelTrustedWifiResumeRetry(resetCount = true) profileNameJob = null + activeProfileRefreshJob = null networkChangeJob = null wakeRescueJob = null - trustedWifiResumeRetryJob = null - trustedWifiResumeRetryCount = 0 trustedWifiResumeInProgress = false trustedWifiResumeStartedAt = 0L + releaseTrustedWifiTransitionWakeLock() cancelTrustedWifiEvaluations() trustedWifiWaiting = false trustedWifiWaitingSsid = "" lastStartParams = null + forgetConnectionProfile() TrustedWifiManager.clear() TunnelManager.scope.launch { SettingsStore(applicationContext).saveTrustedWifiWaiting(false) @@ -259,30 +420,39 @@ class TunnelService : Service() { // Уничтожаем текущий WebView (если капча решается) и чистим контекст CaptchaWebViewManager.onTunnelStop() - TunnelManager.stop(effectiveReason) releaseWakeLock() releaseWifiLock() lastValidatedNetwork = null lastStableNetworkReconnectAt = 0L stableNetworkWasLost = false activeNetworks.clear() - stopForeground(STOP_FOREGROUND_REMOVE) - stopSelf() + trustedWifiValidatedNetworks.clear() + updateNotification("Отключение…") + + // Служба должна жить до фактической остановки WireGuard и нативного клиента. + // Иначе быстрый повторный тап создаёт новую службу, пока прежний транспорт + // ещё завершается, а onDestroy ошибочно записывает системную остановку. + stopSequenceJob = serviceScope.launch { + try { + TunnelManager.stopAndWait(effectiveReason) + } finally { + intentionalStopCompleted = true + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } + } } private fun startNotificationProfileWatcher() { profileNameJob?.cancel() val settingsStore = SettingsStore(applicationContext) profileNameJob = TunnelManager.scope.launch(Dispatchers.Main) { - combine( - settingsStore.activeProfile, - settingsStore.profileNames - ) { activeProfile, profileNames -> - val profile = activeProfile.coerceIn(0, 2) + val profile = connectionProfileIndex + ?: settingsStore.activeTunnelProfile.first() + ?: settingsStore.activeProfile.first().coerceIn(0, 2) + settingsStore.profileNames.collect { profileNames -> val profileLabel = vpnProfileDisplayName(profile, profileNames) - "WDTT Plus · $profileLabel" - }.collect { prefix -> - notificationProfileTitle = prefix + notificationProfileTitle = "WDTT Plus · $profileLabel" if (trustedWifiWaiting) { updateTrustedWifiNotification() } else if (TunnelManager.running.value && !isTunnelPaused) { @@ -292,6 +462,50 @@ class TunnelService : Service() { } } + private fun startActiveProfileRefresh(profileIndex: Int) { + activeProfileRefreshJob?.cancel() + activeProfileRefreshJob = serviceScope.launch(Dispatchers.IO) { + while (isActive) { + delay(ACTIVE_PROFILE_REFRESH_INTERVAL_MS) + if ( + connectionProfileIndex != profileIndex || + !TunnelManager.running.value || + isTunnelPaused || + trustedWifiWaiting || + TunnelManager.isCaptchaInProgress() || + !hasAnyRealNetwork() + ) { + continue + } + AccessLifecycleCoordinator.refreshProfile( + context = applicationContext, + profileIndex = profileIndex, + force = true, + ) + } + } + } + + private fun rememberConnectionProfile(profile: Int, persist: Boolean = true) { + val normalized = profile.coerceIn(0, 2) + connectionProfileIndex = normalized + TunnelManager.activeTunnelProfile.value = normalized + if (!persist) return + profileStateJob?.cancel() + profileStateJob = TunnelManager.scope.launch { + SettingsStore(applicationContext).saveActiveTunnelProfile(normalized) + } + } + + private fun forgetConnectionProfile() { + connectionProfileIndex = null + TunnelManager.activeTunnelProfile.value = null + profileStateJob?.cancel() + profileStateJob = TunnelManager.scope.launch { + SettingsStore(applicationContext).saveActiveTunnelProfile(null) + } + } + private fun registerScreenStateReceiver() { if (screenStateReceiver != null) return screenStateReceiver = object : BroadcastReceiver() { @@ -340,6 +554,8 @@ class TunnelService : Service() { WifiManager.WIFI_STATE_DISABLING, WifiManager.WIFI_STATE_DISABLED, WifiManager.WIFI_STATE_UNKNOWN -> { + trustedWifiValidatedNetworks.forgetWifi() + acquireTrustedWifiTransitionWakeLock() keepTrustedWifiForeground("Ожидание рабочей сети") scheduleTrustedWifiEvaluation(delayMs = 0L) scheduleTrustedWifiResumeRetry() @@ -349,7 +565,9 @@ class TunnelService : Service() { } WifiManager.NETWORK_STATE_CHANGED_ACTION -> { keepTrustedWifiForeground() - scheduleTrustedWifiEvaluation(delayMs = 0L) + // Сам broadcast не содержит стабильного Network-идентификатора: + // при быстрой смене двух Wi-Fi он может относиться уже к старой сети. + // Авторитетные lost/validated события придут через NetworkCallback. } } } @@ -382,13 +600,23 @@ class TunnelService : Service() { return@launch } - TunnelManager.noteWakeRescueReconnect() - updateNotification("Восстановление VPN...") + if (TunnelManager.isNetworkTransitionGraceActive()) { + updateNotification(buildTunnelNotificationText()) + return@launch + } val reconnectAt = System.currentTimeMillis() - TunnelManager.restartTransport( + val restarted = TunnelManager.restartTransport( reason = "[СОН] После пробуждения VPN не подал признаков жизни. Мягко переподключаю транспорт.", minIntervalMs = 60_000L ) + if (!restarted) { + // Другая ветка восстановления уже перезапускает транспорт либо ещё действует + // её защитный интервал. Не запускаем параллельный таймер, который мог бы + // ошибочно остановить уже восстанавливающийся VPN. + updateNotification(buildTunnelNotificationText()) + return@launch + } + updateNotification("Восстановление VPN...") delay(WAKE_RESCUE_FAIL_OPEN_MS) if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch @@ -447,17 +675,30 @@ class TunnelService : Service() { } trustedWifiNetworkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { - scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS) + if (trustedWifiWaiting) { + scheduleTrustedWifiEvaluation(delayMs = 0L) + } else { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS) + } } override fun onLost(network: Network) { - scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) + if (trustedWifiWaiting) { + trustedWifiValidatedNetworks.lost(network) + acquireTrustedWifiTransitionWakeLock() + scheduleTrustedWifiEvaluation(delayMs = 0L) + scheduleTrustedWifiResumeRetry() + } else { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) + } } override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) { - scheduleTrustedWifiEvaluation( - if (trustedWifiWaiting) TRUSTED_WIFI_EXIT_DELAY_MS else TRUSTED_WIFI_ENTER_DELAY_MS - ) + if (trustedWifiWaiting) { + scheduleTrustedWifiEvaluation(delayMs = 0L) + } else { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS) + } } } val request = NetworkRequest.Builder() @@ -521,21 +762,43 @@ class TunnelService : Service() { } private fun scheduleTrustedWifiResumeRetry() { - trustedWifiResumeRetryJob?.cancel() - val delayMs = if (trustedWifiResumeRetryCount < TRUSTED_WIFI_FAST_RESUME_RETRY_COUNT) { - TRUSTED_WIFI_EXIT_DELAY_MS - } else { - TRUSTED_WIFI_SLOW_RESUME_RETRY_MS - } - trustedWifiResumeRetryCount += 1 - trustedWifiResumeRetryJob = TunnelManager.scope.launch { - delay(delayMs) - if (trustedWifiWaiting) { - evaluateTrustedWifiState() + synchronized(trustedWifiResumeRetryLock) { + if (trustedWifiResumeRetryJob?.isActive == true) return + val plan = trustedWifiResumeRetryPlan(trustedWifiResumeRetryCount) + if (plan.keepCpuAwake) { + acquireTrustedWifiTransitionWakeLock() + } else { + releaseTrustedWifiTransitionWakeLock() + } + trustedWifiResumeRetryJob = TunnelManager.scope.launch { + delay(plan.delayMs) + val shouldEvaluate = synchronized(trustedWifiResumeRetryLock) { + trustedWifiResumeRetryJob = null + if (trustedWifiWaiting) { + trustedWifiResumeRetryCount += 1 + true + } else { + false + } + } + if (shouldEvaluate) evaluateTrustedWifiState() } } } + private fun cancelTrustedWifiResumeRetry(resetCount: Boolean) { + synchronized(trustedWifiResumeRetryLock) { + trustedWifiResumeRetryJob?.cancel() + trustedWifiResumeRetryJob = null + if (resetCount) trustedWifiResumeRetryCount = 0 + } + } + + private fun isTrustedWifiResumeRetryScheduled(): Boolean = + synchronized(trustedWifiResumeRetryLock) { + trustedWifiResumeRetryJob?.isActive == true + } + private suspend fun evaluateTrustedWifiState() { if (DeployManager.isDeploying.value) return val store = SettingsStore(applicationContext) @@ -581,6 +844,11 @@ class TunnelService : Service() { TrustedWifiManager.setWaiting(wifi.ssid) store.saveTrustedWifiWaiting(true, wifi.ssid) withContext(Dispatchers.Main) { updateTrustedWifiNotification() } + cancelTrustedWifiResumeRetry(resetCount = true) + releaseTrustedWifiTransitionWakeLock() + } + if (trustedWifiWaiting && !isTrustedWifiResumeRetryScheduled()) { + releaseTrustedWifiTransitionWakeLock() } } } @@ -597,17 +865,26 @@ class TunnelService : Service() { trustedWifiWaiting = true trustedWifiWaitingSsid = cleanSsid isTunnelPaused = false - trustedWifiResumeRetryCount = 0 + trustedWifiValidatedNetworks.forgetWifi() networkChangeJob?.cancel() wakeRescueJob?.cancel() - trustedWifiResumeRetryJob?.cancel() - trustedWifiResumeRetryJob = null + activeProfileRefreshJob?.cancel() + activeProfileRefreshJob = null + cancelTrustedWifiResumeRetry(resetCount = true) + // Авто-WebView может ещё решать капчу, когда нативный процесс уже + // останавливается. Завершаем его до закрытия stdin клиента. + CaptchaWebViewManager.onTunnelStop() TunnelManager.stopAndWait(TunnelStopReason.TrustedWifi) WireGuardHelper(applicationContext).stopTunnel() + TunnelManager.noteTrustedWifiEvent( + "waiting_enter", + "Подключена доверенная сеть — VPN остановлен и ждёт выхода из неё." + ) TrustedWifiManager.setWaiting(cleanSsid) SettingsStore(applicationContext).saveTrustedWifiWaiting(true, cleanSsid) withContext(Dispatchers.Main) { + releaseTrustedWifiTransitionWakeLock() releaseWakeLock() releaseWifiLock() startNotificationProfileWatcher() @@ -623,6 +900,10 @@ class TunnelService : Service() { if (!trustedWifiWaiting) return if (!hasUsableRealNetworkForTrustedWifiResume()) { val status = "Ожидание рабочей сети" + TunnelManager.noteTrustedWifiEvent( + "resume_wait_network", + "Wi-Fi покинута, но Android ещё не подтвердил рабочую сеть; повторяем проверку." + ) TrustedWifiManager.setStatus(status) withContext(Dispatchers.Main) { keepTrustedWifiForeground(status) @@ -633,6 +914,12 @@ class TunnelService : Service() { } if (android.net.VpnService.prepare(applicationContext) != null) { val status = "VPN-разрешение недоступно. Откройте WDTT Plus для восстановления." + releaseTrustedWifiTransitionWakeLock() + TunnelManager.noteTrustedWifiEvent( + "resume_permission", + "Android не дал повторно занять VPN-слот; требуется открыть приложение.", + warning = true + ) TrustedWifiManager.setStatus(status) withContext(Dispatchers.Main) { updateNotification(status) } return @@ -641,17 +928,54 @@ class TunnelService : Service() { val params = lastStartParams ?: buildTunnelParamsFromSettings(applicationContext) if (params == null) { val status = "Не удалось прочитать профиль VPN. Откройте WDTT Plus." + releaseTrustedWifiTransitionWakeLock() + TunnelManager.noteTrustedWifiEvent( + "resume_profile", + "Не удалось прочитать профиль для автоматического запуска.", + warning = true + ) TrustedWifiManager.setStatus(status) withContext(Dispatchers.Main) { updateNotification(status) } return } + val access = AccessLifecycleCoordinator.prepareStart( + applicationContext, + params.profileIndex, + ) + if (access is AccessStartDecision.Denied) { + withContext(Dispatchers.Main) { + reportAccessDenied(access.status) + stopTunnel(TunnelStopReason.AccessExpired) + } + return + } + + val refreshedParams = buildTunnelParamsFromSettings( + applicationContext, + params.profileIndex, + ) + if (refreshedParams == null) { + val status = "Не удалось прочитать обновлённый профиль VPN. Откройте WDTT Plus." + releaseTrustedWifiTransitionWakeLock() + TunnelManager.noteTrustedWifiEvent( + "resume_profile_refresh", + "Не удалось повторно прочитать профиль после проверки перед запуском.", + warning = true, + ) + TrustedWifiManager.setStatus(status) + withContext(Dispatchers.Main) { updateNotification(status) } + return + } + lastStartParams = refreshedParams + withContext(Dispatchers.Main) { + acquireTrustedWifiTransitionWakeLock() Log.i("TunnelService", "Доверенная Wi-Fi покинута, запускаем VPN на рабочей сети") // startTunnel синхронно включает защитный resumeInProgress до снятия waiting. // Поэтому очередной сетевой callback уже не может оставить сервис между // состояниями: без VPN, без ожидания и с удалённым уведомлением. - startTunnel(params, fromTrustedWifiResume = true) + startTunnel(refreshedParams, fromTrustedWifiResume = true) VpnWidgetProvider.updateAllWidgets(applicationContext) } } @@ -661,6 +985,23 @@ class TunnelService : Service() { keepTrustedWifiForeground() } + private fun reportAccessDenied(status: AccessLifecycleStatus) { + val title = status.title.ifBlank { "Профиль временно недоступен" } + val message = status.message.ifBlank { + "Откройте вкладку «Туннель», чтобы проверить доступные действия." + } + TunnelManager.reportConnectionIssue( + title, + message, + kind = ConnectionIssueKind.ACCESS, + ) + TunnelManager.noteAccessLifecycleEvent( + key = "start_denied", + message = title, + warning = true, + ) + } + private fun keepTrustedWifiForeground(statusOverride: String? = null) { val networkName = trustedWifiWaitingSsid.ifBlank { "доверенная Wi-Fi" } val text = statusOverride ?: "VPN выключен в сети «$networkName» · ожидание выхода" @@ -673,6 +1014,7 @@ class TunnelService : Service() { private fun setupNetworkCallback() { connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager activeNetworks.clear() + trustedWifiValidatedNetworks.clear() networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { @@ -698,10 +1040,13 @@ class TunnelService : Service() { override fun onLost(network: Network) { super.onLost(network) - if (trustedWifiWaiting) { - scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) - } activeNetworks.remove(network) + trustedWifiValidatedNetworks.lost(network) + if (trustedWifiWaiting) { + acquireTrustedWifiTransitionWakeLock() + scheduleTrustedWifiEvaluation(delayMs = 0L) + scheduleTrustedWifiResumeRetry() + } if (AMNEZIA_STYLE_RECOVERY) { if (lastValidatedNetwork == network) { lastValidatedNetwork = null @@ -726,8 +1071,22 @@ class TunnelService : Service() { override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) { super.onCapabilitiesChanged(network, networkCapabilities) + val usableRealNetwork = + networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && + networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) && + networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) + trustedWifiValidatedNetworks.update( + network = network, + validated = usableRealNetwork, + wifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) + ) if (trustedWifiWaiting) { - scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) + if (usableRealNetwork) { + acquireTrustedWifiTransitionWakeLock() + scheduleTrustedWifiEvaluation(delayMs = 0L) + } else { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) + } } if (AMNEZIA_STYLE_RECOVERY) { handleStableNetworkCapabilities(network, networkCapabilities) @@ -772,7 +1131,9 @@ class TunnelService : Service() { if (TunnelManager.running.value) { TunnelManager.noteUnderlyingNetworkChanged( "Android подтвердил рабочую сеть", - graceMs = STABLE_NETWORK_RECONNECT_DELAY_MS, + graceMs = transportRecoveryPolicy( + lastStartParams?.managedConfigFirstStart == true + ).networkSettleDelayMs, replaceGrace = false ) } @@ -789,27 +1150,31 @@ class TunnelService : Service() { lastNetworkChangeTime = now if (!TunnelManager.running.value || isTunnelPaused) return + val recoveryPolicy = transportRecoveryPolicy( + lastStartParams?.managedConfigFirstStart == true + ) TunnelManager.noteUnderlyingNetworkChanged( reason, - graceMs = STABLE_NETWORK_RECONNECT_DELAY_MS + 30_000L, + graceMs = recoveryPolicy.networkSettleDelayMs + 30_000L, replaceGrace = true ) networkChangeJob?.cancel() networkChangeJob = TunnelManager.scope.launch(Dispatchers.Main) { Log.d("TunnelService", "$reason, ждём короткую стабилизацию перед reconnect") - delay(STABLE_NETWORK_RECONNECT_DELAY_MS) + delay(recoveryPolicy.networkSettleDelayMs) if (lastNetworkChangeTime != now) return@launch if (!TunnelManager.running.value || !hasAnyRealNetwork() || TunnelManager.isCaptchaInProgress()) return@launch val sinceLastReconnect = System.currentTimeMillis() - lastStableNetworkReconnectAt - if (sinceLastReconnect < STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS) { + if (sinceLastReconnect < recoveryPolicy.reconnectMinIntervalMs) { Log.d("TunnelService", "Пропускаем reconnect: недавний reconnect уже был") return@launch } lastStableNetworkReconnectAt = System.currentTimeMillis() TunnelManager.restartTransport( reason = "[СЕТЬ] Android подтвердил новую сеть. Мягко переподключаю транспорт.", - minIntervalMs = STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS + minIntervalMs = recoveryPolicy.reconnectMinIntervalMs, + force = recoveryPolicy.forceRestart, ) } } @@ -827,16 +1192,7 @@ class TunnelService : Service() { @Suppress("DEPRECATION") private fun hasUsableRealNetworkForTrustedWifiResume(): Boolean { - val cm = connectivityManager - ?: (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).also { - connectivityManager = it - } - return cm.allNetworks.any { network -> - val caps = cm.getNetworkCapabilities(network) ?: return@any false - caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && - caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) && - caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) - } + return trustedWifiValidatedNetworks.hasUsableNetwork() } private fun scheduleNetworkSettleCheck( @@ -925,6 +1281,37 @@ class TunnelService : Service() { } } + @Synchronized + private fun acquireTrustedWifiTransitionWakeLock() { + val lock = trustedWifiTransitionWakeLock ?: run { + val pm = getSystemService(POWER_SERVICE) as PowerManager + pm.newWakeLock( + PowerManager.PARTIAL_WAKE_LOCK, + "wdtt:trusted_wifi_transition" + ).apply { + setReferenceCounted(false) + trustedWifiTransitionWakeLock = this + } + } + runCatching { + if (!lock.isHeld) { + lock.acquire(TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS) + } + }.onFailure { + Log.w("TunnelService", "Не удалось удержать CPU для выхода из доверенной Wi-Fi: ${it.message}") + } + } + + @Synchronized + private fun releaseTrustedWifiTransitionWakeLock() { + trustedWifiTransitionWakeLock?.let { lock -> + runCatching { + if (lock.isHeld) lock.release() + } + } + trustedWifiTransitionWakeLock = null + } + @Suppress("DEPRECATION") private fun acquireWifiLock() { if (wifiLock?.isHeld == true) return @@ -968,6 +1355,8 @@ class TunnelService : Service() { TunnelManager.running.value -> { trustedWifiResumeInProgress = false trustedWifiResumeStartedAt = 0L + cancelTrustedWifiResumeRetry(resetCount = true) + releaseTrustedWifiTransitionWakeLock() } trustedWifiResumeStartedAt > 0L && System.currentTimeMillis() - trustedWifiResumeStartedAt >= @@ -977,6 +1366,15 @@ class TunnelService : Service() { trustedWifiWaiting = true val status = "VPN не запустился, повторяем восстановление" Log.w("TunnelService", status) + CaptchaWebViewManager.onTunnelStop() + releaseWakeLock() + releaseWifiLock() + acquireTrustedWifiTransitionWakeLock() + TunnelManager.noteTrustedWifiEvent( + "resume_timeout", + "Автоматический запуск не начался за 30 секунд; повторяем.", + warning = true + ) TrustedWifiManager.setWaiting("", status) SettingsStore(applicationContext).saveTrustedWifiWaiting(true) keepTrustedWifiForeground(status) @@ -1169,6 +1567,10 @@ class TunnelService : Service() { override fun onDestroy() { super.onDestroy() + val stopReasonOnUnexpectedDestroy = requestedStopReason ?: TunnelStopReason.ServiceDestroyed + val stopWasCompleted = intentionalStopCompleted + invalidatePendingStart() + serviceScope.cancel() wakeRescueJob?.cancel() networkChangeJob?.cancel() screenStateReceiver?.let { @@ -1187,13 +1589,17 @@ class TunnelService : Service() { } trustedWifiSettingsJob?.cancel() cancelTrustedWifiEvaluations() - trustedWifiResumeRetryJob?.cancel() + cancelTrustedWifiResumeRetry(resetCount = false) + releaseTrustedWifiTransitionWakeLock() if (trustedWifiWaiting || trustedWifiResumeInProgress) { releaseWakeLock() releaseWifiLock() TrustedWifiManager.setStatus("Служба ожидания будет восстановлена Android") - } else { - stopTunnel(TunnelStopReason.ServiceDestroyed) + } else if (!stopWasCompleted) { + CaptchaWebViewManager.onTunnelStop() + releaseWakeLock() + releaseWifiLock() + TunnelManager.stop(stopReasonOnUnexpectedDestroy) } } diff --git a/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt b/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt index a86bd8c..cb2fe7d 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt @@ -2,62 +2,141 @@ package com.wdtt.plus import android.content.Context import android.content.Intent -import kotlinx.coroutines.flow.first -suspend fun buildTunnelParamsFromSettings(context: Context): TunnelParams? { +internal const val TUNNEL_PROFILE_INDEX_EXTRA = "profile_index" +internal const val MANAGED_CONFIG_FIRST_START_EXTRA = "managed_config_first_start" + +internal data class TransportRecoveryPolicy( + val networkSettleDelayMs: Long, + val reconnectMinIntervalMs: Long, + val processRestartDelayMs: Long, + val forceRestart: Boolean, +) + +internal fun transportRecoveryPolicy( + managedConfigFirstStart: Boolean, +): TransportRecoveryPolicy = if (managedConfigFirstStart) { + TransportRecoveryPolicy( + networkSettleDelayMs = 3_000L, + reconnectMinIntervalMs = 8_000L, + processRestartDelayMs = 250L, + forceRestart = true, + ) +} else { + TransportRecoveryPolicy( + networkSettleDelayMs = 15_000L, + reconnectMinIntervalMs = 2 * 60_000L, + processRestartDelayMs = 2_500L, + forceRestart = false, + ) +} + +internal enum class TunnelToggleAction { + START, + STOP, + REQUEST_VPN_PERMISSION, +} + +internal fun tunnelToggleAction( + running: Boolean, + trustedWifiWaiting: Boolean, + vpnPermissionRequired: Boolean, +): TunnelToggleAction = when { + running || trustedWifiWaiting -> TunnelToggleAction.STOP + vpnPermissionRequired -> TunnelToggleAction.REQUEST_VPN_PERMISSION + else -> TunnelToggleAction.START +} + +internal fun displayedTunnelProfile( + selectedProfile: Int, + activeTunnelProfile: Int?, + running: Boolean, + trustedWifiWaiting: Boolean, +): Int = if (running || trustedWifiWaiting) { + activeTunnelProfile ?: selectedProfile +} else { + selectedProfile +}.coerceIn(0, 2) + +internal fun shouldUseManagedConfigFirstStart( + remoteManaged: Boolean, + profileMaxWorkers: Int, +): Boolean = remoteManaged && profileMaxWorkers == TUNNEL_WORKERS_PER_GROUP + +suspend fun buildTunnelParamsFromSettings( + context: Context, + profileIndex: Int? = null, +): TunnelParams? { val store = SettingsStore(context.applicationContext) - val linkMode = store.wdttLinkMode.first() - val workersPerHash = store.workersPerHash.first() - val sni = store.sni.first() - val protocol = store.protocol.first() - val vkCallsPreflight = store.vkCallsPreflight.first() - val captchaMode = sanitizeTunnelCaptchaMode(store.captchaMode.first()) - val captchaSolveMethod = store.captchaSolveMethod.first() - val fingerprint = store.selectedFingerprint.first() - val clientIds = store.activeClientIds.first() + val saved = store.tunnelProfileSnapshot(profileIndex) + return buildTunnelParams(saved) +} - return if (linkMode) { - val parts = WdttDeepLink.validate(store.wdttLink.first()).parts ?: return null +internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? { + val workersPerHash = normalizeTunnelWorkerCount( + saved.workersPerHash, + saved.profileMaxWorkers + ) + val managedConfigFirstStart = shouldUseManagedConfigFirstStart( + remoteManaged = saved.remoteManaged, + profileMaxWorkers = saved.profileMaxWorkers, + ) + val linkParts = saved.link + .takeIf { saved.linkMode } + ?.let { WdttDeepLink.validate(it).parts } + + return if (linkParts != null) { TunnelParams( - peer = "${parts.host}:${parts.dtlsPort}", - vkHashes = parts.hashes, + peer = "${linkParts.host}:${linkParts.dtlsPort}", + vkHashes = linkParts.hashes, secondaryVkHash = "", workersPerHash = workersPerHash, - port = parts.localPort, - sni = sni, - connectionPassword = parts.password, - protocol = protocol, - vkCallsPreflight = vkCallsPreflight, - captchaMode = captchaMode, - captchaSolveMethod = captchaSolveMethod, - fingerprint = fingerprint, - clientIds = clientIds + port = linkParts.localPort, + sni = saved.sni, + connectionPassword = linkParts.password, + protocol = saved.protocol, + vkCallsPreflight = saved.vkCallsPreflight, + captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode), + captchaSolveMethod = saved.captchaSolveMethod, + fingerprint = saved.fingerprint, + clientIds = saved.clientIds, + customVkCredentialsEnabled = saved.customVkCredentialsEnabled, + customVkClientId = saved.customVkClientId, + customVkClientSecret = saved.customVkClientSecret, + profileMaxWorkers = saved.profileMaxWorkers, + managedConfigFirstStart = managedConfigFirstStart, + profileIndex = saved.profileIndex, ) } else { - val basePeer = store.peer.first().trim() - val hashes = store.vkHashes.first().trim() - val password = store.connectionPassword.first() + val basePeer = saved.peer.trim() + val hashes = saved.vkHashes.trim() + val password = saved.connectionPassword if (basePeer.isBlank() || hashes.isBlank() || password.isBlank()) return null - val manualPortsEnabled = store.manualPortsEnabled.first() - val serverDtlsPort = if (manualPortsEnabled) store.serverDtlsPort.first() else 56000 - val localPort = if (manualPortsEnabled) store.listenPort.first() else 9000 + val serverDtlsPort = if (saved.manualPortsEnabled) saved.serverDtlsPort else 56000 + val localPort = if (saved.manualPortsEnabled) saved.listenPort else 9000 val peerWithPort = if (basePeer.contains(":")) basePeer else "$basePeer:$serverDtlsPort" TunnelParams( peer = peerWithPort, vkHashes = hashes, - secondaryVkHash = store.secondaryVkHash.first(), + secondaryVkHash = saved.secondaryVkHash, workersPerHash = workersPerHash, port = localPort, - sni = sni, + sni = saved.sni, connectionPassword = password, - protocol = protocol, - vkCallsPreflight = vkCallsPreflight, - captchaMode = captchaMode, - captchaSolveMethod = captchaSolveMethod, - fingerprint = fingerprint, - clientIds = clientIds + protocol = saved.protocol, + vkCallsPreflight = saved.vkCallsPreflight, + captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode), + captchaSolveMethod = saved.captchaSolveMethod, + fingerprint = saved.fingerprint, + clientIds = saved.clientIds, + customVkCredentialsEnabled = saved.customVkCredentialsEnabled, + customVkClientId = saved.customVkClientId, + customVkClientSecret = saved.customVkClientSecret, + profileMaxWorkers = saved.profileMaxWorkers, + managedConfigFirstStart = managedConfigFirstStart, + profileIndex = saved.profileIndex, ) } } @@ -79,6 +158,12 @@ suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? { putExtra("captcha_solve_method", params.captchaSolveMethod) putExtra("fingerprint", params.fingerprint) putExtra("client_ids", params.clientIds) + putExtra("custom_vk_credentials_enabled", params.customVkCredentialsEnabled) + putExtra("custom_vk_client_id", params.customVkClientId) + putExtra("custom_vk_client_secret", params.customVkClientSecret) + putExtra("profile_max_workers", params.profileMaxWorkers) + putExtra(MANAGED_CONFIG_FIRST_START_EXTRA, params.managedConfigFirstStart) + putExtra(TUNNEL_PROFILE_INDEX_EXTRA, params.profileIndex) } } diff --git a/app/src/main/java/com/wdtt/plus/TunnelStartRequestGate.kt b/app/src/main/java/com/wdtt/plus/TunnelStartRequestGate.kt new file mode 100644 index 0000000..9f683c5 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/TunnelStartRequestGate.kt @@ -0,0 +1,20 @@ +package com.wdtt.plus + +/** Keeps delayed service starts from reviving an obsolete or explicitly stopped request. */ +internal class TunnelStartRequestGate { + private var generation: Long = 0 + + @Synchronized + fun next(): Long { + generation += 1 + return generation + } + + @Synchronized + fun invalidate() { + generation += 1 + } + + @Synchronized + fun isCurrent(value: Long): Boolean = value == generation +} diff --git a/app/src/main/java/com/wdtt/plus/TunnelStopCoordinator.kt b/app/src/main/java/com/wdtt/plus/TunnelStopCoordinator.kt new file mode 100644 index 0000000..89322cc --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/TunnelStopCoordinator.kt @@ -0,0 +1,61 @@ +package com.wdtt.plus + +import android.content.Context +import android.content.Intent +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeoutOrNull + +enum class TunnelStopResult { + ALREADY_STOPPED, + STOPPED, + TIMED_OUT, + FAILED; + + val succeeded: Boolean + get() = this == ALREADY_STOPPED || this == STOPPED +} + +object TunnelStopCoordinator { + const val DEFAULT_TIMEOUT_MS = 20_000L + const val DIRECT_NETWORK_SETTLE_MS = 1_000L + + suspend fun stopAndAwait( + context: Context, + timeoutMs: Long = DEFAULT_TIMEOUT_MS, + ): TunnelStopResult { + val appContext = context.applicationContext + val helper = WireGuardHelper(appContext) + val managerActive = TunnelManager.running.value || + TunnelManager.transition.value != TunnelTransition.IDLE + val wireGuardActive = runCatching { helper.isTunnelUp() }.getOrDefault(false) + if (!managerActive && !wireGuardActive) return TunnelStopResult.ALREADY_STOPPED + + val serviceRequested = runCatching { + appContext.startService( + Intent(appContext, TunnelService::class.java).apply { action = "STOP" } + ) + }.isSuccess + if (!serviceRequested) return TunnelStopResult.FAILED + + val stopped = withTimeoutOrNull(timeoutMs.coerceAtLeast(1_000L)) { + // The service owns foreground/lifecycle cleanup. Calling the manager as well makes + // this operation awaitable and repairs a stale `running=false` state with a live + // WireGuard tunnel. Both paths are idempotent behind the same start/stop mutex. + TunnelManager.stopAndWait( + reason = TunnelStopReason.User, + context = appContext, + forceVpnRelease = true, + ) + while ( + TunnelManager.running.value || + TunnelManager.transition.value != TunnelTransition.IDLE || + helper.isTunnelUp() + ) { + delay(50L) + } + true + } == true + + return if (stopped) TunnelStopResult.STOPPED else TunnelStopResult.TIMED_OUT + } +} diff --git a/app/src/main/java/com/wdtt/plus/TunnelWorkerPolicy.kt b/app/src/main/java/com/wdtt/plus/TunnelWorkerPolicy.kt new file mode 100644 index 0000000..2b75f16 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/TunnelWorkerPolicy.kt @@ -0,0 +1,14 @@ +package com.wdtt.plus + +internal const val TUNNEL_WORKERS_PER_GROUP = 9 +internal const val APP_MAX_WORKERS = 108 + +internal fun normalizeTunnelWorkerCount(requested: Int, profileMaxWorkers: Int = 0): Int { + val configuredMaximum = (profileMaxWorkers / TUNNEL_WORKERS_PER_GROUP) * TUNNEL_WORKERS_PER_GROUP + val maximum = configuredMaximum.takeIf { it >= TUNNEL_WORKERS_PER_GROUP } + ?.coerceAtMost(APP_MAX_WORKERS) + ?: APP_MAX_WORKERS + val rounded = ((requested.coerceAtLeast(TUNNEL_WORKERS_PER_GROUP) + TUNNEL_WORKERS_PER_GROUP / 2) / + TUNNEL_WORKERS_PER_GROUP) * TUNNEL_WORKERS_PER_GROUP + return rounded.coerceIn(TUNNEL_WORKERS_PER_GROUP, maximum) +} diff --git a/app/src/main/java/com/wdtt/plus/VkClientCredentials.kt b/app/src/main/java/com/wdtt/plus/VkClientCredentials.kt new file mode 100644 index 0000000..68fd29e --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/VkClientCredentials.kt @@ -0,0 +1,30 @@ +package com.wdtt.plus + +const val DEFAULT_VK_CLIENT_IDS = "6287487,8202606" + +val BUILT_IN_VK_CLIENT_IDS: List = DEFAULT_VK_CLIENT_IDS.split(',') + +data class CustomVkClientCredentials( + val enabled: Boolean = false, + val clientId: String = "", + val clientSecret: String = "" +) { + val complete: Boolean + get() = isValidVkClientId(clientId) && clientSecret.isNotBlank() +} + +fun normalizeVkClientId(value: String): String = + value.filter(Char::isDigit).take(20) + +fun normalizeVkClientSecret(value: String): String = + value.trim().take(512) + +fun isValidVkClientId(value: String): Boolean = + value.isNotBlank() && value.length <= 20 && value.all(Char::isDigit) + +fun customVkCredentialsError(credentials: CustomVkClientCredentials): String? = when { + !credentials.enabled -> null + !isValidVkClientId(credentials.clientId) -> "Укажите числовой Client ID приложения VK." + credentials.clientSecret.isBlank() -> "Укажите защищённый ключ (Client secret) приложения VK." + else -> null +} diff --git a/app/src/main/java/com/wdtt/plus/VkJoinLink.kt b/app/src/main/java/com/wdtt/plus/VkJoinLink.kt index cbd5449..857c30a 100644 --- a/app/src/main/java/com/wdtt/plus/VkJoinLink.kt +++ b/app/src/main/java/com/wdtt/plus/VkJoinLink.kt @@ -1,6 +1,8 @@ package com.wdtt.plus object VkJoinLink { + private val hashPattern = Regex("^[A-Za-z0-9_-]{1,512}$") + fun extractHash(input: String): String { var s = input.trim().trim('<', '>', '"', '\'') if (s.isBlank()) return "" @@ -20,5 +22,30 @@ object VkJoinLink { } return s.trim().trimEnd('/') } -} + fun isValidHash(value: String): Boolean = hashPattern.matches(value.trim()) + + fun isValidInput(input: String): Boolean { + val clean = input.trim().trim('<', '>', '"', '\'') + if (clean.isBlank()) return false + val isLink = clean.startsWith("http://", ignoreCase = true) || + clean.startsWith("https://", ignoreCase = true) + return if (isLink) { + clean.contains("/call/join/", ignoreCase = true) && + isValidHash(extractHash(clean)) + } else { + isValidHash(clean) + } + } + + fun normalizeHashes(input: String): String? { + if (input.isBlank()) return "" + val values = input.split(Regex("[,\\s]+")) + .filter { it.isNotBlank() } + if (values.isEmpty() || values.any { !isValidInput(it) }) return null + return values.map(::extractHash).distinct().joinToString(",") + } + + fun extractValidHash(input: String): String = + extractHash(input).takeIf { isValidInput(input) }.orEmpty() +} diff --git a/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt b/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt index 1489a35..1e9b467 100644 --- a/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt +++ b/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt @@ -43,9 +43,24 @@ class VpnCompactWidgetProvider : AppWidgetProvider() { val waiting = TrustedWifiManager.state.value.waiting scope.launch { val settingsStore = SettingsStore(context) - val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2) + val selectedProfile = settingsStore.activeProfile.first().coerceIn(0, 2) + val activeTunnelProfile = TunnelManager.activeTunnelProfile.value + ?: settingsStore.activeTunnelProfile.first() + val displayedProfile = displayedTunnelProfile( + selectedProfile = selectedProfile, + activeTunnelProfile = activeTunnelProfile, + running = running, + trustedWifiWaiting = waiting, + ) val profileNames = settingsStore.profileNames.first() - val profileName = vpnProfileDisplayName(activeProfile, profileNames) + val profileName = vpnProfileDisplayName(displayedProfile, profileNames) + val accessLifecycle = + settingsStore.accessLifecycleForProfile(displayedProfile).toUiState() + val accessBlocked = + accessLifecycle.managed && + !accessLifecycle.allowConnect && + !running && + !waiting appWidgetIds.forEach { appWidgetId -> val views = RemoteViews(context.packageName, R.layout.vpn_widget_compact) @@ -56,7 +71,12 @@ class VpnCompactWidgetProvider : AppWidgetProvider() { ) views.setTextViewText( R.id.compact_widget_profile, - if (waiting) "Ожидание" else profileName + when { + waiting -> "Ожидание" + accessBlocked -> + accessLifecycle.title.ifBlank { accessLifecycle.fallbackTitle() } + else -> profileName + } ) val toggleIntent = Intent(context, VpnWidgetProvider::class.java).apply { diff --git a/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt b/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt index 8cf0577..774b25f 100644 --- a/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt +++ b/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt @@ -45,8 +45,18 @@ class VpnWidgetProvider : AppWidgetProvider() { val trustedWifi = TrustedWifiManager.state.value scope.launch { val settingsStore = SettingsStore(context) - val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2) + val selectedProfile = settingsStore.activeProfile.first().coerceIn(0, 2) + val activeTunnelProfile = TunnelManager.activeTunnelProfile.value + ?: settingsStore.activeTunnelProfile.first() + val displayedProfile = displayedTunnelProfile( + selectedProfile = selectedProfile, + activeTunnelProfile = activeTunnelProfile, + running = running, + trustedWifiWaiting = trustedWifi.waiting, + ) val profileNames = settingsStore.profileNames.first() + val accessLifecycle = + settingsStore.accessLifecycleForProfile(displayedProfile).toUiState() for (appWidgetId in appWidgetIds) { updateWidgetState( context = context, @@ -54,8 +64,9 @@ class VpnWidgetProvider : AppWidgetProvider() { appWidgetId = appWidgetId, running = running, trustedWifi = trustedWifi, - activeProfile = activeProfile, - profileNames = profileNames + activeProfile = displayedProfile, + profileNames = profileNames, + accessLifecycle = accessLifecycle, ) } } @@ -65,38 +76,53 @@ class VpnWidgetProvider : AppWidgetProvider() { super.onReceive(context, intent) if (intent.action == ACTION_WIDGET_TOGGLE) { runCatching { - if (TunnelManager.running.value || TrustedWifiManager.state.value.waiting) { - // Останавливаем туннель - val stopIntent = Intent(context, TunnelService::class.java).apply { action = "STOP" } - context.startService(stopIntent) - updateAllWidgets(context) - return - } + when ( + tunnelToggleAction( + running = TunnelManager.running.value, + trustedWifiWaiting = TrustedWifiManager.state.value.waiting, + vpnPermissionRequired = VpnService.prepare(context) != null, + ) + ) { + TunnelToggleAction.STOP -> { + context.startService( + Intent(context, TunnelService::class.java).apply { action = "STOP" } + ) + updateAllWidgets(context) + } + TunnelToggleAction.REQUEST_VPN_PERMISSION -> { + Toast.makeText( + context, + "Откройте WDTT Plus и выдайте VPN-разрешение", + Toast.LENGTH_LONG + ).show() + openMainActivity(context) + } + TunnelToggleAction.START -> scope.launch { + try { + val startIntent = buildTunnelStartIntentFromSettings(context) + if (startIntent == null) { + Toast.makeText( + context, + "Заполните настройки подключения в WDTT Plus", + Toast.LENGTH_LONG + ).show() + openMainActivity(context) + return@launch + } - if (VpnService.prepare(context) != null) { - Toast.makeText(context, "Откройте WDTT Plus и выдайте VPN-разрешение", Toast.LENGTH_LONG).show() - openMainActivity(context) - return - } - - // Запуск туннеля в фоне - scope.launch { - try { - val startIntent = buildTunnelStartIntentFromSettings(context) - if (startIntent == null) { - Toast.makeText(context, "Заполните настройки подключения в WDTT Plus", Toast.LENGTH_LONG).show() - openMainActivity(context) - return@launch + if (Build.VERSION.SDK_INT >= 26) { + context.startForegroundService(startIntent) + } else { + context.startService(startIntent) + } + } catch (e: Exception) { + Log.e("VpnWidget", "Failed to start tunnel from widget", e) + Toast.makeText( + context, + "Ошибка запуска: ${e.localizedMessage}", + Toast.LENGTH_SHORT + ).show() } - - if (Build.VERSION.SDK_INT >= 26) { - context.startForegroundService(startIntent) - } else { - context.startService(startIntent) - } - } catch (e: Exception) { - Log.e("VpnWidget", "Failed to start tunnel from widget", e) - Toast.makeText(context, "Ошибка запуска: ${e.localizedMessage}", Toast.LENGTH_SHORT).show() } } }.onFailure { e -> @@ -112,7 +138,8 @@ class VpnWidgetProvider : AppWidgetProvider() { running: Boolean, trustedWifi: TrustedWifiRuntimeState, activeProfile: Int, - profileNames: List + profileNames: List, + accessLifecycle: AccessLifecycleUiState, ) { val views = RemoteViews(context.packageName, R.layout.vpn_widget) @@ -129,8 +156,24 @@ class VpnWidgetProvider : AppWidgetProvider() { views.setTextColor(R.id.widget_status, 0xFF00E5FF.toInt()) // Неоновый голубой views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_active) } else { - views.setTextViewText(R.id.widget_status, "Отключено") - views.setTextColor(R.id.widget_status, 0xFF888888.toInt()) // Матовый серый + val accessBlocked = accessLifecycle.managed && !accessLifecycle.allowConnect + views.setTextViewText( + R.id.widget_status, + accessLifecycle.title.takeIf { accessBlocked && it.isNotBlank() } + ?: accessLifecycle.fallbackTitle().takeIf { accessBlocked } + ?: "Отключено" + ) + views.setTextColor( + R.id.widget_status, + if ( + accessLifecycle.severity == AccessLifecycleSeverity.ERROR && + accessBlocked + ) { + 0xFFFF6B6B.toInt() + } else { + 0xFF888888.toInt() + } + ) views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_inactive) } diff --git a/app/src/main/java/com/wdtt/plus/WdttApplication.kt b/app/src/main/java/com/wdtt/plus/WdttApplication.kt index a0e50ea..3401a73 100644 --- a/app/src/main/java/com/wdtt/plus/WdttApplication.kt +++ b/app/src/main/java/com/wdtt/plus/WdttApplication.kt @@ -37,6 +37,12 @@ class WdttApplication : Application() { } val settingsStore = SettingsStore(this) + CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { + RemoteActionCatalogGateway.fetch(force = true) + } + CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { + AccessLifecycleCoordinator.refreshAllIfStale(this@WdttApplication) + } // Реактивно обновляем виджеты при изменении туннеля, активного профиля или его названия. CoroutineScope(SupervisorJob() + Dispatchers.Main).launch { @@ -45,8 +51,9 @@ class WdttApplication : Application() { TunnelManager.running, TrustedWifiManager.state, settingsStore.activeProfile, - settingsStore.profileNames - ) { _, _, _, _ -> Unit }.collect { + settingsStore.profileNames, + settingsStore.activeAccessLifecycle + ) { _, _, _, _, _ -> Unit }.collect { VpnWidgetProvider.updateAllWidgets(this@WdttApplication) } } catch (e: Exception) { diff --git a/app/src/main/java/com/wdtt/plus/WdttDocument.kt b/app/src/main/java/com/wdtt/plus/WdttDocument.kt new file mode 100644 index 0000000..b2339f6 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/WdttDocument.kt @@ -0,0 +1,28 @@ +package com.wdtt.plus + +object WdttDocument { + const val MIME_TYPE = "application/vnd.wdtt.plus" + const val FILE_EXTENSION = ".wdtt" + + const val LEGACY_TRANSFER_MIME_TYPE = "application/vnd.wdtt.plus.transfer" + const val LEGACY_CLIENT_MIME_TYPE = "application/vnd.wdtt.plus.client" + + fun acceptedMimeTypes(): Array = arrayOf( + MIME_TYPE, + LEGACY_TRANSFER_MIME_TYPE, + LEGACY_CLIENT_MIME_TYPE, + "application/json", + "application/octet-stream", + "text/plain", + ) + + fun isAcceptedMimeType(value: String?): Boolean { + val normalized = value?.substringBefore(';')?.trim()?.lowercase().orEmpty() + return acceptedMimeTypes().any { it == normalized } + } + + fun fileName(stem: String): String { + val cleanStem = stem.trim().removeSuffix(FILE_EXTENSION).ifBlank { "WDTT-Plus" } + return cleanStem + FILE_EXTENSION + } +} diff --git a/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt b/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt index c16a069..fd7dcb7 100644 --- a/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt +++ b/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt @@ -16,6 +16,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import java.io.ByteArrayInputStream +import java.security.MessageDigest class WireGuardHelper(context: Context) { private val appContext = context.applicationContext @@ -24,6 +25,7 @@ class WireGuardHelper(context: Context) { private companion object { val wgMutex = Mutex() var sharedTunnel: WgTunnel? = null + var sharedConfigFingerprint: String? = null } class WgTunnel( @@ -38,6 +40,7 @@ class WireGuardHelper(context: Context) { val isCurrentTunnel = sharedTunnel === this if (isCurrentTunnel) { sharedTunnel = null + sharedConfigFingerprint = null } if (isCurrentTunnel && !suppressDownCallback) { onExternalDown?.invoke() @@ -55,19 +58,6 @@ class WireGuardHelper(context: Context) { throw IllegalStateException("VPN-разрешение не выдано") } - ensureGoBackendServiceStarted() - - sharedTunnel?.let { existingTunnel -> - try { - existingTunnel.suppressDownCallback = true - backend.setState(existingTunnel, Tunnel.State.DOWN, null) - } catch (e: Exception) { - Log.w("WG", "Failed to stop previous tunnel before restart: ${e.readableMessage()}") - } - sharedTunnel = null - delay(150) - } - val parsedConfig = Config.parse(ByteArrayInputStream(configString.toByteArray(Charsets.UTF_8))) val builder = Interface.Builder() @@ -132,11 +122,42 @@ class WireGuardHelper(context: Context) { .addPeer(peerBuilder.build()) .build() + sharedTunnel?.let { existingTunnel -> + val existingUp = runCatching { + backend.getState(existingTunnel) == Tunnel.State.UP + }.getOrDefault(false) + if ( + shouldReuseRunningWireGuard( + tunnelUp = existingUp, + currentConfigFingerprint = sharedConfigFingerprint, + updatedConfig = finalConfig, + ) + ) { + Log.d("WG", "WireGuard config unchanged; keeping the current VPN interface") + return@withContext + } + } + + ensureGoBackendServiceStarted() + + sharedTunnel?.let { existingTunnel -> + try { + existingTunnel.suppressDownCallback = true + backend.setState(existingTunnel, Tunnel.State.DOWN, null) + } catch (e: Exception) { + Log.w("WG", "Failed to stop previous tunnel before restart: ${e.readableMessage()}") + } + sharedTunnel = null + sharedConfigFingerprint = null + delay(150) + } + val nextTunnel = WgTunnel { TunnelManager.onWireGuardStoppedExternally() } setTunnelUpWithRetry(nextTunnel, finalConfig) sharedTunnel = nextTunnel + sharedConfigFingerprint = wireGuardConfigFingerprint(finalConfig) Log.d("WG", "WireGuard tunnel started successfully") } catch (e: Exception) { val detailed = "WireGuard start failed: ${e.readableMessage()}; ${configString.describeWireGuardConfig()}" @@ -154,6 +175,7 @@ class WireGuardHelper(context: Context) { currentTunnel.suppressDownCallback = true backend.setState(currentTunnel, Tunnel.State.DOWN, null) sharedTunnel = null + sharedConfigFingerprint = null delay(150) startTunnelLocked(configFlow) Log.d("WG", "WireGuard tunnel reloaded for new exceptions") @@ -179,6 +201,7 @@ class WireGuardHelper(context: Context) { it.suppressDownCallback = true backend.setState(it, Tunnel.State.DOWN, null) sharedTunnel = null + sharedConfigFingerprint = null Log.d("WG", "WireGuard tunnel stopped") } } catch (e: Exception) { @@ -236,3 +259,17 @@ class WireGuardHelper(context: Context) { return "config lines=${lines.size}, interface=$hasInterface, peer=$hasPeer, privateKey=$hasPrivateKey, publicKey=$hasPublicKey, address=$hasAddress, endpoint=$endpoint" } } + +internal fun shouldReuseRunningWireGuard( + tunnelUp: Boolean, + currentConfigFingerprint: String?, + updatedConfig: Config, +): Boolean = + tunnelUp && + currentConfigFingerprint != null && + currentConfigFingerprint == wireGuardConfigFingerprint(updatedConfig) + +internal fun wireGuardConfigFingerprint(config: Config): String = + MessageDigest.getInstance("SHA-256") + .digest(config.toWgQuickString().toByteArray(Charsets.UTF_8)) + .joinToString(separator = "") { byte -> "%02x".format(byte.toInt() and 0xff) } diff --git a/app/src/main/java/com/wdtt/plus/ui/CollapsingHeaderScroll.kt b/app/src/main/java/com/wdtt/plus/ui/CollapsingHeaderScroll.kt new file mode 100644 index 0000000..b232ecc --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/CollapsingHeaderScroll.kt @@ -0,0 +1,13 @@ +package com.wdtt.plus.ui + +internal fun collapsingHeaderOffsetAfterScroll( + currentOffsetPx: Float, + headerHeightPx: Float, + deltaPx: Float, + allowExpand: Boolean, +): Float { + if (headerHeightPx <= 0f || deltaPx == 0f) return currentOffsetPx + if (deltaPx > 0f && !allowExpand) return currentOffsetPx + return (currentOffsetPx + deltaPx).coerceIn(-headerHeightPx, 0f) +} + 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 6ad2e39..3820c8a 100644 --- a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt @@ -107,11 +107,20 @@ import java.util.Locale import org.json.JSONObject private const val CMD_TIMEOUT = 900000L // 15 minutes -private const val WGCF_VERSION = "2.2.31" -private const val WGCF_LINUX_AMD64_SHA256 = "69147e1a517c66129edd8ac8cb60484d6c9515178d7b4a2f95e3c925f225572a" +private const val SERVER_BACKUP_FORMAT_VERSION = 2 +private const val MAX_SERVER_BACKUP_FILE_CHARS = 8_000_000 +private const val MAX_SERVER_DATABASE_CHARS = 5_000_000 +private const val MAX_SERVER_WG_KEYS_CHARS = 4_096 +internal const val WGCF_VERSION = "2.2.32" +private const val WGCF_LINUX_AMD64_SHA256 = "2ff97f2201972ce582a424455d50a3719a380eef0cd1f3144f7779348e122a2c" private const val WGCF_LINUX_AMD64_URL = "https://github.com/ViRb3/wgcf/releases/download/v$WGCF_VERSION/wgcf_${WGCF_VERSION}_linux_amd64" private const val WGCF_LATEST_RELEASE_API = "https://api.github.com/repos/ViRb3/wgcf/releases/latest" +internal const val THREEPROXY_VERSION = "0.9.7" +private const val THREEPROXY_SOURCE_SHA256 = + "efe862ef8b7c0ddf7b1c45d6b5d72f0b7cd0a3c54447419c7f1bd2239a06fc30" +private const val THREEPROXY_SOURCE_URL = + "https://github.com/3proxy/3proxy/archive/refs/tags/$THREEPROXY_VERSION.tar.gz" private enum class DeployMode { PreserveData, @@ -123,7 +132,7 @@ private enum class ServerImportMode { Merge } -private enum class OutboundDialog { +internal enum class OutboundDialog { LocalProxy, ExternalProxy, WireGuardVps, @@ -195,6 +204,30 @@ private enum class ProxyKind(val label: String, val protocol: String) { Http("HTTP", "http") } +internal fun localProxyCredentialsIssue(login: String, password: String): String? = when { + login.isBlank() -> "Укажите логин прокси." + !login.matches(Regex("^[A-Za-z0-9._@+-]{1,40}$")) -> + "В логине допустимы латинские буквы, цифры и знаки . _ @ + -" + password.length !in 8..80 -> "Пароль должен содержать от 8 до 80 символов." + !password.matches(Regex("^[A-Za-z0-9._~!@%+?,=-]{8,80}$")) -> + "В пароле допустимы латинские буквы, цифры и знаки . _ ~ ! @ % + ? , = -" + else -> null +} + +internal fun externalProxyCredentialsIssue(login: String, password: String): String? = when { + login.isBlank() && password.isNotBlank() -> "Для пароля внешнего прокси укажите логин." + login.isNotBlank() && password.isBlank() -> "Для указанного логина внешнего прокси введите пароль." + login.length > 80 -> "Логин внешнего прокси не должен быть длиннее 80 символов." + password.length > 120 -> "Пароль внешнего прокси не должен быть длиннее 120 символов." + ':' in login -> "Логин внешнего прокси не должен содержать двоеточие." + login.any(Char::isISOControl) || password.any(Char::isISOControl) -> + "Логин и пароль внешнего прокси содержат недопустимые символы." + else -> null +} + +internal fun escapeRedsocksQuotedValue(value: String): String = + value.replace("\\", "\\\\").replace("\"", "\\\"") + private data class OutboundSshTarget( val host: String, val user: String, @@ -208,7 +241,7 @@ private data class OutboundSshTarget( get() = SshCredentials(pass, privateKey, keyPassphrase, allowPasswordAuthentication) } -private data class ServerBackup( +internal data class ServerBackup( val passwordsJson: String, val wgKeysDat: String?, val createdAt: String, @@ -218,7 +251,9 @@ private data class ServerBackup( val mainPassword: String, val adminId: String, val botToken: String, - val dns: String + val dns: String, + val formatVersion: Int = SERVER_BACKUP_FORMAT_VERSION, + val integrityVerified: Boolean = true ) { val hasWgKeys: Boolean get() = !wgKeysDat.isNullOrBlank() @@ -286,7 +321,7 @@ private data class ExistingInstallInfo( get() = serviceExists || binaryExists || configDirExists || accessDbExists || wgKeysExist } -private data class OutboundProfileForms( +internal data class OutboundProfileForms( val localProxyPort: String, val localProxyLogin: String, val localProxyPassword: String, @@ -304,7 +339,7 @@ private data class OutboundProfileForms( val importedWireGuardConfig: String ) -private data class OutboundServerSnapshot( +internal data class OutboundServerSnapshot( val mode: String, val detail: String, val updatedAt: String, @@ -332,7 +367,20 @@ private data class OutboundServerSnapshot( val warpPresent: Boolean, val warpMtu: String, val importedWireGuardConfig: String, - val checkedAtMillis: Long = System.currentTimeMillis() + val checkedAtMillis: Long = System.currentTimeMillis(), + val externalProxyServiceActive: Boolean = externalProxyActive, + val externalProxyRouteActive: Boolean = externalProxyActive, + val wireGuardInterfaceActive: Boolean = wireGuardActive, + val wireGuardServiceActive: Boolean = wireGuardActive, + val wireGuardPolicyRuleActive: Boolean = wireGuardActive, + val wireGuardDefaultRouteActive: Boolean = wireGuardActive, + val wireGuardNatActive: Boolean = wireGuardActive, + val wireGuardOwnerMode: String = "", + val wireGuardConfigOwnerMode: String = "", + val wireGuardMatchesWarp: Boolean = false, + val localProxyServiceEnabled: Boolean = localProxyActive, + val externalProxyServiceEnabled: Boolean = externalProxyServiceActive, + val wireGuardServiceEnabled: Boolean = wireGuardServiceActive ) { val modeLabel: String get() = when (mode) { @@ -355,16 +403,28 @@ private data class OutboundServerSnapshot( val activeRouteLabels: List get() = buildList { - if (externalProxyActive) add("внешний TCP-прокси") - if (wireGuardActive) add("WireGuard-выход") + if (externalProxyRouteActive) add("внешний TCP-прокси") + if (wireGuardRoutingPresent) add("WireGuard-выход") } + val externalProxyRoutingPresent: Boolean + get() = externalProxyServiceActive || externalProxyRouteActive + + val wireGuardRoutingPresent: Boolean + get() = wireGuardInterfaceActive || + wireGuardPolicyRuleActive || + wireGuardDefaultRouteActive || + wireGuardNatActive + + val wireGuardHealthy: Boolean + get() = wireGuardActive && wireGuardServiceActive && wireGuardServiceEnabled + val hasRouteConflict: Boolean - get() = externalProxyActive && wireGuardActive + get() = externalProxyRouteActive && wireGuardRoutingPresent val routeConflictMessage: String? get() = if (hasRouteConflict) { - "На сервере одновременно активны внешний TCP-прокси и WireGuard-выход. Так можно сломать выход клиентов; сначала верните прямой выход или выполните диагностику/очистку." + "На сервере одновременно остались правила внешнего TCP-прокси и WireGuard-выхода. Это может нарушить интернет у клиентов; нажмите «Вернуть прямой выход», затем включите только один режим." } else { null } @@ -387,7 +447,7 @@ private object OutboundProcessCache { } } -private enum class OutboundModeVisualState { +internal enum class OutboundModeVisualState { Unknown, Off, Active, @@ -395,21 +455,45 @@ private enum class OutboundModeVisualState { Error } -private data class OutboundModeIndicator( +internal data class OutboundModeIndicator( val state: OutboundModeVisualState, val text: String ) private val wireGuardOutboundModes = setOf("wireguard_vps", "warp_free", "imported_wg") -private fun outboundModeIndicator(snapshot: OutboundServerSnapshot?, dialog: OutboundDialog): OutboundModeIndicator { +private fun OutboundServerSnapshot.orphanedWireGuardDialog(): OutboundDialog? { + if (!wireGuardRoutingPresent || mode in wireGuardOutboundModes) return null + return when { + wireGuardOwnerMode == "warp_free" -> OutboundDialog.FreeWarp + wireGuardOwnerMode == "imported_wg" -> OutboundDialog.ImportedWireGuard + wireGuardOwnerMode == "wireguard_vps" -> OutboundDialog.WireGuardVps + wireGuardConfigOwnerMode == "warp_free" -> OutboundDialog.FreeWarp + wireGuardConfigOwnerMode == "imported_wg" -> OutboundDialog.ImportedWireGuard + wireGuardConfigOwnerMode == "wireguard_vps" -> OutboundDialog.WireGuardVps + wireGuardMatchesWarp -> OutboundDialog.FreeWarp + importedWireGuardConfig.isNotBlank() && wireGuardExitHost.isBlank() -> + OutboundDialog.ImportedWireGuard + wireGuardExitHost.isNotBlank() -> OutboundDialog.WireGuardVps + warpPresent -> OutboundDialog.FreeWarp + else -> null + } +} + +internal fun outboundModeIndicator( + snapshot: OutboundServerSnapshot?, + dialog: OutboundDialog +): OutboundModeIndicator { if (snapshot == null) { return OutboundModeIndicator(OutboundModeVisualState.Unknown, "не проверено") } if (dialog == OutboundDialog.LocalProxy) { return when { - snapshot.localProxyActive -> OutboundModeIndicator(OutboundModeVisualState.Active, "запущен") + snapshot.localProxyActive && snapshot.localProxyServiceEnabled -> + OutboundModeIndicator(OutboundModeVisualState.Active, "запущен") + snapshot.localProxyActive -> + OutboundModeIndicator(OutboundModeVisualState.Warning, "без автозапуска") snapshot.localProxyPresent -> OutboundModeIndicator(OutboundModeVisualState.Warning, "найден") else -> OutboundModeIndicator(OutboundModeVisualState.Off, "выключен") } @@ -417,10 +501,17 @@ private fun outboundModeIndicator(snapshot: OutboundServerSnapshot?, dialog: Out if (dialog == OutboundDialog.ExternalProxy) { return when { - snapshot.hasRouteConflict && snapshot.externalProxyActive -> OutboundModeIndicator(OutboundModeVisualState.Error, "конфликт") - snapshot.mode == "external_proxy" && snapshot.externalProxyActive -> OutboundModeIndicator(OutboundModeVisualState.Active, "активен") + snapshot.hasRouteConflict && snapshot.externalProxyRouteActive -> OutboundModeIndicator(OutboundModeVisualState.Error, "конфликт") + snapshot.mode == "external_proxy" && + snapshot.externalProxyActive && + snapshot.externalProxyServiceEnabled -> + OutboundModeIndicator(OutboundModeVisualState.Active, "активен") + snapshot.mode == "external_proxy" && snapshot.externalProxyActive -> + OutboundModeIndicator(OutboundModeVisualState.Warning, "без автозапуска") + snapshot.mode == "external_proxy" && snapshot.externalProxyRoutingPresent -> + OutboundModeIndicator(OutboundModeVisualState.Error, "запущен частично") snapshot.mode == "external_proxy" -> OutboundModeIndicator(OutboundModeVisualState.Error, "не запущен") - snapshot.externalProxyActive -> OutboundModeIndicator(OutboundModeVisualState.Warning, "активен вне режима") + snapshot.externalProxyRoutingPresent -> OutboundModeIndicator(OutboundModeVisualState.Warning, "остались правила") snapshot.externalProxyPresent -> OutboundModeIndicator(OutboundModeVisualState.Warning, "настроен") else -> OutboundModeIndicator(OutboundModeVisualState.Off, "выключен") } @@ -428,8 +519,14 @@ private fun outboundModeIndicator(snapshot: OutboundServerSnapshot?, dialog: Out if (dialog == OutboundDialog.FreeWarp) { return when { - snapshot.hasRouteConflict && snapshot.wireGuardActive && snapshot.mode == "warp_free" -> OutboundModeIndicator(OutboundModeVisualState.Error, "конфликт") - snapshot.mode == "warp_free" && snapshot.wireGuardActive -> OutboundModeIndicator(OutboundModeVisualState.Active, "активен") + snapshot.hasRouteConflict && snapshot.wireGuardRoutingPresent && snapshot.mode == "warp_free" -> OutboundModeIndicator(OutboundModeVisualState.Error, "конфликт") + snapshot.mode == "warp_free" && snapshot.wireGuardHealthy -> OutboundModeIndicator(OutboundModeVisualState.Active, "активен") + snapshot.mode == "warp_free" && snapshot.wireGuardActive -> + OutboundModeIndicator(OutboundModeVisualState.Warning, "без автозапуска") + snapshot.mode == "warp_free" && snapshot.wireGuardRoutingPresent -> + OutboundModeIndicator(OutboundModeVisualState.Error, "запущен частично") + snapshot.orphanedWireGuardDialog() == OutboundDialog.FreeWarp -> + OutboundModeIndicator(OutboundModeVisualState.Error, "не отключён") snapshot.mode == "warp_free" && snapshot.warpPresent -> OutboundModeIndicator(OutboundModeVisualState.Error, "не запущен") snapshot.warpPresent -> OutboundModeIndicator(OutboundModeVisualState.Warning, "настроен") else -> OutboundModeIndicator(OutboundModeVisualState.Off, "выключен") @@ -443,11 +540,16 @@ private fun outboundModeIndicator(snapshot: OutboundServerSnapshot?, dialog: Out } if (expectedMode.isNotBlank()) { return when { - snapshot.hasRouteConflict && snapshot.wireGuardActive -> OutboundModeIndicator(OutboundModeVisualState.Error, "конфликт") - snapshot.mode == expectedMode && snapshot.wireGuardActive -> OutboundModeIndicator(OutboundModeVisualState.Active, "активен") + snapshot.hasRouteConflict && snapshot.wireGuardRoutingPresent -> OutboundModeIndicator(OutboundModeVisualState.Error, "конфликт") + snapshot.mode == expectedMode && snapshot.wireGuardHealthy -> OutboundModeIndicator(OutboundModeVisualState.Active, "активен") + snapshot.mode == expectedMode && snapshot.wireGuardActive -> + OutboundModeIndicator(OutboundModeVisualState.Warning, "без автозапуска") + snapshot.mode == expectedMode && snapshot.wireGuardRoutingPresent -> + OutboundModeIndicator(OutboundModeVisualState.Error, "запущен частично") snapshot.mode == expectedMode && snapshot.wireGuardPresent -> OutboundModeIndicator(OutboundModeVisualState.Error, "не запущен") snapshot.mode == expectedMode -> OutboundModeIndicator(OutboundModeVisualState.Error, "нет конфига") - snapshot.wireGuardActive && snapshot.mode !in wireGuardOutboundModes -> OutboundModeIndicator(OutboundModeVisualState.Warning, "WG активен") + snapshot.orphanedWireGuardDialog() == dialog -> + OutboundModeIndicator(OutboundModeVisualState.Error, "не отключён") else -> OutboundModeIndicator(OutboundModeVisualState.Off, "выключен") } } @@ -457,16 +559,26 @@ private fun outboundModeIndicator(snapshot: OutboundServerSnapshot?, dialog: Out private fun OutboundServerSnapshot.outboundModeMismatchWarning(): String? = when { routeConflictMessage != null -> routeConflictMessage - mode == "direct" && activeRouteLabels.isNotEmpty() -> - "в профиле указан прямой выход, но на сервере активен ${activeRouteLabels.joinToString(" и ")}." + mode == "direct" && (externalProxyRoutingPresent || wireGuardRoutingPresent) -> + "записан прямой выход, но на сервере остались внешние службы или правила маршрутизации. Нажмите «Вернуть прямой выход» для полной очистки." + mode == "external_proxy" && externalProxyServiceActive && !externalProxyRouteActive -> + "служба внешнего TCP-прокси запущена, но правило перенаправления трафика WDTT отсутствует." + mode == "external_proxy" && !externalProxyServiceActive && externalProxyRouteActive -> + "правило внешнего TCP-прокси осталось, но его служба не запущена; TCP-трафик клиентов может не работать." + mode == "external_proxy" && externalProxyActive && !externalProxyServiceEnabled -> + "внешний TCP-прокси работает, но его автозапуск выключен; после перезагрузки сервера режим пропадёт." mode == "external_proxy" && !externalProxyActive -> - "режим записан как внешний TCP-прокси, но служба маршрутизации через прокси не запущена." + "режим записан как внешний TCP-прокси, но он запущен не полностью." + mode in wireGuardOutboundModes && wireGuardActive && !wireGuardServiceActive -> + "WireGuard-маршрут работает, но постоянная служба не активна; после перезагрузки сервера режим может пропасть." + mode in wireGuardOutboundModes && wireGuardActive && !wireGuardServiceEnabled -> + "WireGuard-маршрут работает, но автозапуск службы выключен; после перезагрузки сервера режим пропадёт." mode in wireGuardOutboundModes && !wireGuardActive -> - "режим записан как ${modeLabel}, но WireGuard-выход не запущен." - externalProxyActive && mode != "external_proxy" -> - "внешний TCP-прокси запущен, но профиль режима указывает «${modeLabel}»." - wireGuardActive && mode !in wireGuardOutboundModes -> - "WireGuard-выход запущен, но профиль режима указывает «${modeLabel}»." + "режим записан как ${modeLabel}, но не все компоненты WireGuard-маршрута запущены." + externalProxyRoutingPresent && mode != "external_proxy" -> + "на сервере остались компоненты внешнего TCP-прокси, хотя записан режим «${modeLabel}»." + wireGuardRoutingPresent && mode !in wireGuardOutboundModes -> + "на сервере остались компоненты WireGuard-выхода, хотя записан режим «${modeLabel}»." else -> null } @@ -474,6 +586,9 @@ private fun outboundServerShortState(snapshot: OutboundServerSnapshot): String = snapshot.hasRouteConflict -> "конфликт — ${snapshot.activeRouteLabels.joinToString(" и ")}" snapshot.externalProxyActive -> "внешний TCP-прокси" snapshot.wireGuardActive -> snapshot.modeLabel.takeIf { snapshot.mode in wireGuardOutboundModes } ?: "WireGuard-выход" + snapshot.externalProxyRoutingPresent -> "внешний TCP-прокси запущен частично" + snapshot.wireGuardRoutingPresent -> "WireGuard-выход запущен частично" + snapshot.mode != "direct" -> "${snapshot.modeLabel} не запущен" else -> "прямой выход" } @@ -491,7 +606,10 @@ private fun outboundServerStateHint(snapshot: OutboundServerSnapshot): String { return buildString { append("Конфликтных режимов не найдено.") if (snapshot.localProxyActive) { - append(" Прокси VPS запущен отдельно и не переключает выход WDTT-клиентов.") + append(" Прокси на этом VPS запущен отдельно и не переключает выход WDTT-клиентов.") + if (!snapshot.localProxyServiceEnabled) { + append(" Его автозапуск выключен.") + } } if (checkedAt.isNotBlank()) { append(" Проверено: $checkedAt.") @@ -508,9 +626,13 @@ private fun outboundServerStateSummary(snapshot: OutboundServerSnapshot): String snapshot.routeConflictMessage?.let { parts += it } snapshot.outboundModeMismatchWarning()?.takeIf { it != snapshot.routeConflictMessage }?.let { parts += it } if (snapshot.localProxyActive) { - parts += "Прокси VPS запущен отдельно; он не конфликтует с маршрутизацией выхода WDTT." + parts += if (snapshot.localProxyServiceEnabled) { + "Прокси на этом VPS запущен отдельно; он не конфликтует с маршрутизацией выхода WDTT." + } else { + "Прокси на этом VPS работает, но его автозапуск выключен." + } } else if (snapshot.localProxyPresent) { - parts += "Прокси VPS найден, но служба не запущена." + parts += "Прокси на этом VPS найден, но служба не запущена." } formatOutboundCheckTime(snapshot.checkedAtMillis).takeIf { it.isNotBlank() }?.let { parts += "Состояние проверено: $it." @@ -521,16 +643,30 @@ private fun outboundServerStateSummary(snapshot: OutboundServerSnapshot): String return parts.joinToString(" ") } -private fun canReturnDirect(snapshot: OutboundServerSnapshot?): Boolean = - snapshot != null && (snapshot.mode != "direct" || snapshot.externalProxyActive || snapshot.wireGuardActive) +internal fun canReturnDirect(snapshot: OutboundServerSnapshot?): Boolean = + snapshot != null && ( + snapshot.mode != "direct" || + snapshot.externalProxyRoutingPresent || + snapshot.wireGuardRoutingPresent + ) -private fun canDisableOutboundDialog(snapshot: OutboundServerSnapshot?, dialog: OutboundDialog): Boolean { +internal fun canDisableOutboundDialog( + snapshot: OutboundServerSnapshot?, + dialog: OutboundDialog +): Boolean { if (snapshot == null) return false return when (dialog) { - OutboundDialog.ExternalProxy -> snapshot.externalProxyActive - OutboundDialog.WireGuardVps -> snapshot.mode == "wireguard_vps" && snapshot.wireGuardActive - OutboundDialog.FreeWarp -> snapshot.mode == "warp_free" && snapshot.wireGuardActive - OutboundDialog.ImportedWireGuard -> snapshot.mode == "imported_wg" && snapshot.wireGuardActive + OutboundDialog.ExternalProxy -> + snapshot.mode == "external_proxy" || snapshot.externalProxyRoutingPresent + OutboundDialog.WireGuardVps -> + snapshot.mode == "wireguard_vps" || + snapshot.orphanedWireGuardDialog() == OutboundDialog.WireGuardVps + OutboundDialog.FreeWarp -> + snapshot.mode == "warp_free" || + snapshot.orphanedWireGuardDialog() == OutboundDialog.FreeWarp + OutboundDialog.ImportedWireGuard -> + snapshot.mode == "imported_wg" || + snapshot.orphanedWireGuardDialog() == OutboundDialog.ImportedWireGuard else -> false } } @@ -552,7 +688,22 @@ private fun canDeleteFreeWarp(snapshot: OutboundServerSnapshot?): Boolean = snapshot?.warpPresent == true private fun canDeleteImportedWireGuard(snapshot: OutboundServerSnapshot?): Boolean = - snapshot != null && (snapshot.mode == "imported_wg" || snapshot.importedWireGuardConfig.isNotBlank()) + snapshot != null && ( + snapshot.mode == "imported_wg" || + snapshot.wireGuardConfigOwnerMode == "imported_wg" || + snapshot.importedWireGuardConfig.isNotBlank() + ) + +private fun canDeleteExternalProxy(snapshot: OutboundServerSnapshot?): Boolean = + snapshot?.externalProxyPresent == true + +private fun canDeleteWireGuardVps(snapshot: OutboundServerSnapshot?): Boolean = + snapshot != null && ( + snapshot.mode == "wireguard_vps" || + snapshot.wireGuardOwnerMode == "wireguard_vps" || + snapshot.wireGuardConfigOwnerMode == "wireguard_vps" || + snapshot.wireGuardExitHost.isNotBlank() + ) private fun canStopLocalProxy(snapshot: OutboundServerSnapshot?): Boolean = snapshot?.localProxyActive == true @@ -564,7 +715,7 @@ private fun outboundDialogServerStateSummary(snapshot: OutboundServerSnapshot, d val indicator = outboundModeIndicator(snapshot, dialog) val checkedAt = formatOutboundCheckTime(snapshot.checkedAtMillis) val prefix = when (dialog) { - OutboundDialog.LocalProxy -> "Прокси VPS" + OutboundDialog.LocalProxy -> "Прокси на этом VPS" OutboundDialog.ExternalProxy -> "Внешний TCP-прокси" OutboundDialog.WireGuardVps -> "Выход через другой сервер" OutboundDialog.FreeWarp -> "Бесплатный WARP" @@ -574,28 +725,46 @@ private fun outboundDialogServerStateSummary(snapshot: OutboundServerSnapshot, d val parts = mutableListOf("$prefix: ${indicator.text}.") when (dialog) { OutboundDialog.LocalProxy -> when { - snapshot.localProxyActive -> parts += "Служба прокси на сервере запущена." + snapshot.localProxyActive && snapshot.localProxyServiceEnabled -> + parts += "Служба прокси на сервере запущена и включена в автозапуск." + snapshot.localProxyActive -> + parts += "Служба прокси запущена, но её автозапуск выключен." snapshot.localProxyPresent -> parts += "Настройки прокси найдены, но служба сейчас не запущена." else -> parts += "Настройки прокси на сервере не найдены." } OutboundDialog.ExternalProxy -> when { snapshot.externalProxyActive -> parts += "Маршрутизация обычного TCP-трафика WDTT через внешний прокси включена." + snapshot.externalProxyRoutingPresent -> parts += + "Служба или правило внешнего прокси запущены не полностью. Нажмите «Отключить» для очистки либо включите режим заново." snapshot.externalProxyPresent -> parts += "Настройки внешнего прокси найдены, но маршрутизация сейчас не активна." else -> parts += "Внешний TCP-прокси на сервере не настроен." } OutboundDialog.WireGuardVps -> when { - snapshot.mode == "wireguard_vps" && snapshot.wireGuardActive -> parts += "WireGuard-выход через другой сервер активен." + snapshot.mode == "wireguard_vps" && snapshot.wireGuardHealthy -> parts += "WireGuard-выход через другой сервер активен." + snapshot.mode == "wireguard_vps" && snapshot.wireGuardActive -> parts += + "Маршрут через другой сервер работает, но постоянная служба не активна." + snapshot.mode == "wireguard_vps" && snapshot.wireGuardRoutingPresent -> parts += + "WireGuard-выход через другой сервер запущен не полностью." snapshot.mode == "wireguard_vps" && snapshot.wireGuardPresent -> parts += "Конфиг выхода через другой сервер найден, но WireGuard сейчас не запущен." snapshot.wireGuardExitHost.isNotBlank() || snapshot.wireGuardExitPort.isNotBlank() -> parts += "Сохранённые поля второго сервера найдены; нажмите «Настроить выход», чтобы включить режим." else -> parts += "Настройки выхода через другой сервер на сервере не найдены." } OutboundDialog.FreeWarp -> when { - snapshot.mode == "warp_free" && snapshot.wireGuardActive -> parts += "WARP активен; можно выполнить глубокую проверку Cloudflare." + snapshot.mode == "warp_free" && snapshot.wireGuardHealthy -> parts += "WARP активен; можно выполнить глубокую проверку Cloudflare." + snapshot.mode == "warp_free" && snapshot.wireGuardActive -> parts += + "WARP-маршрут работает, но постоянная служба не активна." + snapshot.mode == "warp_free" && snapshot.wireGuardRoutingPresent -> parts += + "WARP запущен не полностью. Нажмите «Отключить» для очистки либо выполните восстановление." + snapshot.orphanedWireGuardDialog() == OutboundDialog.FreeWarp -> parts += "После неудачного включения WARP его общий WireGuard-интерфейс остался запущен. Нажмите «Отключить», чтобы принудительно вернуть прямой выход; регистрация WARP сохранится." snapshot.warpPresent -> parts += "Регистрация или профиль WARP найдены, но WARP сейчас не активен. Нажмите «Установить / восстановить», чтобы включить его без новой регистрации, если сохранённый аккаунт рабочий." else -> parts += "Регистрация WARP на сервере не найдена." } OutboundDialog.ImportedWireGuard -> when { - snapshot.mode == "imported_wg" && snapshot.wireGuardActive -> parts += "Импортированный VPN/WireGuard-файл активен." + snapshot.mode == "imported_wg" && snapshot.wireGuardHealthy -> parts += "Импортированный VPN/WireGuard-файл активен." + snapshot.mode == "imported_wg" && snapshot.wireGuardActive -> parts += + "Маршрут из VPN/WireGuard-файла работает, но постоянная служба не активна." + snapshot.mode == "imported_wg" && snapshot.wireGuardRoutingPresent -> parts += + "VPN/WireGuard-выход запущен не полностью." snapshot.importedWireGuardConfig.isNotBlank() -> parts += "Сохранённый VPN/WireGuard-файл найден, но сейчас не активен. Нажмите «Включить», чтобы применить его." snapshot.mode == "imported_wg" && snapshot.wireGuardPresent -> parts += "Рабочий WireGuard-конфиг найден, но интерфейс сейчас не запущен." else -> parts += "Импортированный VPN/WireGuard-файл на сервере не найден." @@ -683,7 +852,7 @@ fun DeployTab( val savedConnectionPassword by settingsStore.connectionPassword.collectAsStateWithLifecycle(initialValue = "") val savedVkHashes by settingsStore.vkHashes.collectAsStateWithLifecycle(initialValue = "") val savedSecondaryVkHash by settingsStore.secondaryVkHash.collectAsStateWithLifecycle(initialValue = "") - val savedWorkersPerHash by settingsStore.workersPerHash.collectAsStateWithLifecycle(initialValue = 16) + val savedWorkersPerHash by settingsStore.workersPerHash.collectAsStateWithLifecycle(initialValue = 18) val savedProtocol by settingsStore.protocol.collectAsStateWithLifecycle(initialValue = "udp") val savedSni by settingsStore.sni.collectAsStateWithLifecycle(initialValue = "") val savedNoDns by settingsStore.noDns.collectAsStateWithLifecycle(initialValue = false) @@ -753,29 +922,64 @@ fun DeployTab( var outboundLastCheckAttemptAt by remember { mutableLongStateOf(0L) } var outboundLastCheckError by remember { mutableStateOf("") } var outboundAutoCheckedTargetKey by remember { mutableStateOf("") } - var importedWgConfigText by rememberSaveable { mutableStateOf("") } - val outboundPrefs = remember { context.getSharedPreferences("wdtt_outbound_forms", Context.MODE_PRIVATE) } - var localProxyPortInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("local_proxy_port", "1080") ?: "1080") } - var localProxyLoginInput by rememberSaveable { - mutableStateOf(outboundPrefs.getString("local_proxy_login", "")?.takeIf { it.isNotBlank() } ?: "wdtt_${randomToken(5).lowercase()}") + val outboundFormsStore = remember { OutboundFormsStore(context) } + val storedOutboundForms = remember(activeProfile) { + outboundFormsStore.load(activeProfile) } - var localProxyPasswordInput by rememberSaveable { - mutableStateOf(outboundPrefs.getString("local_proxy_password", "")?.takeIf { it.isNotBlank() } ?: randomToken(18)) + var importedWgConfigText by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.importedWireGuardConfig) } - var externalProxyKindName by rememberSaveable { - mutableStateOf(outboundPrefs.getString("external_proxy_kind", ProxyKind.Socks5.name) ?: ProxyKind.Socks5.name) + var localProxyPortInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.localProxyPort) + } + var localProxyLoginInput by rememberSaveable(activeProfile) { + mutableStateOf( + storedOutboundForms.forms.localProxyLogin.takeIf(String::isNotBlank) + ?: "wdtt_${randomToken(5).lowercase()}" + ) + } + var localProxyPasswordInput by rememberSaveable(activeProfile) { + mutableStateOf( + storedOutboundForms.forms.localProxyPassword.takeIf(String::isNotBlank) + ?: randomToken(18) + ) + } + var externalProxyKindName by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.externalProxyKindName) + } + var externalProxyHostInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.externalProxyHost) + } + var externalProxyPortInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.externalProxyPort) + } + var externalProxyLoginInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.externalProxyLogin) + } + var externalProxyPasswordInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.externalProxyPassword) + } + var wireGuardExitHostInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.wireGuardExitHost) + } + var wireGuardExitSshPortInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.wireGuardExitSshPort) + } + var wireGuardExitUserInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.wireGuardExitUser) + } + var wireGuardExitPasswordInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.wireGuardExitPassword) + } + var wireGuardExitPortInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.wireGuardExitPort) + } + var wireGuardExitDnsInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.forms.wireGuardExitDns) + } + var freeWarpMtuInput by rememberSaveable(activeProfile) { + mutableStateOf(storedOutboundForms.warpMtu) } - var externalProxyHostInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("external_proxy_host", "") ?: "") } - var externalProxyPortInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("external_proxy_port", "1080") ?: "1080") } - var externalProxyLoginInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("external_proxy_login", "") ?: "") } - var externalProxyPasswordInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("external_proxy_password", "") ?: "") } - var wireGuardExitHostInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("wg_exit_host", "") ?: "") } - var wireGuardExitSshPortInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("wg_exit_ssh_port", "22") ?: "22") } - var wireGuardExitUserInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("wg_exit_user", "root") ?: "root") } - var wireGuardExitPasswordInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("wg_exit_password", "") ?: "") } - var wireGuardExitPortInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("wg_exit_port", "51820") ?: "51820") } - var wireGuardExitDnsInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("wg_exit_dns", "1.1.1.1,8.8.8.8") ?: "1.1.1.1,8.8.8.8") } - var freeWarpMtuInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("warp_mtu", "1280") ?: "1280") } var showSuccessBanner by rememberSaveable { mutableStateOf(false) } var successCountdown by rememberSaveable { mutableIntStateOf(5) } @@ -794,6 +998,7 @@ fun DeployTab( val deployProgress by DeployManager.deployProgress.collectAsStateWithLifecycle() val currentStep by DeployManager.currentStep.collectAsStateWithLifecycle() val lastDeployResult by DeployManager.lastResult.collectAsStateWithLifecycle() + val installedServerVersion by DeployManager.installedServerVersion.collectAsStateWithLifecycle() LaunchedEffect(savedIp) { ip = savedIp } LaunchedEffect(savedLogin) { login = savedLogin } @@ -890,6 +1095,7 @@ fun DeployTab( serverDiagnosticsReport = null } LaunchedEffect( + activeProfile, localProxyPortInput, localProxyLoginInput, localProxyPasswordInput, @@ -905,25 +1111,31 @@ fun DeployTab( selectedWireGuardExitSshAuthMode, wireGuardExitPortInput, wireGuardExitDnsInput, - freeWarpMtuInput + freeWarpMtuInput, + importedWgConfigText, ) { - outboundPrefs.edit() - .putString("local_proxy_port", localProxyPortInput) - .putString("local_proxy_login", localProxyLoginInput) - .putString("local_proxy_password", localProxyPasswordInput) - .putString("external_proxy_kind", externalProxyKindName) - .putString("external_proxy_host", externalProxyHostInput) - .putString("external_proxy_port", externalProxyPortInput) - .putString("external_proxy_login", externalProxyLoginInput) - .putString("external_proxy_password", externalProxyPasswordInput) - .putString("wg_exit_host", wireGuardExitHostInput) - .putString("wg_exit_ssh_port", wireGuardExitSshPortInput) - .putString("wg_exit_user", wireGuardExitUserInput) - .putString("wg_exit_password", wireGuardExitPasswordInput) - .putString("wg_exit_port", wireGuardExitPortInput) - .putString("wg_exit_dns", wireGuardExitDnsInput) - .putString("warp_mtu", freeWarpMtuInput) - .apply() + kotlinx.coroutines.delay(250) + outboundFormsStore.save( + activeProfile, + OutboundProfileForms( + localProxyPort = localProxyPortInput, + localProxyLogin = localProxyLoginInput, + localProxyPassword = localProxyPasswordInput, + externalProxyKindName = externalProxyKindName, + externalProxyHost = externalProxyHostInput, + externalProxyPort = externalProxyPortInput, + externalProxyLogin = externalProxyLoginInput, + externalProxyPassword = externalProxyPasswordInput, + wireGuardExitHost = wireGuardExitHostInput, + wireGuardExitSshPort = wireGuardExitSshPortInput, + wireGuardExitUser = wireGuardExitUserInput, + wireGuardExitPassword = wireGuardExitPasswordInput, + wireGuardExitPort = wireGuardExitPortInput, + wireGuardExitDns = wireGuardExitDnsInput, + importedWireGuardConfig = importedWgConfigText, + ), + freeWarpMtuInput, + ) } val animatedProgress by animateFloatAsState( targetValue = deployProgress, @@ -952,7 +1164,7 @@ fun DeployTab( scope.launch { try { writeServerBackupToUri(context, uri, backup) - migrationStatus = "${if (backup.hasWgKeys) "Полный" else "Частичный"} экспорт готов: паролей ${backup.passwordCount}, устройств ${backup.deviceCount}." + migrationStatus = "${if (backup.hasWgKeys) "Полный" else "Частичный"} экспорт готов: клиентов ${backup.passwordCount}, устройств ${backup.deviceCount}." } catch (e: Exception) { migrationStatus = "Ошибка экспорта: ${friendlyDeployError(e, "экспорт")}" DeployManager.writeError("Server export error: ${e.message}") @@ -972,7 +1184,16 @@ fun DeployTab( val backup = loadServerBackupFromUri(context, uri) selectedImportBackup = backup selectedImportModeName = ServerImportMode.Replace.name - migrationStatus = "Выбран ${if (backup.hasWgKeys) "полный" else "частичный"} бэкап: паролей ${backup.passwordCount}, устройств ${backup.deviceCount}." + migrationStatus = buildString { + append("Выбран ${if (backup.hasWgKeys) "полный" else "частичный"} бэкап: клиентов ${backup.passwordCount}, устройств ${backup.deviceCount}.") + append( + if (backup.integrityVerified) { + " Целостность файла проверена." + } else { + " Это совместимый старый формат без контрольной суммы." + } + ) + } } catch (e: Exception) { selectedImportBackup = null migrationStatus = "Ошибка файла импорта: ${friendlyDeployError(e, "файл импорта")}" @@ -1357,6 +1578,7 @@ fun DeployTab( fun runOutboundAction( title: String, preflightRouteMode: String? = null, + onSuccess: (() -> Unit)? = null, action: suspend (OutboundSshTarget) -> String ) { val owner = outboundDialog?.name @@ -1397,10 +1619,13 @@ fun DeployTab( afterWarning?.let { "Проверьте сервер: $it" } ).joinToString("\n") outboundStatusOwner = owner + onSuccess?.invoke() } catch (e: Exception) { - outboundStatus = "$title: ${friendlyDeployError(e, "выходной IP")}" + val friendly = friendlyDeployError(e, "выходной IP") + outboundStatus = "$title: $friendly" outboundStatusOwner = owner - DeployManager.writeError("Outbound action failed: ${e.message}") + DeployManager.writeError("Ошибка действия «$title»: $friendly") + TunnelManager.addDeployErrorLog("$title: $friendly") } finally { outboundBusy = false outboundSnapshotBusy = false @@ -1739,7 +1964,10 @@ fun DeployTab( scope.launch { settingsStore.saveDeploySshAuthMode(mode) } }, shape = SegmentedButtonDefaults.itemShape(index, 2), - enabled = !isDeploying + enabled = !isDeploying, + icon = { + StableSegmentedButtonIcon(selected = selectedSshAuthMode == mode) + }, ) { Text(label) } } } @@ -1944,7 +2172,10 @@ fun DeployTab( } if (showSuccessBanner) { - DeploySuccessBanner(successCountdown = successCountdown) + DeploySuccessBanner( + successCountdown = successCountdown, + serverVersion = installedServerVersion + ) } } @@ -1959,7 +2190,7 @@ fun DeployTab( color = MaterialTheme.colorScheme.onSurface ) Text( - "Подключение без установки работает только в направлении сервер → приложение: WDTT Plus проверяет главный пароль, показывает отличия и после подтверждения заполняет локальные поля. На сервер ничего не записывается, пользовательские доступы не меняются.\n\nНаправление приложение → сервер используется при установке с сохранением данных или с нуля. Настройки выходного IP восстанавливаются отдельно кнопкой «Заполнить» в соответствующем блоке.", + "Подключение без установки работает только в направлении сервер → приложение: WDTT Plus проверяет главный пароль, показывает отличия и после подтверждения заполняет локальные поля. На сервер ничего не записывается, пользовательские доступы не меняются.\n\nНаправление приложение → сервер используется при установке с сохранением данных или с нуля. Настройки выходного IP восстанавливаются отдельно кнопкой «Загрузить настройки» в соответствующем блоке.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) @@ -2217,7 +2448,14 @@ fun DeployTab( runOutboundAction("Останавливаю прокси на этом сервере") { stopLocalProxy(it) } }, onRemove = { - runOutboundAction("Удаляю прокси с этого сервера") { removeLocalProxy(it) } + runOutboundAction( + title = "Удаляю прокси с этого сервера", + onSuccess = { + localProxyPortInput = "" + localProxyLoginInput = "" + localProxyPasswordInput = "" + } + ) { removeLocalProxy(it) } } ) OutboundDialog.ExternalProxy -> ExternalProxyDialog( @@ -2233,6 +2471,7 @@ fun DeployTab( loginInput = externalProxyLoginInput, passwordInput = externalProxyPasswordInput, disableEnabled = canDisableOutboundDialog(outboundSnapshot, OutboundDialog.ExternalProxy), + deleteEnabled = canDeleteExternalProxy(outboundSnapshot), onKindChanged = { externalProxyKindName = it.name }, onHostChanged = { externalProxyHostInput = it }, onPortChanged = { externalProxyPortInput = it }, @@ -2260,6 +2499,18 @@ fun DeployTab( }, onDisable = { runOutboundAction("Возвращаю прямой выход WDTT") { disableOutboundExit(it) } + }, + onDelete = { + runOutboundAction( + title = "Удаляю настройки внешнего TCP-прокси", + onSuccess = { + externalProxyKindName = ProxyKind.Socks5.name + externalProxyHostInput = "" + externalProxyPortInput = "" + externalProxyLoginInput = "" + externalProxyPasswordInput = "" + } + ) { deleteExternalProxy(it) } } ) OutboundDialog.WireGuardVps -> WireGuardExitVpsDialog( @@ -2277,9 +2528,9 @@ fun DeployTab( privateKeyConfigured = savedWireGuardExitSshPrivateKey.isNotBlank(), hasSshAuthentication = wireGuardExitSshCredentials.hasAuthentication, wgPortInput = wireGuardExitPortInput, - dnsInput = wireGuardExitDnsInput, disableEnabled = canDisableOutboundDialog(outboundSnapshot, OutboundDialog.WireGuardVps), checkEnabled = true, + deleteEnabled = canDeleteWireGuardVps(outboundSnapshot), onHostChanged = { wireGuardExitHostInput = it }, onSshPortChanged = { wireGuardExitSshPortInput = it }, onUserChanged = { wireGuardExitUserInput = it }, @@ -2291,16 +2542,14 @@ fun DeployTab( onEditSshKey = { showWireGuardExitSshKeyDialog = true }, onSshHelp = { showWireGuardExitSshHelp = true }, onWgPortChanged = { wireGuardExitPortInput = it }, - onDnsChanged = { wireGuardExitDnsInput = it }, onDismiss = { outboundDialog = null }, - onInstall = { foreignHost, foreignPort, foreignUser, foreignPassword, wgPort, dns -> + onInstall = { foreignHost, foreignPort, foreignUser, foreignPassword, wgPort -> val forms = currentOutboundProfileForms().copy( wireGuardExitHost = foreignHost, wireGuardExitSshPort = foreignPort.toString(), wireGuardExitUser = foreignUser, wireGuardExitPassword = foreignPassword, - wireGuardExitPort = wgPort.toString(), - wireGuardExitDns = dns + wireGuardExitPort = wgPort.toString() ) runOutboundAction("Настраиваю WireGuard-выход через другой сервер", preflightRouteMode = "wireguard_vps") { val result = installWireGuardExitVps( @@ -2310,8 +2559,7 @@ fun DeployTab( foreignPort = foreignPort, foreignUser = foreignUser, foreignCredentials = wireGuardExitSshCredentials, - wgPort = wgPort, - dns = dns + wgPort = wgPort ) val saveMessage = saveOutboundProfileMessage(context, it, forms, "Поля выхода через другой сервер сохранены на сервере для восстановления.") "$result\n$saveMessage" @@ -2330,6 +2578,35 @@ fun DeployTab( }, onDisable = { runOutboundAction("Возвращаю прямой выход WDTT") { disableOutboundExit(it) } + }, + onDelete = { + val foreignHost = wireGuardExitHostInput.trim() + val foreignPort = wireGuardExitSshPortInput.toIntOrNull() ?: 0 + val foreignUser = wireGuardExitUserInput.trim() + runOutboundAction( + title = "Удаляю выход через другой сервер", + onSuccess = { + wireGuardExitHostInput = "" + wireGuardExitSshPortInput = "" + wireGuardExitUserInput = "" + wireGuardExitPasswordInput = "" + wireGuardExitPortInput = "" + wireGuardExitDnsInput = "" + scope.launch { + settingsStore.saveWireGuardExitSshKey("", "") + settingsStore.saveWireGuardExitSshAuthMode("password") + } + wireGuardExitSshAuthMode = "password" + } + ) { + deleteWireGuardExitVps( + current = it, + foreignHost = foreignHost, + foreignPort = foreignPort, + foreignUser = foreignUser, + foreignCredentials = wireGuardExitSshCredentials + ) + } } ) OutboundDialog.FreeWarp -> FreeWarpDialog( @@ -2429,8 +2706,10 @@ fun DeployTab( } }, onDelete = { - importedWgConfigText = "" - runOutboundAction("Удаляю VPN/WireGuard-файл и возвращаю прямой выход") { deleteImportedWireGuardExit(it) } + runOutboundAction( + title = "Удаляю VPN/WireGuard-файл", + onSuccess = { importedWgConfigText = "" } + ) { deleteImportedWireGuardExit(it) } } ) OutboundDialog.Diagnostics -> OutboundDiagnosticsDialog( @@ -2554,7 +2833,7 @@ fun DeployTab( ) { HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f)) Text( - "Экспорт сохраняет базу WDTT Plus: профиль владельца, Telegram-бота, клиентов, привязки устройств, статистику и историю. Полный экспорт дополнительно сохраняет WireGuard-ключи сервера.", + "Экспорт сохраняет базу WDTT Plus: профиль и устройства владельца, настройки Telegram-бота, клиентов, сроки хранения записей, привязки устройств, статистику и историю. Полный экспорт дополнительно сохраняет WireGuard-ключи сервера.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) @@ -2573,6 +2852,11 @@ fun DeployTab( style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error ) + Text( + "Новые файлы экспорта получают контрольные суммы. Перед импортом приложение проверяет целостность базы и WireGuard-ключей; старые файлы остаются совместимыми.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) Row( modifier = Modifier.fillMaxWidth(), @@ -2629,7 +2913,7 @@ fun DeployTab( includeWgKeys = includeKeys ) pendingExportBackup = backup - migrationStatus = "Бэкап подготовлен: паролей ${backup.passwordCount}, устройств ${backup.deviceCount}. Выберите место сохранения." + migrationStatus = "Бэкап подготовлен: клиентов ${backup.passwordCount}, устройств ${backup.deviceCount}. Выберите место сохранения." val stamp = SimpleDateFormat("yyyyMMdd-HHmm", Locale.US).format(Date()) val safeHost = ip.replace(Regex("[^A-Za-z0-9_.-]"), "_").ifBlank { "server" } exportLauncher.launch("wdtt-backup-$safeHost-$stamp.json") @@ -2674,10 +2958,23 @@ fun DeployTab( verticalArrangement = Arrangement.spacedBy(8.dp) ) { Text( - "Выбран ${if (backup.hasWgKeys) "полный" else "частичный"} бэкап: ${backup.passwordCount} паролей, ${backup.deviceCount} устройств${if (backup.hasWgKeys) ", WG-ключи сервера включены" else ", без WG-ключей сервера"}.", + "Выбран ${if (backup.hasWgKeys) "полный" else "частичный"} бэкап: ${backup.passwordCount} клиентов, ${backup.deviceCount} устройств${if (backup.hasWgKeys) ", WG-ключи сервера включены" else ", без WG-ключей сервера"}.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface ) + Text( + if (backup.integrityVerified) { + "Целостность файла подтверждена." + } else { + "Старый совместимый формат: контрольной суммы в файле нет." + }, + style = MaterialTheme.typography.bodySmall, + color = if (backup.integrityVerified) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.error + } + ) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { FilterChip( selected = selectedImportMode == ServerImportMode.Replace, @@ -2698,7 +2995,7 @@ fun DeployTab( if (selectedImportMode == ServerImportMode.Replace) { "Заменить: база сервера будет перезаписана бэкапом. Это режим для переезда на новый сервер." } else { - "Добавить: текущие настройки сервера сохранятся, отсутствующие пароли и устройства будут добавлены без перезаписи конфликтов." + "Добавить: текущие настройки сервера сохранятся, отсутствующие клиенты и устройства будут добавлены без перезаписи конфликтов." }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant @@ -3031,7 +3328,7 @@ private fun DeployResultPanel( } @Composable -private fun DeploySuccessBanner(successCountdown: Int) { +private fun DeploySuccessBanner(successCountdown: Int, serverVersion: String) { Surface( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), @@ -3045,12 +3342,19 @@ private fun DeploySuccessBanner(successCountdown: Int) { ) { Icon(Icons.Default.CheckCircle, contentDescription = null, tint = WDTTColors.connected) Spacer(Modifier.width(8.dp)) - Text( - text = "Деплой успешно завершён ($successCountdown)", - color = WDTTColors.connected, - fontWeight = FontWeight.Bold, - style = MaterialTheme.typography.bodyMedium - ) + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + text = "Деплой успешно завершён ($successCountdown)", + color = WDTTColors.connected, + fontWeight = FontWeight.Bold, + style = MaterialTheme.typography.bodyMedium + ) + Text( + text = "Серверная часть: WDTT Plus $serverVersion", + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall + ) + } } } } @@ -3147,6 +3451,11 @@ private fun OutboundRoutingSection( style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) + Text( + "Отдельного переключателя режимов нет: кнопка включения или установки внутри выбранного варианта делает его текущим и отключает прежний выход. «Вернуть прямой выход» принудительно отключает все внешние маршруты WDTT, но сохраняет их настройки для повторного включения.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.tertiary + ) OutboundServerStateCard( snapshot = snapshot, snapshotBusy = snapshotBusy, @@ -3158,7 +3467,7 @@ private fun OutboundRoutingSection( ) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { OutboundModeButton( - title = "Прокси VPS", + title = "Прокси на этом VPS", description = "Создаёт SOCKS5/HTTP на этом сервере. IP не скрывает: выход будет через тот же VPS.", enabled = enabled, indicator = outboundModeIndicator(snapshot, OutboundDialog.LocalProxy) @@ -3199,7 +3508,7 @@ private fun OutboundRoutingSection( } } Text( - "«Заполнить» читает сохранённые настройки с сервера и заменяет ими только локальные поля этого блока. На сервер ничего не записывается; активный режим выхода не переключается.", + "«Загрузить настройки» читает сохранённые значения с сервера и заменяет ими только поля текущего VPN-профиля в приложении. На сервер ничего не записывается; активный режим выхода не переключается.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) @@ -3219,7 +3528,7 @@ private fun OutboundRoutingSection( CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) Spacer(Modifier.width(6.dp)) } - Text(if (restoring) "Читаю..." else "Заполнить", fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center) + Text(if (restoring) "Загрузка..." else "Загрузить настройки", fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center) } OutlinedButton( onClick = onStatus, @@ -3232,7 +3541,7 @@ private fun OutboundRoutingSection( CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) Spacer(Modifier.width(6.dp)) } - Text(if (readingStatus) "Читаю..." else "Статус", fontWeight = FontWeight.SemiBold) + Text(if (readingStatus) "Проверка..." else "Подробный статус", fontWeight = FontWeight.SemiBold) } } if (status.isNotBlank()) { @@ -3488,8 +3797,10 @@ private fun LocalProxyDialog( onRemove: () -> Unit ) { var passwordFocused by rememberSaveable { mutableStateOf(false) } + var confirmRemove by rememberSaveable { mutableStateOf(false) } val port = portInput.toIntOrNull()?.takeIf { it in 1..65533 } - OutboundDialogFrame("Прокси VPS", status, progressTitle, progress, onDismiss) { + val credentialsIssue = localProxyCredentialsIssue(loginInput, passwordInput) + OutboundDialogFrame("Прокси на этом VPS", status, progressTitle, progress, onDismiss) { OutboundDialogStateBanner(indicator) Text( "На этом же VPS будут созданы два входа с одним логином и паролем: SOCKS5 и HTTP. Это удобно как прокси, но IP не маскирует: наружу будет виден текущий сервер.", @@ -3510,6 +3821,7 @@ private fun LocalProxyDialog( onValueChange = { onLoginChanged(it.filter { c -> !c.isWhitespace() }.take(40)) }, label = { Text("Логин") }, singleLine = true, + isError = credentialsIssue != null && loginInput.isNotBlank(), modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp) ) @@ -3518,12 +3830,16 @@ private fun LocalProxyDialog( onValueChange = { onPasswordChanged(it.filter { c -> !c.isWhitespace() }.take(80)) }, label = { Text("Пароль") }, singleLine = true, + isError = credentialsIssue != null && passwordInput.isNotBlank(), visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(), modifier = Modifier .fillMaxWidth() .onFocusChanged { passwordFocused = it.isFocused }, shape = RoundedCornerShape(16.dp) ) + if (credentialsIssue != null) { + InlineActionMessage(credentialsIssue) + } if (port != null) { Text( "SOCKS5: порт $port. HTTP: порт ${port + 1}. Веб-страница 3proxy: порт ${port + 2}. Логин и пароль одинаковые для всех вариантов. «Проверить» не устанавливает прокси, а подключается к уже запущенному SOCKS5 с этими данными.", @@ -3537,11 +3853,11 @@ private fun LocalProxyDialog( secondaryBusy = actionTitle.contains("Проверяю прокси", ignoreCase = true), primaryText = "Установить", primaryBusyText = "Установка...", - primaryEnabled = port != null && loginInput.isNotBlank() && passwordInput.length >= 8, + primaryEnabled = port != null && credentialsIssue == null, onPrimary = { onInstall(port ?: 1080, loginInput, passwordInput) }, secondaryText = "Проверить", secondaryBusyText = "Проверка...", - secondaryEnabled = port != null && loginInput.isNotBlank() && passwordInput.isNotBlank(), + secondaryEnabled = port != null && credentialsIssue == null, onSecondary = { onCheck(port ?: 1080, loginInput, passwordInput) } ) OutlinedButton( @@ -3572,7 +3888,7 @@ private fun LocalProxyDialog( Text(if (stopping) "Остановка..." else "Остановить", textAlign = TextAlign.Center) } OutlinedButton( - onClick = onRemove, + onClick = { confirmRemove = true }, enabled = !busy && removeEnabled, modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 48.dp), shape = RoundedCornerShape(16.dp), @@ -3587,6 +3903,29 @@ private fun LocalProxyDialog( } } } + if (confirmRemove) { + AlertDialog( + onDismissRequest = { if (!busy) confirmRemove = false }, + title = { Text("Удалить прокси с этого VPS?") }, + text = { + Text( + "Будут удалены служба, конфигурация и правила доступа к портам. Установленный бинарник 3proxy останется в системе и сможет использоваться при повторной установке." + ) + }, + confirmButton = { + Button( + onClick = { + confirmRemove = false + onRemove() + }, + enabled = !busy + ) { Text("Удалить") } + }, + dismissButton = { + TextButton(onClick = { confirmRemove = false }, enabled = !busy) { Text("Отмена") } + } + ) + } } @Composable @@ -3603,6 +3942,7 @@ private fun ExternalProxyDialog( loginInput: String, passwordInput: String, disableEnabled: Boolean, + deleteEnabled: Boolean, onKindChanged: (ProxyKind) -> Unit, onHostChanged: (String) -> Unit, onPortChanged: (String) -> Unit, @@ -3611,11 +3951,14 @@ private fun ExternalProxyDialog( onDismiss: () -> Unit, onCheck: (ProxyKind, String, Int, String, String) -> Unit, onEnable: (ProxyKind, String, Int, String, String) -> Unit, - onDisable: () -> Unit + onDisable: () -> Unit, + onDelete: () -> Unit ) { var passwordFocused by rememberSaveable { mutableStateOf(false) } + var confirmDelete by rememberSaveable { mutableStateOf(false) } val port = portInput.toIntOrNull()?.takeIf { it in 1..65535 } val hostValid = hostInput.isValidPublicHost() + val credentialsIssue = externalProxyCredentialsIssue(loginInput, passwordInput) OutboundDialogFrame("Внешний TCP-прокси", status, progressTitle, progress, onDismiss) { OutboundDialogStateBanner(indicator) Text( @@ -3670,6 +4013,9 @@ private fun ExternalProxyDialog( .onFocusChanged { passwordFocused = it.isFocused }, shape = RoundedCornerShape(16.dp) ) + if (credentialsIssue != null) { + InlineActionMessage(credentialsIssue) + } Text( "При включении прежний внешний выход WDTT будет выключен, затем начнёт работать этот прокси. Это маскирует только поддерживаемый TCP-трафик пользователей; обычный интернет самого сервера не меняется.", style = MaterialTheme.typography.bodySmall, @@ -3681,22 +4027,61 @@ private fun ExternalProxyDialog( secondaryBusy = actionTitle.contains("Проверяю доступность", ignoreCase = true), primaryText = "Включить", primaryBusyText = "Включение...", - primaryEnabled = hostValid && port != null, + primaryEnabled = hostValid && port != null && credentialsIssue == null, onPrimary = { onEnable(kind, hostInput.trim(), port ?: 1080, loginInput, passwordInput) }, secondaryText = "Проверить", secondaryBusyText = "Проверка...", - secondaryEnabled = hostValid && port != null, + secondaryEnabled = hostValid && port != null && credentialsIssue == null, onSecondary = { onCheck(kind, hostInput.trim(), port ?: 1080, loginInput, passwordInput) } ) - OutlinedButton(onClick = onDisable, enabled = !busy && disableEnabled, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) { - val disabling = actionTitle.contains("Возвращаю", ignoreCase = true) - if (disabling) { - CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) - Spacer(Modifier.width(6.dp)) + Row( + modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedButton( + onClick = onDisable, + enabled = !busy && disableEnabled, + modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + val disabling = actionTitle.contains("Возвращаю", ignoreCase = true) + if (disabling) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + Spacer(Modifier.width(6.dp)) + } + Text(if (disabling) "Отключение..." else "Отключить") + } + OutlinedButton( + onClick = { confirmDelete = true }, + enabled = !busy && deleteEnabled, + modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + Text("Удалить") } - Text(if (disabling) "Отключение..." else "Отключить") } } + if (confirmDelete) { + AlertDialog( + onDismissRequest = { if (!busy) confirmDelete = false }, + title = { Text("Удалить настройки внешнего прокси?") }, + text = { + Text("С текущего VPS будут удалены служба, конфигурация, сохранённые реквизиты и правила перенаправления внешнего TCP-прокси.") + }, + confirmButton = { + Button( + onClick = { + confirmDelete = false + onDelete() + }, + enabled = !busy + ) { Text("Удалить") } + }, + dismissButton = { + TextButton(onClick = { confirmDelete = false }, enabled = !busy) { Text("Отмена") } + } + ) + } } @Composable @@ -3715,9 +4100,9 @@ private fun WireGuardExitVpsDialog( privateKeyConfigured: Boolean, hasSshAuthentication: Boolean, wgPortInput: String, - dnsInput: String, disableEnabled: Boolean, checkEnabled: Boolean, + deleteEnabled: Boolean, onHostChanged: (String) -> Unit, onSshPortChanged: (String) -> Unit, onUserChanged: (String) -> Unit, @@ -3726,13 +4111,14 @@ private fun WireGuardExitVpsDialog( onEditSshKey: () -> Unit, onSshHelp: () -> Unit, onWgPortChanged: (String) -> Unit, - onDnsChanged: (String) -> Unit, onDismiss: () -> Unit, - onInstall: (String, Int, String, String, Int, String) -> Unit, + onInstall: (String, Int, String, String, Int) -> Unit, onCheck: () -> Unit, - onDisable: () -> Unit + onDisable: () -> Unit, + onDelete: () -> Unit ) { var passwordFocused by rememberSaveable { mutableStateOf(false) } + var confirmDelete by rememberSaveable { mutableStateOf(false) } val hostValid = hostInput.isValidPublicHost() val sshPort = sshPortInput.toIntOrNull()?.takeIf { it in 1..65535 } val wgPort = wgPortInput.toIntOrNull()?.takeIf { it in 1..65535 } @@ -3759,7 +4145,10 @@ private fun WireGuardExitVpsDialog( selected = sshAuthMode == mode, onClick = { onSshAuthModeChanged(mode) }, shape = SegmentedButtonDefaults.itemShape(index, 2), - enabled = !busy + enabled = !busy, + icon = { + StableSegmentedButtonIcon(selected = sshAuthMode == mode) + }, ) { Text(label) } } } @@ -3817,29 +4206,25 @@ private fun WireGuardExitVpsDialog( Text(if (privateKeyConfigured) "Приватный SSH-ключ добавлен" else "Добавить приватный SSH-ключ") } } - Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) { - OutlinedTextField( - value = wgPortInput, - onValueChange = { onWgPortChanged(it.filter(Char::isDigit).take(5)) }, - label = { Text("Порт WireGuard") }, - singleLine = true, - modifier = Modifier.weight(1f), - shape = RoundedCornerShape(16.dp) - ) - OutlinedTextField( - value = dnsInput, - onValueChange = { onDnsChanged(it.filter { c -> !c.isWhitespace() }) }, - label = { Text("DNS") }, - singleLine = true, - modifier = Modifier.weight(1f), - shape = RoundedCornerShape(16.dp) - ) - } + OutlinedTextField( + value = wgPortInput, + onValueChange = { onWgPortChanged(it.filter(Char::isDigit).take(5)) }, + label = { Text("UDP-порт WireGuard") }, + supportingText = { Text("Порт будет открыт на дополнительном VPS.") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp) + ) Text( - "Если настройка не получится, WDTT Plus попытается вернуть прямой выход через текущий сервер. Приватный SSH-ключ дополнительного VPS хранится только на этом Android-устройстве; после переустановки приложения его потребуется добавить снова.", + "Если настройка не получится, WDTT Plus восстановит прежние настройки на обоих VPS. DNS-параметры VPN-профиля здесь не применяются: DNS для клиентов задаётся в основных настройках WDTT. Приватный SSH-ключ дополнительного VPS хранится только на этом Android-устройстве; после переустановки приложения его потребуется добавить снова.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error ) + Text( + "«Отключить» возвращает прямой выход на текущем VPS и оставляет WireGuard на дополнительном VPS готовым для повторного включения. «Удалить» очищает созданную WDTT-конфигурацию на обоих VPS.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) DialogButtons( busy = busy, primaryBusy = actionTitle.contains("Настраиваю WireGuard", ignoreCase = true), @@ -3847,21 +4232,63 @@ private fun WireGuardExitVpsDialog( primaryText = "Настроить выход", primaryBusyText = "Настройка...", primaryEnabled = hostValid && sshPort != null && wgPort != null && userInput.isNotBlank() && hasSshAuthentication, - onPrimary = { onInstall(hostInput.trim(), sshPort ?: 22, userInput, passwordInput, wgPort ?: 51820, dnsInput) }, + onPrimary = { onInstall(hostInput.trim(), sshPort ?: 22, userInput, passwordInput, wgPort ?: 51820) }, secondaryText = "Проверить", secondaryBusyText = "Проверка...", secondaryEnabled = checkEnabled, onSecondary = onCheck ) - OutlinedButton(onClick = onDisable, enabled = !busy && disableEnabled, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) { - val disabling = actionTitle.contains("Возвращаю", ignoreCase = true) - if (disabling) { - CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) - Spacer(Modifier.width(6.dp)) + Row( + modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedButton( + onClick = onDisable, + enabled = !busy && disableEnabled, + modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + val disabling = actionTitle.contains("Возвращаю", ignoreCase = true) + if (disabling) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + Spacer(Modifier.width(6.dp)) + } + Text(if (disabling) "Отключение..." else "Отключить") + } + OutlinedButton( + onClick = { confirmDelete = true }, + enabled = !busy && deleteEnabled && hostValid && sshPort != null && + userInput.isNotBlank() && hasSshAuthentication, + modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + Text("Удалить") } - Text(if (disabling) "Отключение..." else "Отключить") } } + if (confirmDelete) { + AlertDialog( + onDismissRequest = { if (!busy) confirmDelete = false }, + title = { Text("Удалить выход через другой сервер?") }, + text = { + Text( + "Текущий VPS сначала вернётся на прямой выход. Затем на дополнительном VPS будут удалены созданные WDTT WireGuard-служба, конфигурация, ключи и правила firewall. Потребуется рабочий SSH-доступ к обоим серверам." + ) + }, + confirmButton = { + Button( + onClick = { + confirmDelete = false + onDelete() + }, + enabled = !busy + ) { Text("Удалить") } + }, + dismissButton = { + TextButton(onClick = { confirmDelete = false }, enabled = !busy) { Text("Отмена") } + } + ) + } } @Composable @@ -4126,6 +4553,7 @@ private fun ImportedWireGuardDialog( onDelete: () -> Unit ) { 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) { OutboundDialogStateBanner(indicator) @@ -4208,7 +4636,7 @@ private fun ImportedWireGuardDialog( Text(if (disabling) "Отключение..." else "Отключить", textAlign = TextAlign.Center) } OutlinedButton( - onClick = onDelete, + onClick = { confirmDelete = true }, enabled = !busy && deleteEnabled, modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 48.dp), shape = RoundedCornerShape(16.dp), @@ -4223,6 +4651,29 @@ private fun ImportedWireGuardDialog( } } } + if (confirmDelete) { + AlertDialog( + onDismissRequest = { if (!busy) confirmDelete = false }, + title = { Text("Удалить VPN/WireGuard-файл?") }, + text = { + Text( + "Рабочий файл и его сохранённая копия на текущем сервере будут удалены, а выход WDTT вернётся на прямой. Для повторного включения потребуется выбрать файл заново." + ) + }, + confirmButton = { + Button( + onClick = { + confirmDelete = false + onDelete() + }, + enabled = !busy + ) { Text("Удалить") } + }, + dismissButton = { + TextButton(onClick = { confirmDelete = false }, enabled = !busy) { Text("Отмена") } + } + ) + } } @Composable @@ -4263,6 +4714,13 @@ private fun OutboundDiagnosticsDialog( private fun InlineActionMessage(status: String, modifier: Modifier = Modifier) { val isError = status.startsWith("Ошибка", true) || status.startsWith("Укажите", true) || + status.startsWith("В логине", true) || + status.startsWith("В пароле", true) || + status.startsWith("Пароль должен", true) || + status.startsWith("Для указанного", true) || + status.startsWith("Для пароля", true) || + status.startsWith("Логин внешнего", true) || + status.startsWith("Пароль внешнего", true) || status.startsWith("Выбран публичный", true) || status.startsWith("Формат ключа", true) || status.contains("добавьте приватный", true) || @@ -4672,6 +5130,39 @@ internal fun serverDiagnosticsScript( sed -n 's/.*"outboundMode"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' /etc/wdtt/outbound.json 2>/dev/null | head -n 1 fi } + wdtt_diag_wg_exit_probe() { + mode="${'$'}1" + source_ip="${'$'}(ip -4 -o addr show dev wdtt0 2>/dev/null | awk '{split(${'$'}4, addr, "/"); print addr[1]; exit}')" + if ! wdtt_diag_cmd curl; then + echo "не выполнена: curl отсутствует" + return 2 + fi + if [ -z "${'$'}source_ip" ]; then + 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)" + if [ -z "${'$'}trace" ]; then + echo "не пройдена: HTTPS через маршрут WDTT не отвечает" + return 1 + fi + exit_ip="${'$'}(printf '%s\n' "${'$'}trace" | sed -n 's/^ip=//p' | head -n 1)" + if [ "${'$'}mode" = "warp_free" ]; then + warp_state="${'$'}(printf '%s\n' "${'$'}trace" | sed -n 's/^warp=//p' | head -n 1)" + case "${'$'}warp_state" in + on|plus) + echo "пройдена: Cloudflare подтвердил warp=${'$'}warp_state, выходной IPv4 ${'$'}{exit_ip:-определён}" + return 0 + ;; + *) + echo "не пройдена: маршрут отвечает, но Cloudflare сообщил warp=${'$'}{warp_state:-не определён}" + return 1 + ;; + esac + fi + echo "пройдена: HTTPS через маршрут WDTT отвечает, выходной IPv4 ${'$'}{exit_ip:-определён}" + return 0 + } OS_NAME="${'$'}(wdtt_diag_os_name)" OS_ID="${'$'}(wdtt_diag_os_id)" @@ -4800,34 +5291,24 @@ internal fun serverDiagnosticsScript( wdtt_diag_emit "WARNING" "Сеть сервера" "публичный IPv4 не проверен" "${'$'}NET_DETAILS" "Проверьте исходящий HTTPS-доступ с сервера; он нужен для wgcf, WARP-проверок и обновлений." fi - VK_WARN=0 VK_DETAILS="" - for host in vk.com api.vk.me calls.okcdn.ru id.vk.com static.vk.com static.vk.ru; do + 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_WARN=1 VK_DETAILS="${'$'}VK_DETAILS ${'$'}host DNS: не разрешается;" fi done - VK_HTTP="${'$'}(wdtt_diag_http_probe https://vk.com/)"; VK_HTTP_CODE="${'$'}?" - [ "${'$'}VK_HTTP_CODE" = "0" ] || VK_WARN=1 - VK_DETAILS="${'$'}VK_DETAILS vk.com HTTPS: ${'$'}VK_HTTP;" - VK_API_HTTP="${'$'}(wdtt_diag_http_probe 'https://api.vk.me/method/users.get?v=5.131')"; VK_API_HTTP_CODE="${'$'}?" - [ "${'$'}VK_API_HTTP_CODE" = "0" ] || VK_WARN=1 - VK_DETAILS="${'$'}VK_DETAILS api.vk.me HTTPS: ${'$'}VK_API_HTTP;" - OK_HTTP="${'$'}(wdtt_diag_http_probe https://calls.okcdn.ru/fb.do)"; OK_HTTP_CODE="${'$'}?" - [ "${'$'}OK_HTTP_CODE" = "0" ] || VK_WARN=1 - VK_DETAILS="${'$'}VK_DETAILS calls.okcdn.ru HTTPS: ${'$'}OK_HTTP;" - CAPTCHA_HTTP="${'$'}(wdtt_diag_http_probe https://id.vk.com/)"; CAPTCHA_HTTP_CODE="${'$'}?" - [ "${'$'}CAPTCHA_HTTP_CODE" = "0" ] || VK_WARN=1 - VK_DETAILS="${'$'}VK_DETAILS id.vk.com HTTPS: ${'$'}CAPTCHA_HTTP." - if [ "${'$'}VK_WARN" = "0" ]; then - wdtt_diag_emit "OK" "VK / TURN-зависимости" "базовая доступность есть" "${'$'}VK_DETAILS Реальные TURN-адреса выдаются VK/OK только для конкретного живого VK-хеша, поэтому TURN Allocate без хеша здесь не выполняется." "Если туннель не стартует, дополнительно проверьте VK-хеш на телефоне: там проверяется получение TURN credentials и возможная капча." - else - wdtt_diag_emit "WARNING" "VK / TURN-зависимости" "есть риск недоступности" "${'$'}VK_DETAILS Реальные TURN-адреса выдаются VK/OK только для конкретного живого VK-хеша, поэтому TURN Allocate без хеша здесь не выполняется." "Проверьте DNS/HTTPS-доступ к VK и OK CDN с VPS, регион VPS и состояние VK-хеша на телефоне." - fi + 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 @@ -4882,12 +5363,27 @@ internal fun serverDiagnosticsScript( 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="" + NAT_RULES=0 + DIRECT_NAT_ACTIVE=0 + WG_NAT_ACTIVE=0 + WG_POLICY_RULE_ACTIVE=0 + WG_DEFAULT_ROUTE_ACTIVE=0 + WG_INTERFACE_ACTIVE=0 + WG_SERVICE_ACTIVE=0 if wdtt_diag_cmd iptables; then NAT_RULES="${'$'}(iptables -t nat -S 2>/dev/null | grep -c 'WDTT\\|wdtt\\|MASQUERADE' 2>/dev/null)" FIREWALL_DETAILS="iptables найден; NAT-правил WDTT/MASQUERADE: ${'$'}NAT_RULES." FIREWALL_SEVERITY="OK" FIREWALL_STATUS="iptables доступен" + iptables -t nat -S POSTROUTING 2>/dev/null | + grep -q -- '--comment WDTT_MANAGED .*MASQUERADE' && + DIRECT_NAT_ACTIVE=1 + iptables -t nat -S POSTROUTING 2>/dev/null | + grep -q -- "-o wg-wdtt-exit .*--comment WDTT_EXIT .*MASQUERADE" && + WG_NAT_ACTIVE=1 elif wdtt_diag_cmd nft; then FIREWALL_DETAILS="iptables не найден, nft найден. Часть скриптов WDTT Plus ожидает iptables-совместимый интерфейс." FIREWALL_SEVERITY="WARNING" @@ -4901,8 +5397,47 @@ internal fun serverDiagnosticsScript( RULES="${'$'}(ip rule show 2>/dev/null | grep -c 'lookup 100\\|from .* table 100' 2>/dev/null)" ROUTE100="${'$'}(ip route show table 100 2>/dev/null | head -n 2 | tr '\n' '; ')" FIREWALL_DETAILS="${'$'}FIREWALL_DETAILS Policy routing table 100 rules: ${'$'}RULES. table 100: ${'$'}{ROUTE100:-пусто}." + ip rule show 2>/dev/null | + grep -Eq 'from [^ ]+ lookup 100([[:space:]]|${'$'})|from [^ ]+ lookup wdtt-exit([[:space:]]|${'$'})|from [^ ]+ table 100([[:space:]]|${'$'})' && + WG_POLICY_RULE_ACTIVE=1 + ip route show table 100 2>/dev/null | + grep -Eq '^default([[:space:]].*)? dev wg-wdtt-exit([[:space:]]|${'$'})' && + WG_DEFAULT_ROUTE_ACTIVE=1 + ip link show dev wg-wdtt-exit >/dev/null 2>&1 && WG_INTERFACE_ACTIVE=1 fi - wdtt_diag_emit "${'$'}FIREWALL_SEVERITY" "Маршрутизация и NAT" "${'$'}FIREWALL_STATUS" "${'$'}FIREWALL_DETAILS" "Для внешнего выхода WDTT через WARP/VPN/прокси нужны ip rule/ip route и NAT." + if wdtt_diag_cmd systemctl && systemctl is-active --quiet wdtt-wg-exit.service 2>/dev/null; then + WG_SERVICE_ACTIVE=1 + fi + case "${'$'}OUT_MODE" in + warp_free|wireguard_vps|imported_wg) + FIREWALL_DETAILS="${'$'}FIREWALL_DETAILS WireGuard-выход: интерфейс=${'$'}WG_INTERFACE_ACTIVE, служба=${'$'}WG_SERVICE_ACTIVE, правило=${'$'}WG_POLICY_RULE_ACTIVE, маршрут=${'$'}WG_DEFAULT_ROUTE_ACTIVE, NAT=${'$'}WG_NAT_ACTIVE." + WG_EXIT_PROBE="${'$'}(wdtt_diag_wg_exit_probe "${'$'}OUT_MODE")" + WG_EXIT_PROBE_CODE="${'$'}?" + FIREWALL_DETAILS="${'$'}FIREWALL_DETAILS Сквозная проверка: ${'$'}WG_EXIT_PROBE." + if [ "${'$'}WG_INTERFACE_ACTIVE" = "1" ] && + [ "${'$'}WG_SERVICE_ACTIVE" = "1" ] && + [ "${'$'}WG_POLICY_RULE_ACTIVE" = "1" ] && + [ "${'$'}WG_DEFAULT_ROUTE_ACTIVE" = "1" ] && + [ "${'$'}WG_NAT_ACTIVE" = "1" ] && + [ "${'$'}WG_EXIT_PROBE_CODE" = "0" ]; then + FIREWALL_SEVERITY="OK" + FIREWALL_STATUS="WireGuard-выход исправен" + else + FIREWALL_SEVERITY="ERROR" + FIREWALL_STATUS="WireGuard-выход запущен не полностью" + fi + ;; + direct|"") + if [ "${'$'}WDTT_SERVICE_FOR_ROUTING" = "active" ] && [ "${'$'}DIRECT_NAT_ACTIVE" != "1" ]; then + FIREWALL_SEVERITY="ERROR" + FIREWALL_STATUS="NAT прямого выхода отсутствует" + elif [ "${'$'}WDTT_SERVICE_FOR_ROUTING" = "active" ]; then + FIREWALL_SEVERITY="OK" + FIREWALL_STATUS="прямой выход настроен" + fi + ;; + esac + wdtt_diag_emit "${'$'}FIREWALL_SEVERITY" "Маршрутизация и NAT" "${'$'}FIREWALL_STATUS" "${'$'}FIREWALL_DETAILS" "Для WARP/VPN нужны одновременно активные интерфейс и служба, правило ip rule, маршрут таблицы 100, NAT WDTT_EXIT и успешный HTTPS-выход. Откройте выбранный режим в «Выходной IP и прокси» и нажмите «Установить / восстановить»." WDTT_SERVICE="${'$'}(wdtt_diag_service_state wdtt.service)" WDTT_BIN="${'$'}(wdtt_diag_file_state /usr/local/bin/wdtt-server)" @@ -4969,12 +5504,15 @@ internal fun serverDiagnosticsScript( fi wdtt_diag_emit "INFO" "WireGuard" "${'$'}WG_TOOLS" "Интерфейсы wg: ${'$'}{WG_IFACES:-нет или недоступно}. /etc/wireguard/wg-wdtt-exit.conf: ${'$'}(wdtt_diag_file_state /etc/wireguard/wg-wdtt-exit.conf)." "PrivateKey и содержимое конфигов не читаются." - OUT_MODE="${'$'}(wdtt_diag_outbound_mode)" WG_EXIT="${'$'}(wdtt_diag_service_state wdtt-wg-exit.service)" WARP_TIMER="${'$'}(wdtt_diag_service_state wdtt-warp-watchdog.timer)" PROXY_SERVICE="${'$'}(wdtt_diag_service_state wdtt-3proxy.service)" REDSOCKS_SERVICE="${'$'}(wdtt_diag_service_state wdtt-redsocks.service)" OUT_DETAILS="mode=${'$'}{OUT_MODE:-direct/не задан}. wg-exit=${'$'}WG_EXIT. warp-watchdog=${'$'}WARP_TIMER. 3proxy=${'$'}PROXY_SERVICE. redsocks=${'$'}REDSOCKS_SERVICE." + if wdtt_diag_cmd journalctl && [ "${'$'}WG_EXIT" != "active" ]; then + WG_EXIT_LOG="${'$'}(journalctl -u wdtt-wg-exit.service -n 12 --no-pager 2>/dev/null | sed -E 's/(private[[:space:]_-]*key[[:space:]]*[:=])[[:space:]]*[^[:space:]]+/\1 (скрыт)/Ig' | tr '\n' '; ' | head -c 1200)" + [ -n "${'$'}WG_EXIT_LOG" ] && OUT_DETAILS="${'$'}OUT_DETAILS Последний журнал wg-exit: ${'$'}WG_EXIT_LOG" + fi if [ -r /etc/wdtt-plus/warp/selected.env ]; then WARP_SELECTED="${'$'}(sed -n 's/^WARP_MTU=/MTU /p;s/^WARP_ENDPOINT=/endpoint /p' /etc/wdtt-plus/warp/selected.env 2>/dev/null | tr '\n' '; ')" OUT_DETAILS="${'$'}OUT_DETAILS WARP подбор: ${'$'}WARP_SELECTED" @@ -5181,8 +5719,7 @@ 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) - if (clean.contains("[✗]") || clean.contains("FAIL") || - (clean.contains("error", true) && !clean.contains("2>/dev/null"))) { + if (shouldWriteRemoteErrorToUserLog(clean)) { DeployManager.writeError("REMOTE: $clean") TunnelManager.addDeployErrorLog("REMOTE: $clean") } @@ -5213,7 +5750,7 @@ private class SSHClient(private val session: Session, private val pass: String) } } - fun upload(localFile: File, remotePath: String) { + fun upload(localFile: File, remotePath: String, permissions: Int? = null) { if (!session.isConnected) { DeployManager.writeError("SSH upload: сессия разорвана") throw Exception("Session is down") @@ -5223,6 +5760,7 @@ private class SSHClient(private val session: Session, private val pass: String) sftp = session.openChannel("sftp") as ChannelSftp sftp.connect(15000) sftp.put(localFile.absolutePath, remotePath) + permissions?.let { sftp.chmod(it, remotePath) } } catch (e: Exception) { DeployManager.writeError("SFTP upload error: ${e.message} | file: ${localFile.name}") throw e @@ -5295,13 +5833,40 @@ private suspend fun runRootScript( } } -private fun outboundShellPrelude(): String = """ +private suspend fun runCheckedRootScript( + target: OutboundSshTarget, + script: String, + timeout: Long = CMD_TIMEOUT +): String = withContext(Dispatchers.IO) { + var session: Session? = null + try { + session = createSshSession(target.host, target.user, target.credentials, target.port) + val output = SSHClient(session, target.pass) + .exec(rootCommand(script), timeout = timeout) + .trim() + markerValue(output, "WDTT_ERROR")?.let { + throw IllegalStateException(output.take(1200)) + } + if (output.startsWith("error:", ignoreCase = true) || + output.contains("\nerror:", ignoreCase = true) + ) { + throw IllegalStateException(output.take(1200)) + } + output + } finally { + try { session?.disconnect() } catch (_: Exception) {} + } +} + +internal fun outboundShellPrelude(): String = """ set -e WDTT_SUBNET="${'$'}(ip -4 route show dev wdtt0 scope link 2>/dev/null | awk '{print ${'$'}1; exit}')" [ -n "${'$'}WDTT_SUBNET" ] || WDTT_SUBNET="10.66.66.0/24" WDTT_IFACE="wdtt0" WDTT_TABLE="100" WDTT_WG_IFACE="wg-wdtt-exit" + WDTT_WG_OWNER_FILE="/etc/wdtt-plus/wg-exit/owner" + WDTT_WG_CONFIG_OWNER_FILE="/etc/wdtt-plus/wg-exit/config-owner" mkdir -p /etc/wdtt /etc/wdtt/outbound /etc/wdtt-plus/wg-exit wdtt_ext_iface() { ip -o route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if (${'$'}i=="dev") {print ${'$'}(i+1); exit}}' @@ -5361,20 +5926,33 @@ private fun outboundShellPrelude(): String = """ return 1 fi } - wdtt_clear_external_out() { + 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 + iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true + iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true + fi + systemctl disable --now wdtt-redsocks 2>/dev/null || systemctl stop wdtt-redsocks 2>/dev/null || true + wdtt_kill_redsocks_listener + systemctl reset-failed wdtt-redsocks.service 2>/dev/null || true + } + wdtt_clear_wireguard_out() { systemctl disable --now wdtt-warp-watchdog.timer 2>/dev/null || true systemctl disable --now wdtt-wg-exit.service 2>/dev/null || true if command -v iptables >/dev/null 2>&1; then - iptables -t nat -D PREROUTING -i "${'$'}WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null || true - iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true - iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true - iptables -t nat -D POSTROUTING -s "${'$'}WDTT_SUBNET" -o "${'$'}WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null || true + while iptables -t nat -D POSTROUTING -s "${'$'}WDTT_SUBNET" -o "${'$'}WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null; do :; done fi - ip rule del from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TABLE" priority 100 2>/dev/null || true + while ip rule del from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TABLE" priority 100 2>/dev/null; do :; done ip route flush table "${'$'}WDTT_TABLE" 2>/dev/null || true - systemctl disable --now wdtt-redsocks 2>/dev/null || systemctl stop wdtt-redsocks 2>/dev/null || true - wdtt_kill_redsocks_listener - wg-quick down "${'$'}WDTT_WG_IFACE" 2>/dev/null || true + if ! wg-quick down "${'$'}WDTT_WG_IFACE" 2>/dev/null; then + ip link delete "${'$'}WDTT_WG_IFACE" 2>/dev/null || true + fi + rm -f "${'$'}WDTT_WG_OWNER_FILE" + systemctl reset-failed wdtt-wg-exit.service 2>/dev/null || true + } + wdtt_clear_external_out() { + wdtt_clear_proxy_out + wdtt_clear_wireguard_out } wdtt_kill_redsocks_listener() { rm -f /run/wdtt-redsocks.pid 2>/dev/null || true @@ -5399,24 +5977,32 @@ private fun outboundShellPrelude(): String = """ [ -n "${'$'}proxy_ip" ] && iptables -t nat -A "${'$'}chain" -d "${'$'}proxy_ip" -j RETURN 2>/dev/null || true } wdtt_cleanup_proxy_test() { + cleanup_test_source="${'$'}{WDTT_PROXY_TEST_SOURCE:-}" + [ -n "${'$'}cleanup_test_source" ] && iptables -t nat -D OUTPUT -s "${'$'}cleanup_test_source" -p tcp -j WDTT_PROXY_TEST 2>/dev/null || true + # Удаляем также правило старых версий, если предыдущая проверка была прервана. iptables -t nat -D OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST 2>/dev/null || true iptables -t nat -F WDTT_PROXY_TEST 2>/dev/null || true iptables -t nat -X WDTT_PROXY_TEST 2>/dev/null || true + WDTT_PROXY_TEST_SOURCE="" } wdtt_test_redsocks_path() { proxy_ip="${'$'}1" systemctl is-active --quiet wdtt-redsocks || { echo WDTT_ERROR=external_proxy_service_inactive; return 1; } command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; return 1; } + test_source="${'$'}(wdtt_test_source)" + [ -n "${'$'}test_source" ] || { echo WDTT_ERROR=wdtt_iface_not_found; return 1; } wdtt_cleanup_proxy_test + WDTT_PROXY_TEST_SOURCE="${'$'}test_source" iptables -t nat -N WDTT_PROXY_TEST 2>/dev/null || true iptables -t nat -F WDTT_PROXY_TEST wdtt_proxy_reserved_returns WDTT_PROXY_TEST "${'$'}proxy_ip" iptables -t nat -A WDTT_PROXY_TEST -p tcp -j REDIRECT --to-ports 12345 - if ! iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST 2>/dev/null; then + if ! iptables -t nat -I OUTPUT -s "${'$'}test_source" -p tcp -j WDTT_PROXY_TEST 2>/dev/null; then wdtt_cleanup_proxy_test - return 0 + echo WDTT_ERROR=external_proxy_test_rule_failed + return 1 fi - test_ip="${'$'}(curl -4fsS --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/tmp/wdtt-redsocks-test.err || true)" + test_ip="${'$'}(curl --interface "${'$'}test_source" -4fsS --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/tmp/wdtt-redsocks-test.err || true)" wdtt_cleanup_proxy_test [ -n "${'$'}test_ip" ] || { echo WDTT_ERROR=external_proxy_apply_failed; tail -n 20 /var/log/wdtt-redsocks.log 2>/dev/null || true; cat /tmp/wdtt-redsocks-test.err 2>/dev/null || true; return 1; } echo "Проверка пути через внешний TCP-прокси успешна. IP через прокси: ${'$'}test_ip" @@ -5440,10 +6026,14 @@ private fun outboundShellPrelude(): String = """ private fun outboundReadPrelude(): String = """ set -e + WDTT_IFACE="wdtt0" + WDTT_TABLE="100" WDTT_WG_IFACE="wg-wdtt-exit" + WDTT_WG_OWNER_FILE="/etc/wdtt-plus/wg-exit/owner" + WDTT_WG_CONFIG_OWNER_FILE="/etc/wdtt-plus/wg-exit/config-owner" """.trimIndent() -private fun outboundStatusScript(): String = shellScript( +internal fun outboundStatusScript(): String = shellScript( outboundShellPrelude(), """ MODE="direct" @@ -5498,8 +6088,35 @@ private fun outboundStatusScript(): String = shellScript( echo "Проверочный выход WDTT: режим не распознан" ;; esac - if systemctl is-active wdtt-3proxy >/dev/null 2>&1; then echo "Прокси VPS: служба запущена"; else echo "Прокси VPS: служба остановлена"; fi - if systemctl is-active wdtt-redsocks >/dev/null 2>&1; then echo "Внешний TCP-прокси для WDTT: включён"; else echo "Внешний TCP-прокси для WDTT: выключен"; fi + if systemctl is-active wdtt-3proxy >/dev/null 2>&1; then echo "Прокси на этом VPS: служба запущена"; else echo "Прокси на этом VPS: служба остановлена"; fi + if systemctl is-enabled wdtt-3proxy >/dev/null 2>&1; then echo "Автозапуск прокси на этом VPS: включён"; else echo "Автозапуск прокси на этом VPS: выключен"; fi + if systemctl is-active wdtt-redsocks >/dev/null 2>&1; then echo "Служба внешнего TCP-прокси для WDTT: запущена"; else echo "Служба внешнего TCP-прокси для WDTT: остановлена"; fi + if systemctl is-enabled wdtt-redsocks >/dev/null 2>&1; then echo "Автозапуск внешнего TCP-прокси: включён"; else echo "Автозапуск внешнего TCP-прокси: выключен"; fi + if command -v iptables >/dev/null 2>&1 && + iptables -t nat -C PREROUTING -i "${'$'}WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null; then + echo "Маршрут обычного TCP-трафика WDTT через внешний прокси: применён" + else + echo "Маршрут обычного TCP-трафика WDTT через внешний прокси: отсутствует" + fi + if systemctl is-active wdtt-wg-exit.service >/dev/null 2>&1; then echo "Служба WireGuard-выхода: запущена"; else echo "Служба WireGuard-выхода: остановлена"; fi + if systemctl is-enabled wdtt-wg-exit.service >/dev/null 2>&1; then echo "Автозапуск WireGuard-выхода: включён"; else echo "Автозапуск WireGuard-выхода: выключен"; fi + if ip rule show 2>/dev/null | grep -Eq "from [^ ]+ lookup ${'$'}WDTT_TABLE([[:space:]]|${'$'})|from [^ ]+ lookup wdtt-exit([[:space:]]|${'$'})"; then + echo "Правило маршрутизации подсети WDTT: применено" + else + echo "Правило маршрутизации подсети WDTT: отсутствует" + fi + if ip route show table "${'$'}WDTT_TABLE" 2>/dev/null | grep -Eq "^default([[:space:]].*)? dev ${'$'}WDTT_WG_IFACE([[:space:]]|${'$'})"; then + echo "Маршрут по умолчанию через WireGuard: применён" + else + echo "Маршрут по умолчанию через WireGuard: отсутствует" + fi + if command -v iptables >/dev/null 2>&1 && + iptables -t nat -S POSTROUTING 2>/dev/null | + grep -q -- "-o ${'$'}WDTT_WG_IFACE .*--comment WDTT_EXIT .*MASQUERADE"; then + echo "NAT WireGuard-выхода для подсети WDTT: применён" + else + echo "NAT WireGuard-выхода для подсети WDTT: отсутствует" + fi if command -v wg >/dev/null 2>&1 && wg show "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1; then echo "WireGuard ${'$'}WDTT_WG_IFACE:" wg show "${'$'}WDTT_WG_IFACE" | sed -E 's/(private key: ).*/\1(скрыт)/' @@ -5542,9 +6159,13 @@ private fun outboundProfileSaveScript(forms: OutboundProfileForms): String { b64Line("WG_VPS_HOST_B64", forms.wireGuardExitHost), line("WG_VPS_SSH_PORT", port(forms.wireGuardExitSshPort)), b64Line("WG_VPS_USER_B64", forms.wireGuardExitUser), - b64Line("WG_VPS_PASSWORD_B64", forms.wireGuardExitPassword), + // SSH-пароль второго VPS нужен только во время настройки. Не оставляем + // root-доступ к нему на основном сервере. + b64Line("WG_VPS_PASSWORD_B64", ""), line("WG_VPS_PORT", port(forms.wireGuardExitPort)), - b64Line("WG_VPS_DNS_B64", forms.wireGuardExitDns), + // DNS для клиентов задаётся в основных настройках WDTT, а не в + // policy-routed WireGuard-выходе. + b64Line("WG_VPS_DNS_B64", ""), b64Line("IMPORTED_WG_CONFIG_B64", forms.importedWireGuardConfig) ).joinToString("\n") val profileScript = """ @@ -5587,7 +6208,7 @@ private suspend fun saveOutboundProfileMessage( } ) -private fun outboundSnapshotScript(): String = shellScript( +internal fun outboundSnapshotScript(): String = shellScript( outboundReadPrelude(), """ PROFILE_FILE=/etc/wdtt/outbound-profile.env @@ -5596,6 +6217,10 @@ private fun outboundSnapshotScript(): String = shellScript( [ -f "${'$'}PROFILE_FILE" ] || return 0 grep -E "^${'$'}key=" "${'$'}PROFILE_FILE" 2>/dev/null | tail -n 1 | sed 's/^[^=]*=//' } + wdtt_profile_has_key() { + key="${'$'}1" + [ -f "${'$'}PROFILE_FILE" ] && grep -q -E "^${'$'}key=" "${'$'}PROFILE_FILE" 2>/dev/null + } wdtt_b64() { command -v base64 >/dev/null 2>&1 || return 0 printf '%s' "${'$'}1" | base64 | tr -d '\n' @@ -5650,22 +6275,43 @@ private fun outboundSnapshotScript(): String = shellScript( LOCAL_PRESENT=1 fi if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet wdtt-3proxy 2>/dev/null; then - LOCAL_ACTIVE=1 + LOCAL_SERVICE_ACTIVE=1 LOCAL_PRESENT=1 else - LOCAL_ACTIVE=0 + LOCAL_SERVICE_ACTIVE=0 fi - LOCAL_PORT="${'$'}(wdtt_profile_value LOCAL_PROXY_PORT)" - [ -n "${'$'}LOCAL_PORT" ] || LOCAL_PORT="${'$'}(wdtt_json_number /etc/wdtt/local-proxy.json socks5Port)" - [ -n "${'$'}LOCAL_PORT" ] || LOCAL_PORT="${'$'}(wdtt_3proxy_port)" - LOCAL_LOGIN_B64="${'$'}(wdtt_profile_value LOCAL_PROXY_LOGIN_B64)" - if [ -z "${'$'}LOCAL_LOGIN_B64" ]; then + if command -v systemctl >/dev/null 2>&1 && systemctl is-enabled --quiet wdtt-3proxy 2>/dev/null; then + LOCAL_SERVICE_ENABLED=1 + else + LOCAL_SERVICE_ENABLED=0 + fi + if wdtt_profile_has_key LOCAL_PROXY_PORT; then + LOCAL_PORT="${'$'}(wdtt_profile_value LOCAL_PROXY_PORT)" + else + LOCAL_PORT="${'$'}(wdtt_json_number /etc/wdtt/local-proxy.json socks5Port)" + [ -n "${'$'}LOCAL_PORT" ] || LOCAL_PORT="${'$'}(wdtt_3proxy_port)" + fi + LOCAL_ACTIVE="${'$'}LOCAL_SERVICE_ACTIVE" + case "${'$'}LOCAL_PORT" in + ''|*[!0-9]*) LOCAL_ACTIVE=0;; + *) + if [ "${'$'}LOCAL_SERVICE_ACTIVE" = 1 ] && + command -v ss >/dev/null 2>&1 && + ! ss -ltn 2>/dev/null | awk '{print ${'$'}4}' | grep -Eq ":${'$'}LOCAL_PORT${'$'}"; then + LOCAL_ACTIVE=0 + fi + ;; + esac + if wdtt_profile_has_key LOCAL_PROXY_LOGIN_B64; then + LOCAL_LOGIN_B64="${'$'}(wdtt_profile_value LOCAL_PROXY_LOGIN_B64)" + else LOCAL_LOGIN="${'$'}(wdtt_json_string /etc/wdtt/local-proxy.json login)" [ -n "${'$'}LOCAL_LOGIN" ] || LOCAL_LOGIN="${'$'}(wdtt_3proxy_login)" LOCAL_LOGIN_B64="${'$'}(wdtt_b64 "${'$'}LOCAL_LOGIN")" fi - LOCAL_PASSWORD_B64="${'$'}(wdtt_profile_value LOCAL_PROXY_PASSWORD_B64)" - if [ -z "${'$'}LOCAL_PASSWORD_B64" ]; then + if wdtt_profile_has_key LOCAL_PROXY_PASSWORD_B64; then + LOCAL_PASSWORD_B64="${'$'}(wdtt_profile_value LOCAL_PROXY_PASSWORD_B64)" + else LOCAL_PASSWORD="${'$'}(wdtt_json_string /etc/wdtt/local-proxy.json password)" [ -n "${'$'}LOCAL_PASSWORD" ] || LOCAL_PASSWORD="${'$'}(wdtt_3proxy_password)" LOCAL_PASSWORD_B64="${'$'}(wdtt_b64 "${'$'}LOCAL_PASSWORD")" @@ -5688,36 +6334,66 @@ private fun outboundSnapshotScript(): String = shellScript( socks5) REDSOCKS_KIND="Socks5";; http|http-connect) REDSOCKS_KIND="Http";; esac - EXTERNAL_KIND="${'$'}(wdtt_profile_value EXTERNAL_PROXY_KIND)" - if [ -z "${'$'}EXTERNAL_KIND" ]; then + if wdtt_profile_has_key EXTERNAL_PROXY_KIND; then + EXTERNAL_KIND="${'$'}(wdtt_profile_value EXTERNAL_PROXY_KIND)" + else case "${'$'}DETAIL_KIND" in socks5) EXTERNAL_KIND="Socks5";; http) EXTERNAL_KIND="Http";; *) EXTERNAL_KIND="${'$'}REDSOCKS_KIND";; esac fi - EXTERNAL_HOST_B64="${'$'}(wdtt_profile_value EXTERNAL_PROXY_HOST_B64)" - if [ -z "${'$'}EXTERNAL_HOST_B64" ]; then + if wdtt_profile_has_key EXTERNAL_PROXY_HOST_B64; then + EXTERNAL_HOST_B64="${'$'}(wdtt_profile_value EXTERNAL_PROXY_HOST_B64)" + else EXTERNAL_HOST="${'$'}DETAIL_HOST" [ -n "${'$'}EXTERNAL_HOST" ] || EXTERNAL_HOST="${'$'}(wdtt_redsocks_value ip)" EXTERNAL_HOST_B64="${'$'}(wdtt_b64 "${'$'}EXTERNAL_HOST")" fi - EXTERNAL_PORT="${'$'}(wdtt_profile_value EXTERNAL_PROXY_PORT)" - [ -n "${'$'}EXTERNAL_PORT" ] || EXTERNAL_PORT="${'$'}DETAIL_PORT" - [ -n "${'$'}EXTERNAL_PORT" ] || EXTERNAL_PORT="${'$'}(wdtt_redsocks_value port)" - EXTERNAL_LOGIN_B64="${'$'}(wdtt_profile_value EXTERNAL_PROXY_LOGIN_B64)" - [ -n "${'$'}EXTERNAL_LOGIN_B64" ] || EXTERNAL_LOGIN_B64="${'$'}(wdtt_b64 "$(wdtt_redsocks_value login)")" - EXTERNAL_PASSWORD_B64="${'$'}(wdtt_profile_value EXTERNAL_PROXY_PASSWORD_B64)" - [ -n "${'$'}EXTERNAL_PASSWORD_B64" ] || EXTERNAL_PASSWORD_B64="${'$'}(wdtt_b64 "$(wdtt_redsocks_value password)")" + if wdtt_profile_has_key EXTERNAL_PROXY_PORT; then + EXTERNAL_PORT="${'$'}(wdtt_profile_value EXTERNAL_PROXY_PORT)" + else + EXTERNAL_PORT="${'$'}DETAIL_PORT" + [ -n "${'$'}EXTERNAL_PORT" ] || EXTERNAL_PORT="${'$'}(wdtt_redsocks_value port)" + fi + if wdtt_profile_has_key EXTERNAL_PROXY_LOGIN_B64; then + EXTERNAL_LOGIN_B64="${'$'}(wdtt_profile_value EXTERNAL_PROXY_LOGIN_B64)" + else + EXTERNAL_LOGIN_B64="${'$'}(wdtt_b64 "$(wdtt_redsocks_value login)")" + fi + if wdtt_profile_has_key EXTERNAL_PROXY_PASSWORD_B64; then + EXTERNAL_PASSWORD_B64="${'$'}(wdtt_profile_value EXTERNAL_PROXY_PASSWORD_B64)" + else + EXTERNAL_PASSWORD_B64="${'$'}(wdtt_b64 "$(wdtt_redsocks_value password)")" + fi EXTERNAL_PRESENT=0 - if [ -f /etc/wdtt/redsocks.conf ] || [ "${'$'}MODE" = "external_proxy" ] || [ -n "${'$'}EXTERNAL_HOST_B64" ] || [ -n "${'$'}EXTERNAL_PORT" ]; then + if [ -f /etc/wdtt/redsocks.conf ] || [ "${'$'}MODE" = "external_proxy" ] || [ -n "${'$'}EXTERNAL_HOST_B64" ]; then EXTERNAL_PRESENT=1 fi if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet wdtt-redsocks 2>/dev/null; then - EXTERNAL_ACTIVE=1 + EXTERNAL_SERVICE_ACTIVE=1 EXTERNAL_PRESENT=1 + if command -v ss >/dev/null 2>&1 && + ! ss -ltn 2>/dev/null | awk '{print ${'$'}4}' | grep -Eq ':12345${'$'}'; then + EXTERNAL_SERVICE_ACTIVE=0 + fi else - EXTERNAL_ACTIVE=0 + EXTERNAL_SERVICE_ACTIVE=0 + fi + if command -v systemctl >/dev/null 2>&1 && systemctl is-enabled --quiet wdtt-redsocks 2>/dev/null; then + EXTERNAL_SERVICE_ENABLED=1 + else + EXTERNAL_SERVICE_ENABLED=0 + fi + EXTERNAL_ROUTE_ACTIVE=0 + if command -v iptables >/dev/null 2>&1 && + iptables -t nat -C PREROUTING -i "${'$'}WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null && + iptables -t nat -S WDTT_PROXY_OUT 2>/dev/null | grep -q -- '--to-ports 12345'; then + EXTERNAL_ROUTE_ACTIVE=1 + fi + EXTERNAL_ACTIVE=0 + if [ "${'$'}EXTERNAL_SERVICE_ACTIVE" = 1 ] && [ "${'$'}EXTERNAL_ROUTE_ACTIVE" = 1 ]; then + EXTERNAL_ACTIVE=1 fi WG_CONF="" @@ -5726,11 +6402,52 @@ private fun outboundSnapshotScript(): String = shellScript( WG_PRESENT=0 [ -n "${'$'}WG_CONF" ] && WG_PRESENT=1 if command -v wg >/dev/null 2>&1 && wg show "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1; then - WG_ACTIVE=1 + WG_INTERFACE_ACTIVE=1 WG_PRESENT=1 else - WG_ACTIVE=0 + WG_INTERFACE_ACTIVE=0 fi + if command -v systemctl >/dev/null 2>&1 && + systemctl is-active --quiet wdtt-wg-exit.service 2>/dev/null; then + WG_SERVICE_ACTIVE=1 + else + WG_SERVICE_ACTIVE=0 + fi + if command -v systemctl >/dev/null 2>&1 && + systemctl is-enabled --quiet wdtt-wg-exit.service 2>/dev/null; then + WG_SERVICE_ENABLED=1 + else + WG_SERVICE_ENABLED=0 + fi + WG_POLICY_RULE_ACTIVE=0 + ip rule show 2>/dev/null | grep -Eq "from [^ ]+ lookup ${'$'}WDTT_TABLE([[:space:]]|${'$'})|from [^ ]+ lookup wdtt-exit([[:space:]]|${'$'})" && + WG_POLICY_RULE_ACTIVE=1 + WG_DEFAULT_ROUTE_ACTIVE=0 + ip route show table "${'$'}WDTT_TABLE" 2>/dev/null | grep -Eq "^default([[:space:]].*)? dev ${'$'}WDTT_WG_IFACE([[:space:]]|${'$'})" && + WG_DEFAULT_ROUTE_ACTIVE=1 + WG_NAT_ACTIVE=0 + if command -v iptables >/dev/null 2>&1 && + iptables -t nat -S POSTROUTING 2>/dev/null | + grep -q -- "-o ${'$'}WDTT_WG_IFACE .*--comment WDTT_EXIT .*MASQUERADE"; then + WG_NAT_ACTIVE=1 + fi + WG_ACTIVE=0 + if [ "${'$'}WG_INTERFACE_ACTIVE" = 1 ] && + [ "${'$'}WG_POLICY_RULE_ACTIVE" = 1 ] && + [ "${'$'}WG_DEFAULT_ROUTE_ACTIVE" = 1 ] && + [ "${'$'}WG_NAT_ACTIVE" = 1 ]; then + WG_ACTIVE=1 + fi + WG_OWNER_MODE="${'$'}(cat "${'$'}WDTT_WG_OWNER_FILE" 2>/dev/null | head -n 1)" + case "${'$'}WG_OWNER_MODE" in + wireguard_vps|warp_free|imported_wg) ;; + *) WG_OWNER_MODE="";; + esac + WG_CONFIG_OWNER_MODE="${'$'}(cat "${'$'}WDTT_WG_CONFIG_OWNER_FILE" 2>/dev/null | head -n 1)" + case "${'$'}WG_CONFIG_OWNER_MODE" in + wireguard_vps|warp_free|imported_wg) ;; + *) WG_CONFIG_OWNER_MODE="";; + esac WG_ENDPOINT="" WG_DNS="" WG_MTU="" @@ -5747,27 +6464,52 @@ private fun outboundSnapshotScript(): String = shellScript( WG_ENDPOINT_HOST="${'$'}{WG_ENDPOINT_HOST#[}" WG_ENDPOINT_HOST="${'$'}{WG_ENDPOINT_HOST%]}" fi - WG_VPS_HOST_B64="${'$'}(wdtt_profile_value WG_VPS_HOST_B64)" - [ -n "${'$'}WG_VPS_HOST_B64" ] || WG_VPS_HOST_B64="${'$'}(wdtt_b64 "${'$'}WG_ENDPOINT_HOST")" + if wdtt_profile_has_key WG_VPS_HOST_B64; then + WG_VPS_HOST_B64="${'$'}(wdtt_profile_value WG_VPS_HOST_B64)" + elif [ "${'$'}MODE" = "wireguard_vps" ]; then + WG_VPS_HOST_B64="${'$'}(wdtt_b64 "${'$'}WG_ENDPOINT_HOST")" + else + WG_VPS_HOST_B64="" + fi WG_VPS_SSH_PORT="${'$'}(wdtt_profile_value WG_VPS_SSH_PORT)" WG_VPS_USER_B64="${'$'}(wdtt_profile_value WG_VPS_USER_B64)" WG_VPS_PASSWORD_B64="${'$'}(wdtt_profile_value WG_VPS_PASSWORD_B64)" - WG_VPS_PORT="${'$'}(wdtt_profile_value WG_VPS_PORT)" - [ -n "${'$'}WG_VPS_PORT" ] || WG_VPS_PORT="${'$'}WG_ENDPOINT_PORT" - WG_VPS_DNS_B64="${'$'}(wdtt_profile_value WG_VPS_DNS_B64)" - [ -n "${'$'}WG_VPS_DNS_B64" ] || WG_VPS_DNS_B64="${'$'}(wdtt_b64 "${'$'}WG_DNS")" - if [ -n "${'$'}WG_VPS_HOST_B64" ] || [ -n "${'$'}WG_VPS_PORT" ]; then + if wdtt_profile_has_key WG_VPS_PORT; then + WG_VPS_PORT="${'$'}(wdtt_profile_value WG_VPS_PORT)" + elif [ "${'$'}MODE" = "wireguard_vps" ]; then + WG_VPS_PORT="${'$'}WG_ENDPOINT_PORT" + else + WG_VPS_PORT="" + fi + if wdtt_profile_has_key WG_VPS_DNS_B64; then + WG_VPS_DNS_B64="${'$'}(wdtt_profile_value WG_VPS_DNS_B64)" + elif [ "${'$'}MODE" = "wireguard_vps" ]; then + WG_VPS_DNS_B64="${'$'}(wdtt_b64 "${'$'}WG_DNS")" + else + WG_VPS_DNS_B64="" + fi + if [ -n "${'$'}WG_VPS_HOST_B64" ]; then WG_PRESENT=1 fi IMPORTED_WG_CONFIG_B64="${'$'}(wdtt_profile_value IMPORTED_WG_CONFIG_B64)" - if [ "${'$'}MODE" = "imported_wg" ] && [ -z "${'$'}IMPORTED_WG_CONFIG_B64" ] && [ -n "${'$'}WG_CONF" ]; then + if [ "${'$'}MODE" = "imported_wg" ] && ! wdtt_profile_has_key IMPORTED_WG_CONFIG_B64 && [ -n "${'$'}WG_CONF" ]; then IMPORTED_WG_CONFIG_B64="${'$'}(wdtt_file_b64 "${'$'}WG_CONF")" fi [ -n "${'$'}IMPORTED_WG_CONFIG_B64" ] && WG_PRESENT=1 WARP_PRESENT=0 - if [ -f /etc/wdtt-plus/warp/wgcf-account.toml ] || [ -f /etc/wdtt-plus/warp/wgcf-profile.conf ]; then + if [ -d /etc/wdtt-plus/warp ] || + [ -f /usr/local/bin/wgcf ] || + [ -f /usr/local/lib/wdtt/warp-watchdog ] || + [ -f /etc/systemd/system/wdtt-warp-watchdog.service ] || + [ -f /etc/systemd/system/wdtt-warp-watchdog.timer ]; then WARP_PRESENT=1 fi + WG_MATCHES_WARP=0 + if [ -n "${'$'}WG_CONF" ] && + [ -f /etc/wdtt-plus/warp/wgcf-profile.conf ] && + cmp -s "${'$'}WG_CONF" /etc/wdtt-plus/warp/wgcf-profile.conf; then + WG_MATCHES_WARP=1 + fi printf 'WDTT_OUTBOUND_MODE=%s\n' "${'$'}MODE" printf 'WDTT_OUTBOUND_DETAIL_B64=%s\n' "$(wdtt_b64 "${'$'}DETAIL")" @@ -5775,11 +6517,15 @@ private fun outboundSnapshotScript(): String = shellScript( printf 'WDTT_HAS_PROFILE=%s\n' "${'$'}HAS_PROFILE" printf 'WDTT_LOCAL_PROXY_PRESENT=%s\n' "${'$'}LOCAL_PRESENT" printf 'WDTT_LOCAL_PROXY_ACTIVE=%s\n' "${'$'}LOCAL_ACTIVE" + printf 'WDTT_LOCAL_PROXY_SERVICE_ENABLED=%s\n' "${'$'}LOCAL_SERVICE_ENABLED" printf 'WDTT_LOCAL_PROXY_PORT=%s\n' "${'$'}LOCAL_PORT" printf 'WDTT_LOCAL_PROXY_LOGIN_B64=%s\n' "${'$'}LOCAL_LOGIN_B64" printf 'WDTT_LOCAL_PROXY_PASSWORD_B64=%s\n' "${'$'}LOCAL_PASSWORD_B64" printf 'WDTT_EXTERNAL_PROXY_PRESENT=%s\n' "${'$'}EXTERNAL_PRESENT" printf 'WDTT_EXTERNAL_PROXY_ACTIVE=%s\n' "${'$'}EXTERNAL_ACTIVE" + printf 'WDTT_EXTERNAL_PROXY_SERVICE_ACTIVE=%s\n' "${'$'}EXTERNAL_SERVICE_ACTIVE" + printf 'WDTT_EXTERNAL_PROXY_SERVICE_ENABLED=%s\n' "${'$'}EXTERNAL_SERVICE_ENABLED" + printf 'WDTT_EXTERNAL_PROXY_ROUTE_ACTIVE=%s\n' "${'$'}EXTERNAL_ROUTE_ACTIVE" printf 'WDTT_EXTERNAL_PROXY_KIND_NAME=%s\n' "${'$'}EXTERNAL_KIND" printf 'WDTT_EXTERNAL_PROXY_HOST_B64=%s\n' "${'$'}EXTERNAL_HOST_B64" printf 'WDTT_EXTERNAL_PROXY_PORT=%s\n' "${'$'}EXTERNAL_PORT" @@ -5787,6 +6533,15 @@ private fun outboundSnapshotScript(): String = shellScript( printf 'WDTT_EXTERNAL_PROXY_PASSWORD_B64=%s\n' "${'$'}EXTERNAL_PASSWORD_B64" printf 'WDTT_WG_PRESENT=%s\n' "${'$'}WG_PRESENT" printf 'WDTT_WG_ACTIVE=%s\n' "${'$'}WG_ACTIVE" + printf 'WDTT_WG_INTERFACE_ACTIVE=%s\n' "${'$'}WG_INTERFACE_ACTIVE" + printf 'WDTT_WG_SERVICE_ACTIVE=%s\n' "${'$'}WG_SERVICE_ACTIVE" + printf 'WDTT_WG_SERVICE_ENABLED=%s\n' "${'$'}WG_SERVICE_ENABLED" + printf 'WDTT_WG_POLICY_RULE_ACTIVE=%s\n' "${'$'}WG_POLICY_RULE_ACTIVE" + printf 'WDTT_WG_DEFAULT_ROUTE_ACTIVE=%s\n' "${'$'}WG_DEFAULT_ROUTE_ACTIVE" + printf 'WDTT_WG_NAT_ACTIVE=%s\n' "${'$'}WG_NAT_ACTIVE" + printf 'WDTT_WG_OWNER_MODE=%s\n' "${'$'}WG_OWNER_MODE" + printf 'WDTT_WG_CONFIG_OWNER_MODE=%s\n' "${'$'}WG_CONFIG_OWNER_MODE" + printf 'WDTT_WG_MATCHES_WARP=%s\n' "${'$'}WG_MATCHES_WARP" printf 'WDTT_WG_VPS_HOST_B64=%s\n' "${'$'}WG_VPS_HOST_B64" printf 'WDTT_WG_VPS_SSH_PORT=%s\n' "${'$'}WG_VPS_SSH_PORT" printf 'WDTT_WG_VPS_USER_B64=%s\n' "${'$'}WG_VPS_USER_B64" @@ -5849,7 +6604,20 @@ private fun parseOutboundServerSnapshot(output: String): OutboundServerSnapshot wireGuardExitDns = decoded("WDTT_WG_VPS_DNS_B64"), warpPresent = flag("WDTT_WARP_PRESENT"), warpMtu = value("WDTT_WARP_MTU"), - importedWireGuardConfig = decoded("WDTT_IMPORTED_WG_CONFIG_B64") + importedWireGuardConfig = decoded("WDTT_IMPORTED_WG_CONFIG_B64"), + externalProxyServiceActive = flag("WDTT_EXTERNAL_PROXY_SERVICE_ACTIVE"), + externalProxyRouteActive = flag("WDTT_EXTERNAL_PROXY_ROUTE_ACTIVE"), + wireGuardInterfaceActive = flag("WDTT_WG_INTERFACE_ACTIVE"), + wireGuardServiceActive = flag("WDTT_WG_SERVICE_ACTIVE"), + wireGuardPolicyRuleActive = flag("WDTT_WG_POLICY_RULE_ACTIVE"), + wireGuardDefaultRouteActive = flag("WDTT_WG_DEFAULT_ROUTE_ACTIVE"), + wireGuardNatActive = flag("WDTT_WG_NAT_ACTIVE"), + wireGuardOwnerMode = value("WDTT_WG_OWNER_MODE"), + wireGuardConfigOwnerMode = value("WDTT_WG_CONFIG_OWNER_MODE"), + wireGuardMatchesWarp = flag("WDTT_WG_MATCHES_WARP"), + localProxyServiceEnabled = flag("WDTT_LOCAL_PROXY_SERVICE_ENABLED"), + externalProxyServiceEnabled = flag("WDTT_EXTERNAL_PROXY_SERVICE_ENABLED"), + wireGuardServiceEnabled = flag("WDTT_WG_SERVICE_ENABLED") ) } @@ -5859,7 +6627,7 @@ private fun outboundRestoreSummary(snapshot: OutboundServerSnapshot): String { parts += "Активный режим: ${snapshot.modeLabel}." if (snapshot.hasProfile) parts += "Сохранённый профиль найден." if (snapshot.localProxyPresent) { - parts += if (snapshot.localProxyActive) "Прокси VPS найден и запущен." else "Прокси VPS найден, служба не запущена." + parts += if (snapshot.localProxyActive) "Прокси на этом VPS найден и запущен." else "Прокси на этом VPS найден, служба не запущена." } if (snapshot.externalProxyPresent) { parts += if (snapshot.externalProxyActive) "Внешний TCP-прокси включён." else "Поля внешнего TCP-прокси заполнены." @@ -6006,26 +6774,43 @@ private suspend fun readOutboundDiagnostics(target: OutboundSshTarget): String = } } +internal fun disableOutboundExitScript(): String = shellScript( + outboundShellPrelude(), + """ + echo "WDTT_PROGRESS|0.25|Останавливаю внешний TCP-прокси и WireGuard-выход, если они включены..." + wdtt_clear_external_out + if command -v wg >/dev/null 2>&1 && wg show "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1; then + ip link delete "${'$'}WDTT_WG_IFACE" 2>/dev/null || true + fi + while ip rule del from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TABLE" priority 100 2>/dev/null; do :; done + ip route flush table "${'$'}WDTT_TABLE" 2>/dev/null || true + CLEANUP_LEFT=0 + (command -v wg >/dev/null 2>&1 && wg show "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1) && CLEANUP_LEFT=1 + systemctl is-active --quiet wdtt-wg-exit.service 2>/dev/null && CLEANUP_LEFT=1 + systemctl is-active --quiet wdtt-redsocks.service 2>/dev/null && CLEANUP_LEFT=1 + ip rule show 2>/dev/null | grep -Eq "from [^ ]+ lookup ${'$'}WDTT_TABLE([[:space:]]|${'$'})|from [^ ]+ lookup wdtt-exit([[:space:]]|${'$'})" && + CLEANUP_LEFT=1 + ip route show table "${'$'}WDTT_TABLE" 2>/dev/null | grep -Eq "^default([[:space:]].*)? dev ${'$'}WDTT_WG_IFACE([[:space:]]|${'$'})" && + CLEANUP_LEFT=1 + if command -v iptables >/dev/null 2>&1; then + iptables -t nat -S PREROUTING 2>/dev/null | grep -q -- "-i ${'$'}WDTT_IFACE .* -j WDTT_PROXY_OUT" && + CLEANUP_LEFT=1 + iptables -t nat -S POSTROUTING 2>/dev/null | grep -q -- "-o ${'$'}WDTT_WG_IFACE .*--comment WDTT_EXIT .*MASQUERADE" && + CLEANUP_LEFT=1 + fi + if [ "${'$'}CLEANUP_LEFT" != 0 ]; then + echo WDTT_ERROR=direct_cleanup_failed + exit 3 + fi + echo "WDTT_PROGRESS|0.75|Сохраняю режим прямого выхода через текущий сервер..." + wdtt_write_mode "direct" "прямой выход" + echo "WDTT_PROGRESS|1.0|Прямой выход включён." + echo "Внешний TCP-прокси или WireGuard-выход отключён. WDTT-пользователи снова идут напрямую через текущий сервер." + """ +) + private suspend fun disableOutboundExit(target: OutboundSshTarget): String = withContext(Dispatchers.IO) { - var session: Session? = null - try { - session = createSshSession(target.host, target.user, target.credentials, target.port) - val ssh = SSHClient(session, target.pass) - val script = shellScript( - outboundShellPrelude(), - """ - echo "WDTT_PROGRESS|0.25|Останавливаю внешний TCP-прокси и WireGuard-выход, если они включены..." - wdtt_clear_external_out - echo "WDTT_PROGRESS|0.75|Сохраняю режим прямого выхода через текущий сервер..." - wdtt_write_mode "direct" "прямой выход" - echo "WDTT_PROGRESS|1.0|Прямой выход включён." - echo "Внешний TCP-прокси или WireGuard-выход отключён. WDTT-пользователи снова идут напрямую через текущий сервер." - """ - ) - ssh.exec(rootCommand(script), timeout = 30000L).trim() - } finally { - try { session?.disconnect() } catch (_: Exception) {} - } + runCheckedRootScript(target, disableOutboundExitScript(), timeout = 30000L) } private suspend fun installLocalProxy( @@ -6035,6 +6820,10 @@ private suspend fun installLocalProxy( login: String, proxyPassword: String ): String { + require(port in 1..65533) { "порт SOCKS5 должен быть от 1 до 65533" } + require(localProxyCredentialsIssue(login, proxyPassword) == null) { + localProxyCredentialsIssue(login, proxyPassword).orEmpty() + } val httpPort = (port + 1).coerceAtMost(65535) val script = shellScript( outboundShellPrelude(), @@ -6044,6 +6833,9 @@ private suspend fun installLocalProxy( ADMIN_PORT=${httpPort + 1} PROXY_LOGIN=${shellQuote(login)} PROXY_PASSWORD=${shellQuote(proxyPassword)} + THREEPROXY_VERSION=${shellQuote(THREEPROXY_VERSION)} + THREEPROXY_SOURCE_URL=${shellQuote(THREEPROXY_SOURCE_URL)} + THREEPROXY_SOURCE_SHA256=${shellQuote(THREEPROXY_SOURCE_SHA256)} wdtt_progress() { echo "WDTT_PROGRESS|${'$'}1|${'$'}2"; } install_pkg() { if command -v apt-get >/dev/null 2>&1; then @@ -6065,17 +6857,17 @@ private suspend fun installLocalProxy( } install_3proxy_build_deps() { if command -v apt-get >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc libc6-dev libssl-dev + install_pkg curl ca-certificates tar gzip make gcc coreutils libc6-dev libssl-dev libpcre2-dev elif command -v dnf >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc glibc-devel openssl-devel + install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel openssl-devel pcre2-devel elif command -v yum >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc glibc-devel openssl-devel + install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel openssl-devel pcre2-devel elif command -v zypper >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc glibc-devel libopenssl-devel + install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel libopenssl-devel pcre2-devel elif command -v apk >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc musl-dev linux-headers openssl-dev + install_pkg curl ca-certificates tar gzip make gcc coreutils musl-dev linux-headers openssl-dev pcre2-dev elif command -v pacman >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc glibc openssl + install_pkg curl ca-certificates tar gzip make gcc coreutils glibc openssl pcre2 else return 1 fi @@ -6084,36 +6876,47 @@ private suspend fun installLocalProxy( TMP_DIR="${'$'}(mktemp -d)" cleanup() { rm -rf "${'$'}TMP_DIR"; } trap cleanup EXIT - wdtt_progress 0.50 "Пакета 3proxy нет, готовлю сборку из исходников..." + wdtt_progress 0.50 "Готовлю проверенную сборку 3proxy из исходников..." install_3proxy_build_deps || true command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_curl; exit 2; } command -v tar >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_tar; exit 2; } command -v gzip >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_gzip; exit 2; } command -v make >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_make; exit 2; } + command -v sha256sum >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_sha256sum; exit 2; } (command -v gcc >/dev/null 2>&1 || command -v cc >/dev/null 2>&1) || { echo WDTT_ERROR=3proxy_source_no_compiler; exit 2; } [ -f /usr/include/openssl/evp.h ] || [ -f /usr/local/include/openssl/evp.h ] || { echo WDTT_ERROR=3proxy_source_no_openssl_headers; exit 2; } + [ -f /usr/include/pcre2.h ] || [ -f /usr/local/include/pcre2.h ] || { echo WDTT_ERROR=3proxy_source_no_pcre2_headers; exit 2; } cd "${'$'}TMP_DIR" - wdtt_progress 0.58 "Скачиваю исходники 3proxy..." - curl -fsSL -o 3proxy.tar.gz https://github.com/3proxy/3proxy/archive/refs/heads/master.tar.gz || { echo WDTT_ERROR=3proxy_source_download_failed; exit 2; } + wdtt_progress 0.58 "Скачиваю закреплённый выпуск 3proxy ${'$'}THREEPROXY_VERSION..." + curl -fsSL --retry 2 --connect-timeout 12 --max-time 180 \ + -o 3proxy.tar.gz "${'$'}THREEPROXY_SOURCE_URL" || + { echo WDTT_ERROR=3proxy_source_download_failed; exit 2; } + ACTUAL_SOURCE_SHA256="${'$'}(sha256sum 3proxy.tar.gz | awk '{print ${'$'}1}')" + [ "${'$'}ACTUAL_SOURCE_SHA256" = "${'$'}THREEPROXY_SOURCE_SHA256" ] || + { echo WDTT_ERROR=3proxy_source_checksum_failed; exit 2; } tar -xzf 3proxy.tar.gz || { echo WDTT_ERROR=3proxy_source_unpack_failed; exit 2; } - cd 3proxy-* + cd "3proxy-${'$'}THREEPROXY_VERSION" wdtt_progress 0.68 "Собираю 3proxy на сервере..." ln -sf Makefile.Linux Makefile make >/tmp/wdtt-3proxy-build.log 2>&1 || { echo WDTT_ERROR=3proxy_source_build_failed; tail -n 20 /tmp/wdtt-3proxy-build.log; exit 2; } BUILT_BIN="${'$'}(find . -type f -name 3proxy -perm -111 | head -n1)" [ -n "${'$'}BUILT_BIN" ] || { echo WDTT_ERROR=3proxy_source_binary_missing; exit 2; } install -m 755 "${'$'}BUILT_BIN" /usr/local/bin/3proxy || { echo WDTT_ERROR=3proxy_source_install_failed; exit 2; } + printf '%s\n' "${'$'}THREEPROXY_VERSION" >/etc/wdtt/3proxy-version + chmod 600 /etc/wdtt/3proxy-version } wdtt_progress 0.08 "Определяю систему и права..." command -v systemctl >/dev/null 2>&1 || { echo WDTT_ERROR=systemd_required; exit 2; } wdtt_progress 0.18 "Готовлю пакетный менеджер..." install_pkg curl ca-certificates || true - wdtt_progress 0.32 "Пробую установить 3proxy из репозитория..." - install_pkg 3proxy || true THREEPROXY_BIN="${'$'}(command -v 3proxy || true)" - if [ -z "${'$'}THREEPROXY_BIN" ]; then - install_3proxy_from_source || true + INSTALLED_THREEPROXY_VERSION="${'$'}(cat /etc/wdtt/3proxy-version 2>/dev/null || true)" + if [ -z "${'$'}THREEPROXY_BIN" ] || [ "${'$'}INSTALLED_THREEPROXY_VERSION" != "${'$'}THREEPROXY_VERSION" ]; then + wdtt_progress 0.32 "Устанавливаю закреплённый выпуск 3proxy ${'$'}THREEPROXY_VERSION..." + install_3proxy_from_source THREEPROXY_BIN="${'$'}(command -v 3proxy || true)" + else + wdtt_progress 0.50 "Закреплённый выпуск 3proxy ${'$'}THREEPROXY_VERSION уже установлен." fi [ -n "${'$'}THREEPROXY_BIN" ] || { echo WDTT_ERROR=3proxy_install_failed; exit 2; } wdtt_progress 0.76 "Пишу настройки SOCKS5 и HTTP..." @@ -6131,6 +6934,29 @@ private suspend fun installLocalProxy( admin -p${'$'}ADMIN_PORT -i0.0.0.0 EOF chmod 600 /etc/wdtt/3proxy.cfg + mkdir -p /usr/local/lib/wdtt + cat >/usr/local/lib/wdtt/local-proxy-firewall </dev/null 2>&1; then + iptables -S INPUT 2>/dev/null | grep 'WDTT_LOCAL_PROXY' | sed 's/^-A /iptables -D /' | + while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done + fi + } + if [ "${'$'}{action}" = down ]; then + cleanup + exit 0 + fi + [ "${'$'}{action}" = up ] || exit 2 + command -v iptables >/dev/null 2>&1 || exit 0 + cleanup + iptables -I INPUT -p tcp --dport $port -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT + iptables -I INPUT -p tcp --dport $httpPort -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT + iptables -I INPUT -p tcp --dport ${httpPort + 1} -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT + EOF + chmod 700 /usr/local/lib/wdtt/local-proxy-firewall wdtt_progress 0.82 "Настраиваю службу wdtt-3proxy..." cat >/etc/systemd/system/wdtt-3proxy.service </dev/null - systemctl is-active --quiet wdtt-3proxy || { echo WDTT_ERROR=local_proxy_service_inactive; exit 3; } - wdtt_progress 0.92 "Открываю порты в firewall, если он есть..." - if command -v iptables >/dev/null 2>&1; then - iptables -C INPUT -p tcp --dport "${'$'}PROXY_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "${'$'}PROXY_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT - iptables -C INPUT -p tcp --dport "${'$'}HTTP_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "${'$'}HTTP_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT - iptables -C INPUT -p tcp --dport "${'$'}ADMIN_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "${'$'}ADMIN_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT + if ! systemctl enable wdtt-3proxy >/dev/null || + ! systemctl restart wdtt-3proxy >/dev/null || + ! systemctl is-active --quiet wdtt-3proxy; then + systemctl disable --now wdtt-3proxy 2>/dev/null || true + echo WDTT_ERROR=local_proxy_service_inactive + exit 3 fi + wdtt_progress 0.92 "Открываю порты в firewall, если он есть..." + /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 --socks5-hostname "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD@127.0.0.1:${'$'}PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" - [ -n "${'$'}TEST_IP" ] || { echo WDTT_ERROR=local_proxy_check_failed; exit 3; } + TEST_IP="${'$'}(curl --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" --socks5-hostname "127.0.0.1:${'$'}PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" + [ -n "${'$'}TEST_IP" ] || + { systemctl 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 --socks5-hostname "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD@127.0.0.1:${'$'}PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" + IP="${'$'}(curl --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" --socks5-hostname "127.0.0.1:${'$'}PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" [ -n "${'$'}IP" ] || { echo WDTT_ERROR=local_proxy_check_failed; exit 3; } echo "WDTT_PROGRESS|1.0|Прокси отвечает." echo "Проверка успешна: SOCKS5 на 127.0.0.1:${'$'}PROXY_PORT отвечает с указанными логином и паролем. Выходной IP: ${'$'}IP" @@ -6210,53 +7045,65 @@ private suspend fun checkLocalProxy( return runRootScript(context, target, script, timeout = 30000L) } -private suspend fun stopLocalProxy(target: OutboundSshTarget): String = withContext(Dispatchers.IO) { - var session: Session? = null - try { - session = createSshSession(target.host, target.user, target.credentials, target.port) - val ssh = SSHClient(session, target.pass) - val script = """ - echo "WDTT_PROGRESS|0.35|Останавливаю службу прокси на этом сервере..." - systemctl stop wdtt-3proxy 2>/dev/null || true - echo "WDTT_PROGRESS|0.85|Проверяю, что прокси больше не запущен..." - if systemctl is-active --quiet wdtt-3proxy 2>/dev/null; then - echo WDTT_ERROR=local_proxy_service_still_active - exit 3 - fi - echo "WDTT_PROGRESS|1.0|Прокси остановлен." - echo "Прокси VPS остановлен. Настройки сохранены, его можно снова включить кнопкой «Установить»." - """.trimIndent() - ssh.exec(rootCommand(script), timeout = 20000L).trim() - } finally { - try { session?.disconnect() } catch (_: Exception) {} - } -} +internal fun stopLocalProxyScript(): String = """ + set -e + echo "WDTT_PROGRESS|0.35|Останавливаю службу прокси на этом сервере..." + systemctl disable --now wdtt-3proxy 2>/dev/null || systemctl stop wdtt-3proxy 2>/dev/null || true + echo "WDTT_PROGRESS|0.85|Проверяю, что прокси больше не запущен..." + if systemctl is-active --quiet wdtt-3proxy 2>/dev/null || + systemctl is-enabled --quiet wdtt-3proxy 2>/dev/null; then + echo WDTT_ERROR=local_proxy_service_still_active + exit 3 + fi + echo "WDTT_PROGRESS|1.0|Прокси остановлен." + echo "Прокси на этом VPS остановлен и убран из автозапуска. Настройки сохранены, его можно снова включить кнопкой «Установить»." +""".trimIndent() -private suspend fun removeLocalProxy(target: OutboundSshTarget): String = withContext(Dispatchers.IO) { - var session: Session? = null - try { - session = createSshSession(target.host, target.user, target.credentials, target.port) - val ssh = SSHClient(session, target.pass) - val script = shellScript( - """ - echo "WDTT_PROGRESS|0.25|Останавливаю службу прокси..." - systemctl disable --now wdtt-3proxy 2>/dev/null || true - echo "WDTT_PROGRESS|0.55|Удаляю файлы настроек прокси..." - rm -f /etc/systemd/system/wdtt-3proxy.service /etc/wdtt/3proxy.cfg /etc/wdtt/local-proxy.json - systemctl daemon-reload 2>/dev/null || true - echo "WDTT_PROGRESS|0.80|Удаляю правила доступа к портам прокси..." - if command -v iptables >/dev/null 2>&1; then - iptables -S INPUT 2>/dev/null | grep WDTT_LOCAL_PROXY | sed 's/^-A /iptables -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done - fi - echo "WDTT_PROGRESS|1.0|Прокси удалён." - echo "Прокси VPS удалён: служба, настройки и правила доступа к портам очищены." - """ - ) - ssh.exec(rootCommand(script), timeout = 30000L).trim() - } finally { - try { session?.disconnect() } catch (_: Exception) {} - } -} +private suspend fun stopLocalProxy(target: OutboundSshTarget): String = + runCheckedRootScript(target, stopLocalProxyScript(), timeout = 20000L) + +internal fun removeLocalProxyScript(): String = shellScript( + outboundShellPrelude(), + """ + echo "WDTT_PROGRESS|0.25|Останавливаю службу прокси..." + systemctl disable --now wdtt-3proxy 2>/dev/null || true + echo "WDTT_PROGRESS|0.55|Удаляю файлы настроек прокси..." + rm -f /etc/systemd/system/wdtt-3proxy.service /etc/wdtt/3proxy.cfg /etc/wdtt/local-proxy.json \ + /usr/local/lib/wdtt/local-proxy-firewall + systemctl daemon-reload 2>/dev/null || true + echo "WDTT_PROGRESS|0.80|Удаляю правила доступа к портам прокси..." + if command -v iptables >/dev/null 2>&1; then + iptables -S INPUT 2>/dev/null | grep WDTT_LOCAL_PROXY | sed 's/^-A /iptables -D /' | while read -r cmd; do ${'$'}cmd 2>/dev/null || true; done + fi + if [ -f /etc/wdtt/outbound-profile.env ]; then + tmp_profile=/etc/wdtt/outbound-profile.env.tmp + grep -Ev '^(LOCAL_PROXY_PORT|LOCAL_PROXY_LOGIN_B64|LOCAL_PROXY_PASSWORD_B64)=' \ + /etc/wdtt/outbound-profile.env >"${'$'}tmp_profile" 2>/dev/null || true + chmod 600 "${'$'}tmp_profile" + mv "${'$'}tmp_profile" /etc/wdtt/outbound-profile.env + fi + LOCAL_REMOVE_LEFT=0 + systemctl is-active --quiet wdtt-3proxy 2>/dev/null && LOCAL_REMOVE_LEFT=1 + systemctl is-enabled --quiet wdtt-3proxy 2>/dev/null && LOCAL_REMOVE_LEFT=1 + [ -e /etc/systemd/system/wdtt-3proxy.service ] && LOCAL_REMOVE_LEFT=1 + [ -e /etc/wdtt/3proxy.cfg ] && LOCAL_REMOVE_LEFT=1 + [ -e /etc/wdtt/local-proxy.json ] && LOCAL_REMOVE_LEFT=1 + [ -e /usr/local/lib/wdtt/local-proxy-firewall ] && LOCAL_REMOVE_LEFT=1 + if command -v iptables >/dev/null 2>&1 && + iptables -S INPUT 2>/dev/null | grep -q WDTT_LOCAL_PROXY; then + LOCAL_REMOVE_LEFT=1 + fi + if [ "${'$'}LOCAL_REMOVE_LEFT" != 0 ]; then + echo WDTT_ERROR=local_proxy_remove_failed + exit 3 + fi + echo "WDTT_PROGRESS|1.0|Прокси удалён." + echo "Прокси на этом VPS удалён: служба, настройки, сохранённые реквизиты и правила доступа к портам очищены." + """ +) + +private suspend fun removeLocalProxy(target: OutboundSshTarget): String = + runCheckedRootScript(target, removeLocalProxyScript(), timeout = 30000L) private suspend fun checkExternalProxy( context: Context, @@ -6267,15 +7114,25 @@ private suspend fun checkExternalProxy( login: String, proxyPassword: String ): String { + require(host.isValidPublicHost()) { "укажите домен или IPv4 внешнего прокси без схемы и порта" } + require(port in 1..65535) { "порт внешнего прокси должен быть от 1 до 65535" } + require(externalProxyCredentialsIssue(login, proxyPassword) == null) { + externalProxyCredentialsIssue(login, proxyPassword).orEmpty() + } val scheme = if (kind == ProxyKind.Socks5) "socks5h" else "http" - val auth = if (login.isNotBlank()) "${login}:${proxyPassword}@" else "" - val proxyUri = "$scheme://$auth$host:$port" + val proxyUri = "$scheme://$host:$port" val script = """ 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)} - IP="${'$'}(curl --proxy "${'$'}PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)" + PROXY_LOGIN=${shellQuote(login)} + PROXY_PASSWORD=${shellQuote(proxyPassword)} + if [ -n "${'$'}PROXY_LOGIN" ]; then + IP="${'$'}(curl --proxy "${'$'}PROXY_URI" --proxy-user "${'$'}PROXY_LOGIN:${'$'}PROXY_PASSWORD" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)" + else + IP="${'$'}(curl --proxy "${'$'}PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)" + fi [ -n "${'$'}IP" ] || { echo WDTT_ERROR=external_proxy_check_failed; exit 3; } echo "WDTT_PROGRESS|1.0|Внешний TCP-прокси отвечает." echo "Проверка успешна: ${kind.label} отвечает, сервер смог открыть проверочный сайт через него. IP через прокси: ${'$'}IP" @@ -6292,6 +7149,11 @@ private suspend fun enableExternalProxy( login: String, proxyPassword: String ): String { + require(host.isValidPublicHost()) { "укажите домен или IPv4 внешнего прокси без схемы и порта" } + require(port in 1..65535) { "порт внешнего прокси должен быть от 1 до 65535" } + require(externalProxyCredentialsIssue(login, proxyPassword) == null) { + externalProxyCredentialsIssue(login, proxyPassword).orEmpty() + } val redsocksType = if (kind == ProxyKind.Socks5) "socks5" else "http-connect" val script = shellScript( outboundShellPrelude(), @@ -6302,6 +7164,8 @@ private suspend fun enableExternalProxy( PROXY_PORT=$port PROXY_LOGIN=${shellQuote(login)} PROXY_PASSWORD=${shellQuote(proxyPassword)} + PROXY_LOGIN_CONFIG=${shellQuote(escapeRedsocksQuotedValue(login))} + PROXY_PASSWORD_CONFIG=${shellQuote(escapeRedsocksQuotedValue(proxyPassword))} wdtt_progress() { echo "WDTT_PROGRESS|${'$'}1|${'$'}2"; } wdtt_progress 0.12 "Готовлю компонент перенаправления через внешний TCP-прокси..." wdtt_install_redsocks_tools || true @@ -6332,23 +7196,52 @@ private suspend fun enableExternalProxy( type = ${'$'}REDSOCKS_TYPE; EOF if [ -n "${'$'}PROXY_LOGIN" ]; then - printf ' login = "%s";\n' "${'$'}PROXY_LOGIN" >>/etc/wdtt/redsocks.conf - printf ' password = "%s";\n' "${'$'}PROXY_PASSWORD" >>/etc/wdtt/redsocks.conf + printf ' login = "%s";\n' "${'$'}PROXY_LOGIN_CONFIG" >>/etc/wdtt/redsocks.conf + printf ' password = "%s";\n' "${'$'}PROXY_PASSWORD_CONFIG" >>/etc/wdtt/redsocks.conf fi cat >>/etc/wdtt/redsocks.conf </usr/local/lib/wdtt/redsocks-routes </dev/null; do :; done + iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true + iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true + } + if [ "${'$'}{action}" = down ]; then + cleanup + exit 0 + fi + [ "${'$'}{action}" = up ] || exit 2 + cleanup + iptables -t nat -N WDTT_PROXY_OUT + for net in 0.0.0.0/8 10.0.0.0/8 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 224.0.0.0/4 240.0.0.0/4; do + iptables -t nat -A WDTT_PROXY_OUT -d "${'$'}{net}" -j RETURN + done + [ -n "${'$'}{PROXY_IP}" ] && iptables -t nat -A WDTT_PROXY_OUT -d "${'$'}{PROXY_IP}" -j RETURN + iptables -t nat -A WDTT_PROXY_OUT -p tcp -j REDIRECT --to-ports 12345 + iptables -t nat -A PREROUTING -i "${'$'}{WDTT_IFACE}" -p tcp -j WDTT_PROXY_OUT + EOF + chmod 700 /usr/local/lib/wdtt/redsocks-routes wdtt_progress 0.76 "Настраиваю службу перенаправления WDTT..." cat >/etc/systemd/system/wdtt-redsocks.service </dev/null - systemctl is-active --quiet wdtt-redsocks || { echo WDTT_ERROR=external_proxy_service_inactive; journalctl -u wdtt-redsocks -n 30 --no-pager 2>/dev/null || true; exit 3; } + if ! systemctl enable wdtt-redsocks >/dev/null || + ! systemctl restart wdtt-redsocks >/dev/null || + ! systemctl is-active --quiet wdtt-redsocks; then + journalctl -u wdtt-redsocks -n 30 --no-pager 2>/dev/null || true + wdtt_clear_external_out + wdtt_write_mode "direct" "rollback after external proxy service error" + echo WDTT_ERROR=external_proxy_service_inactive + exit 3 + fi wdtt_progress 0.92 "Направляю обычные TCP-подключения WDTT через внешний TCP-прокси..." - iptables -t nat -N WDTT_PROXY_OUT 2>/dev/null || true - iptables -t nat -F WDTT_PROXY_OUT - wdtt_proxy_reserved_returns WDTT_PROXY_OUT "${'$'}PROXY_IP" - iptables -t nat -A WDTT_PROXY_OUT -p tcp -j REDIRECT --to-ports 12345 - iptables -t nat -C PREROUTING -i "${'$'}WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null || iptables -t nat -A PREROUTING -i "${'$'}WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT + /usr/local/lib/wdtt/redsocks-routes up || + { echo WDTT_ERROR=external_proxy_route_install_failed; wdtt_clear_external_out; wdtt_write_mode "direct" "rollback after external proxy route error"; exit 3; } wdtt_progress 0.96 "Проверяю путь WDTT через внешний TCP-прокси..." if ! wdtt_test_redsocks_path "${'$'}PROXY_IP"; then wdtt_clear_external_out @@ -6381,6 +7278,52 @@ private suspend fun enableExternalProxy( return runRootScript(context, target, script, timeout = CMD_TIMEOUT) } +internal fun deleteExternalProxyScript(): String = shellScript( + outboundShellPrelude(), + """ + MODE="${'$'}(sed -n 's/.*"outboundMode"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' /etc/wdtt/outbound.json 2>/dev/null | head -n 1)" + echo "WDTT_PROGRESS|0.25|Останавливаю внешний TCP-прокси..." + wdtt_clear_proxy_out + echo "WDTT_PROGRESS|0.55|Удаляю службу и настройки внешнего прокси..." + rm -f /etc/systemd/system/wdtt-redsocks.service \ + /etc/wdtt/redsocks.conf \ + /usr/local/lib/wdtt/redsocks-routes \ + /var/log/wdtt-redsocks.log \ + /run/wdtt-redsocks.pid + systemctl daemon-reload 2>/dev/null || true + if [ -f /etc/wdtt/outbound-profile.env ]; then + tmp_profile=/etc/wdtt/outbound-profile.env.tmp + grep -Ev '^(EXTERNAL_PROXY_KIND|EXTERNAL_PROXY_HOST_B64|EXTERNAL_PROXY_PORT|EXTERNAL_PROXY_LOGIN_B64|EXTERNAL_PROXY_PASSWORD_B64)=' \ + /etc/wdtt/outbound-profile.env >"${'$'}tmp_profile" 2>/dev/null || true + chmod 600 "${'$'}tmp_profile" + mv "${'$'}tmp_profile" /etc/wdtt/outbound-profile.env + fi + if [ "${'$'}MODE" = "external_proxy" ]; then + wdtt_write_mode "direct" "прямой выход" + fi + EXTERNAL_REMOVE_LEFT=0 + systemctl is-active --quiet wdtt-redsocks 2>/dev/null && EXTERNAL_REMOVE_LEFT=1 + systemctl is-enabled --quiet wdtt-redsocks 2>/dev/null && EXTERNAL_REMOVE_LEFT=1 + [ -e /etc/systemd/system/wdtt-redsocks.service ] && EXTERNAL_REMOVE_LEFT=1 + [ -e /etc/wdtt/redsocks.conf ] && EXTERNAL_REMOVE_LEFT=1 + [ -e /usr/local/lib/wdtt/redsocks-routes ] && EXTERNAL_REMOVE_LEFT=1 + if command -v iptables >/dev/null 2>&1 && + { iptables -t nat -S WDTT_PROXY_OUT >/dev/null 2>&1 || + iptables -t nat -S PREROUTING 2>/dev/null | grep -q -- "-i ${'$'}WDTT_IFACE .* -j WDTT_PROXY_OUT"; }; then + EXTERNAL_REMOVE_LEFT=1 + fi + if [ "${'$'}EXTERNAL_REMOVE_LEFT" != 0 ]; then + echo WDTT_ERROR=external_proxy_remove_failed + exit 3 + fi + echo "WDTT_PROGRESS|1.0|Настройки внешнего TCP-прокси удалены." + echo "Служба, конфигурация, сохранённые реквизиты и правила внешнего TCP-прокси удалены." + """ +) + +private suspend fun deleteExternalProxy(target: OutboundSshTarget): String = + runCheckedRootScript(target, deleteExternalProxyScript(), timeout = 30000L) + internal fun validateWireGuardConfigText(config: String): Result = runCatching { val raw = config.trim() require(raw.toByteArray(Charsets.UTF_8).size <= 64 * 1024) { "файл больше 64 КБ" } @@ -6487,7 +7430,11 @@ private fun wireGuardPolicyScript(mode: String, detail: String): String = shellS echo "WDTT_PROGRESS|0.72|Отключаю прежний внешний выход WDTT..." wdtt_clear_external_out echo "WDTT_PROGRESS|0.78|Создаю постоянную службу WireGuard-выхода..." - mkdir -p /usr/local/lib/wdtt + mkdir -p /usr/local/lib/wdtt /etc/wdtt-plus/wg-exit + printf '%s\n' ${shellQuote(mode)} >"${'$'}WDTT_WG_OWNER_FILE" + printf '%s\n' ${shellQuote(mode)} >"${'$'}WDTT_WG_CONFIG_OWNER_FILE" + chmod 600 "${'$'}WDTT_WG_OWNER_FILE" + chmod 600 "${'$'}WDTT_WG_CONFIG_OWNER_FILE" cat >/usr/local/lib/wdtt/wg-exit-up <<'WDTT_WG_UP' #!/bin/sh set -eu @@ -6496,6 +7443,19 @@ 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 + wdtt_wg_up_cleanup() { + status="${'$'}?" + trap - 0 + if [ "${'$'}status" -ne 0 ]; then + set +e + 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 + wg-quick down "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1 || ip link delete "${'$'}WDTT_WG_IFACE" 2>/dev/null + fi + exit "${'$'}status" + } + trap wdtt_wg_up_cleanup 0 wg-quick down "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1 || true wg-quick up "${'$'}WDTT_WG_IFACE" ip rule del from "${'$'}WDTT_SUBNET" table "${'$'}WDTT_TABLE" priority 100 2>/dev/null || true @@ -6503,6 +7463,7 @@ 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 + trap - 0 WDTT_WG_UP cat >/usr/local/lib/wdtt/wg-exit-down <<'WDTT_WG_DOWN' #!/bin/sh @@ -6534,8 +7495,21 @@ private fun wireGuardPolicyScript(mode: String, detail: String): String = shellS WDTT_WG_SERVICE systemctl daemon-reload echo "WDTT_PROGRESS|0.84|Поднимаю WireGuard-интерфейс и маршруты WDTT..." - systemctl enable --now wdtt-wg-exit.service >/dev/null - systemctl is-active --quiet wdtt-wg-exit.service || { echo WDTT_ERROR=wireguard_exit_service_inactive; exit 3; } + if ! systemctl enable --now wdtt-wg-exit.service >/tmp/wdtt-wg-exit-start.log 2>&1 || + ! systemctl is-active --quiet wdtt-wg-exit.service; then + echo "WireGuard-служба не запустилась; очищаю частично созданный интерфейс и маршруты." + tail -n 12 /tmp/wdtt-wg-exit-start.log 2>/dev/null || true + systemctl disable --now wdtt-wg-exit.service 2>/dev/null || true + /usr/local/lib/wdtt/wg-exit-down >/dev/null 2>&1 || true + ip link delete "${'$'}WDTT_WG_IFACE" 2>/dev/null || true + systemctl reset-failed wdtt-wg-exit.service 2>/dev/null || true + wdtt_write_mode "direct" "rollback after WireGuard service start error" + rm -f "${'$'}WDTT_WG_OWNER_FILE" + rm -f /tmp/wdtt-wg-exit-start.log + echo WDTT_ERROR=wireguard_exit_service_inactive + exit 3 + fi + rm -f /tmp/wdtt-wg-exit-start.log echo "WDTT_PROGRESS|0.95|Сохраняю новый режим выхода WDTT..." wdtt_write_mode ${shellQuote(mode)} ${shellQuote(detail)} sleep 1 @@ -7137,14 +8111,37 @@ private suspend fun resetFreeWarpRegistration(target: OutboundSshTarget): String """ WARP_DIR=/etc/wdtt-plus/warp MODE="${'$'}(sed -n 's/.*"outboundMode"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' /etc/wdtt/outbound.json 2>/dev/null | head -n 1)" + OWNER="${'$'}(cat "${'$'}WDTT_WG_OWNER_FILE" 2>/dev/null | head -n 1)" + CONFIG_OWNER="${'$'}(cat "${'$'}WDTT_WG_CONFIG_OWNER_FILE" 2>/dev/null | head -n 1)" + WARP_CONFIG_MATCH=0 + if [ -f /etc/wireguard/wg-wdtt-exit.conf ] && + [ -f "${'$'}WARP_DIR/wgcf-profile.conf" ] && + cmp -s /etc/wireguard/wg-wdtt-exit.conf "${'$'}WARP_DIR/wgcf-profile.conf"; then + WARP_CONFIG_MATCH=1 + fi + WARP_OWNS_CONFIG=0 + if [ "${'$'}CONFIG_OWNER" = "warp_free" ] || + { [ -z "${'$'}CONFIG_OWNER" ] && [ "${'$'}WARP_CONFIG_MATCH" = 1 ]; }; then + WARP_OWNS_CONFIG=1 + fi + WARP_OWNS_ACTIVE_WG=0 + if [ "${'$'}MODE" = "warp_free" ] || + { [ "${'$'}MODE" = "direct" ] && [ "${'$'}OWNER" = "warp_free" ]; } || + { [ "${'$'}MODE" = "direct" ] && [ -z "${'$'}OWNER" ] && [ "${'$'}WARP_CONFIG_MATCH" = 1 ]; }; then + WARP_OWNS_ACTIVE_WG=1 + fi echo "WDTT_PROGRESS|0.20|Останавливаю WARP и автопроверку..." systemctl disable --now wdtt-warp-watchdog.timer wdtt-warp-watchdog.service 2>/dev/null || true - if [ "${'$'}MODE" = "warp_free" ]; then + if [ "${'$'}MODE" = "warp_free" ] || [ "${'$'}WARP_OWNS_ACTIVE_WG" = 1 ]; then echo "WDTT_PROGRESS|0.45|Возвращаю прямой выход WDTT..." - wdtt_clear_external_out - rm -f /etc/wireguard/wg-wdtt-exit.conf /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf + wdtt_clear_wireguard_out wdtt_write_mode "direct" "WARP registration reset" fi + if [ "${'$'}WARP_OWNS_CONFIG" = 1 ]; then + rm -f /etc/wireguard/wg-wdtt-exit.conf \ + /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf \ + "${'$'}WDTT_WG_CONFIG_OWNER_FILE" + fi echo "WDTT_PROGRESS|0.75|Удаляю текущую регистрацию и профиль WARP..." mkdir -p "${'$'}WARP_DIR" rm -f "${'$'}WARP_DIR"/wgcf-account.toml "${'$'}WARP_DIR"/wgcf-account.toml.invalid-* \ @@ -7152,9 +8149,14 @@ private suspend fun resetFreeWarpRegistration(target: OutboundSshTarget): String "${'$'}WARP_DIR"/selected.env "${'$'}WARP_DIR"/health.env chmod 700 "${'$'}WARP_DIR" 2>/dev/null || true systemctl reset-failed wdtt-warp-watchdog.service wdtt-wg-exit.service 2>/dev/null || true + if [ -e "${'$'}WARP_DIR/wgcf-account.toml" ] || + [ -e "${'$'}WARP_DIR/wgcf-profile.conf" ]; then + echo WDTT_ERROR=warp_registration_reset_failed + exit 3 + fi echo "WDTT_PROGRESS|1.0|Регистрация WARP сброшена." echo "Текущая регистрация, ключи и профиль WARP удалены. Проверенный wgcf оставлен на сервере." - if [ "${'$'}MODE" = "warp_free" ]; then + if [ "${'$'}MODE" = "warp_free" ] || [ "${'$'}WARP_OWNS_ACTIVE_WG" = 1 ]; then echo "WDTT-пользователи снова выходят напрямую через текущий VPS. Для новой регистрации нажмите «Установить / восстановить»." else echo "Активный режим выхода WDTT не был WARP; он не изменён." @@ -7177,24 +8179,60 @@ private suspend fun deleteFreeWarp(target: OutboundSshTarget): String = withCont val script = shellScript( outboundShellPrelude(), """ + WARP_DIR=/etc/wdtt-plus/warp MODE="${'$'}(sed -n 's/.*"outboundMode"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' /etc/wdtt/outbound.json 2>/dev/null | head -n 1)" + OWNER="${'$'}(cat "${'$'}WDTT_WG_OWNER_FILE" 2>/dev/null | head -n 1)" + CONFIG_OWNER="${'$'}(cat "${'$'}WDTT_WG_CONFIG_OWNER_FILE" 2>/dev/null | head -n 1)" + WARP_CONFIG_MATCH=0 + if [ -f /etc/wireguard/wg-wdtt-exit.conf ] && + [ -f "${'$'}WARP_DIR/wgcf-profile.conf" ] && + cmp -s /etc/wireguard/wg-wdtt-exit.conf "${'$'}WARP_DIR/wgcf-profile.conf"; then + WARP_CONFIG_MATCH=1 + fi + WARP_OWNS_CONFIG=0 + if [ "${'$'}CONFIG_OWNER" = "warp_free" ] || + { [ -z "${'$'}CONFIG_OWNER" ] && [ "${'$'}WARP_CONFIG_MATCH" = 1 ]; }; then + WARP_OWNS_CONFIG=1 + fi + WARP_OWNS_ACTIVE_WG=0 + if [ "${'$'}MODE" = "warp_free" ] || + { [ "${'$'}MODE" = "direct" ] && [ "${'$'}OWNER" = "warp_free" ]; } || + { [ "${'$'}MODE" = "direct" ] && [ -z "${'$'}OWNER" ] && [ "${'$'}WARP_CONFIG_MATCH" = 1 ]; }; then + WARP_OWNS_ACTIVE_WG=1 + fi echo "WDTT_PROGRESS|0.20|Останавливаю автоматическую проверку WARP..." systemctl disable --now wdtt-warp-watchdog.timer wdtt-warp-watchdog.service 2>/dev/null || true - if [ "${'$'}MODE" = "warp_free" ]; then + if [ "${'$'}MODE" = "warp_free" ] || [ "${'$'}WARP_OWNS_ACTIVE_WG" = 1 ]; then echo "WDTT_PROGRESS|0.45|Возвращаю прямой выход WDTT..." - wdtt_clear_external_out - rm -f /etc/wireguard/wg-wdtt-exit.conf /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf + wdtt_clear_wireguard_out wdtt_write_mode "direct" "прямой выход" fi + if [ "${'$'}WARP_OWNS_CONFIG" = 1 ]; then + rm -f /etc/wireguard/wg-wdtt-exit.conf \ + /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf \ + "${'$'}WDTT_WG_CONFIG_OWNER_FILE" + fi echo "WDTT_PROGRESS|0.70|Удаляю регистрацию, ключи и профиль WARP..." - rm -rf /etc/wdtt-plus/warp + rm -rf "${'$'}WARP_DIR" rm -f /usr/local/bin/wgcf /usr/local/bin/wgcf.previous /usr/local/lib/wdtt/warp-watchdog rm -f /etc/systemd/system/wdtt-warp-watchdog.service /etc/systemd/system/wdtt-warp-watchdog.timer systemctl daemon-reload 2>/dev/null || true systemctl reset-failed wdtt-warp-watchdog.service 2>/dev/null || true + WARP_REMOVE_LEFT=0 + [ -e "${'$'}WARP_DIR" ] && WARP_REMOVE_LEFT=1 + [ -e /usr/local/bin/wgcf ] && WARP_REMOVE_LEFT=1 + [ -e /usr/local/lib/wdtt/warp-watchdog ] && WARP_REMOVE_LEFT=1 + [ -e /etc/systemd/system/wdtt-warp-watchdog.service ] && WARP_REMOVE_LEFT=1 + [ -e /etc/systemd/system/wdtt-warp-watchdog.timer ] && WARP_REMOVE_LEFT=1 + systemctl is-active --quiet wdtt-warp-watchdog.timer 2>/dev/null && WARP_REMOVE_LEFT=1 + systemctl is-enabled --quiet wdtt-warp-watchdog.timer 2>/dev/null && WARP_REMOVE_LEFT=1 + if [ "${'$'}WARP_REMOVE_LEFT" != 0 ]; then + echo WDTT_ERROR=warp_remove_failed + exit 3 + fi echo "WDTT_PROGRESS|1.0|Бесплатный WARP удалён." echo "Регистрация, ключи, профиль и автоматическая проверка WARP удалены с сервера." - if [ "${'$'}MODE" = "warp_free" ]; then + if [ "${'$'}MODE" = "warp_free" ] || [ "${'$'}WARP_OWNS_ACTIVE_WG" = 1 ]; then echo "WDTT-пользователи снова выходят напрямую через текущий VPS." else echo "Другой активный режим выхода не изменён." @@ -7244,33 +8282,237 @@ private suspend fun enableImportedWireGuardExit( } } -private suspend fun deleteImportedWireGuardExit(target: OutboundSshTarget): String = withContext(Dispatchers.IO) { - var session: Session? = null +internal fun deleteImportedWireGuardExitScript(): String = shellScript( + outboundShellPrelude(), + """ + MODE="${'$'}(sed -n 's/.*"outboundMode"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' /etc/wdtt/outbound.json 2>/dev/null | head -n 1)" + OWNER="${'$'}(cat "${'$'}WDTT_WG_OWNER_FILE" 2>/dev/null | head -n 1)" + CONFIG_OWNER="${'$'}(cat "${'$'}WDTT_WG_CONFIG_OWNER_FILE" 2>/dev/null | head -n 1)" + OWNS_ACTIVE=0 + OWNS_CONFIG=0 + if [ "${'$'}MODE" = "imported_wg" ] || + { [ "${'$'}MODE" = "direct" ] && [ "${'$'}OWNER" = "imported_wg" ]; }; then + OWNS_ACTIVE=1 + OWNS_CONFIG=1 + fi + if [ "${'$'}CONFIG_OWNER" = "imported_wg" ] || + { [ -z "${'$'}CONFIG_OWNER" ] && + grep -q '^IMPORTED_WG_CONFIG_B64=.' /etc/wdtt/outbound-profile.env 2>/dev/null && + [ "${'$'}MODE" != "warp_free" ] && + [ "${'$'}MODE" != "wireguard_vps" ]; }; then + OWNS_CONFIG=1 + fi + echo "WDTT_PROGRESS|0.25|Отключаю импортированный WireGuard-выход, если он запущен..." + if [ "${'$'}OWNS_ACTIVE" = 1 ]; then + wdtt_clear_wireguard_out + wdtt_write_mode "direct" "прямой выход" + fi + if [ "${'$'}OWNS_CONFIG" = 1 ]; then + rm -f /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf \ + /etc/wireguard/wg-wdtt-exit.conf \ + "${'$'}WDTT_WG_CONFIG_OWNER_FILE" + fi + echo "WDTT_PROGRESS|0.60|Удаляю сохранённую копию VPN/WireGuard-файла..." + if [ -f /etc/wdtt/outbound-profile.env ]; then + tmp_profile=/etc/wdtt/outbound-profile.env.tmp + grep -v '^IMPORTED_WG_CONFIG_B64=' /etc/wdtt/outbound-profile.env >"${'$'}tmp_profile" 2>/dev/null || true + chmod 600 "${'$'}tmp_profile" + mv "${'$'}tmp_profile" /etc/wdtt/outbound-profile.env + fi + IMPORTED_REMOVE_LEFT=0 + grep -q '^IMPORTED_WG_CONFIG_B64=' /etc/wdtt/outbound-profile.env 2>/dev/null && + IMPORTED_REMOVE_LEFT=1 + if [ "${'$'}OWNS_CONFIG" = 1 ]; then + if [ "${'$'}OWNS_ACTIVE" = 1 ] && + command -v wg >/dev/null 2>&1 && + wg show "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1; then + IMPORTED_REMOVE_LEFT=1 + fi + [ -e /etc/wireguard/wg-wdtt-exit.conf ] && IMPORTED_REMOVE_LEFT=1 + [ -e /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf ] && IMPORTED_REMOVE_LEFT=1 + fi + if [ "${'$'}IMPORTED_REMOVE_LEFT" != 0 ]; then + echo WDTT_ERROR=imported_wireguard_remove_failed + exit 3 + fi + echo "WDTT_PROGRESS|1.0|VPN/WireGuard-файл удалён." + if [ "${'$'}OWNS_ACTIVE" = 1 ]; then + echo "VPN/WireGuard-файл удалён, выход WDTT возвращён напрямую через текущий сервер." + else + echo "Сохранённая копия VPN/WireGuard-файла удалена. Другой активный режим выхода не изменён." + fi + """ +) + +private suspend fun deleteImportedWireGuardExit(target: OutboundSshTarget): String = + runCheckedRootScript(target, deleteImportedWireGuardExitScript(), timeout = 30000L) + +internal fun deleteWireGuardVpsCurrentScript(): String = shellScript( + outboundShellPrelude(), + """ + MODE="${'$'}(sed -n 's/.*"outboundMode"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' /etc/wdtt/outbound.json 2>/dev/null | head -n 1)" + OWNER="${'$'}(cat "${'$'}WDTT_WG_OWNER_FILE" 2>/dev/null | head -n 1)" + CONFIG_OWNER="${'$'}(cat "${'$'}WDTT_WG_CONFIG_OWNER_FILE" 2>/dev/null | head -n 1)" + OWNS_ACTIVE=0 + OWNS_CONFIG=0 + if [ "${'$'}MODE" = "wireguard_vps" ] || + { [ "${'$'}MODE" = "direct" ] && [ "${'$'}OWNER" = "wireguard_vps" ]; }; then + OWNS_ACTIVE=1 + OWNS_CONFIG=1 + fi + if [ "${'$'}CONFIG_OWNER" = "wireguard_vps" ] || + { [ -z "${'$'}CONFIG_OWNER" ] && + [ -f /etc/wireguard/wg-wdtt-exit.conf ] && + grep -Eq 'Address[[:space:]]*=[[:space:]]*10\\.77\\.77\\.2/30' /etc/wireguard/wg-wdtt-exit.conf 2>/dev/null && + grep -Eq 'AllowedIPs[[:space:]]*=[[:space:]]*0\\.0\\.0\\.0/0' /etc/wireguard/wg-wdtt-exit.conf 2>/dev/null; }; then + OWNS_CONFIG=1 + fi + echo "WDTT_PROGRESS|0.25|Возвращаю прямой выход на текущем VPS..." + if [ "${'$'}OWNS_ACTIVE" = 1 ]; then + wdtt_clear_wireguard_out + wdtt_write_mode "direct" "прямой выход" + fi + if [ "${'$'}OWNS_CONFIG" = 1 ]; then + rm -f /etc/wireguard/wg-wdtt-exit.conf \ + /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf \ + "${'$'}WDTT_WG_CONFIG_OWNER_FILE" \ + /etc/wdtt-plus/wg-exit/private.key \ + /etc/wdtt-plus/wg-exit/public.key \ + /etc/systemd/system/wdtt-wg-exit.service \ + /usr/local/lib/wdtt/wg-exit-up \ + /usr/local/lib/wdtt/wg-exit-down + rm -rf /etc/wdtt-plus/wg-exit/transactions + rmdir /etc/wdtt-plus/wg-exit 2>/dev/null || true + systemctl daemon-reload 2>/dev/null || true + fi + echo "WDTT_PROGRESS|0.55|Удаляю сохранённые поля дополнительного VPS..." + if [ -f /etc/wdtt/outbound-profile.env ]; then + tmp_profile=/etc/wdtt/outbound-profile.env.tmp + grep -Ev '^(WG_VPS_HOST_B64|WG_VPS_SSH_PORT|WG_VPS_USER_B64|WG_VPS_PASSWORD_B64|WG_VPS_PORT|WG_VPS_DNS_B64)=' \ + /etc/wdtt/outbound-profile.env >"${'$'}tmp_profile" 2>/dev/null || true + chmod 600 "${'$'}tmp_profile" + mv "${'$'}tmp_profile" /etc/wdtt/outbound-profile.env + fi + CURRENT_REMOVE_LEFT=0 + if [ "${'$'}OWNS_CONFIG" = 1 ]; then + systemctl is-active --quiet wdtt-wg-exit.service 2>/dev/null && CURRENT_REMOVE_LEFT=1 + systemctl is-enabled --quiet wdtt-wg-exit.service 2>/dev/null && CURRENT_REMOVE_LEFT=1 + if [ "${'$'}OWNS_ACTIVE" = 1 ]; then + (command -v wg >/dev/null 2>&1 && wg show "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1) && + CURRENT_REMOVE_LEFT=1 + ip rule show 2>/dev/null | grep -Eq "from [^ ]+ lookup ${'$'}WDTT_TABLE([[:space:]]|${'$'})|from [^ ]+ lookup wdtt-exit([[:space:]]|${'$'})" && + CURRENT_REMOVE_LEFT=1 + fi + [ -e /etc/wireguard/wg-wdtt-exit.conf ] && CURRENT_REMOVE_LEFT=1 + [ -e /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf ] && CURRENT_REMOVE_LEFT=1 + [ -e /etc/wdtt-plus/wg-exit/private.key ] && CURRENT_REMOVE_LEFT=1 + [ -e /etc/wdtt-plus/wg-exit/public.key ] && CURRENT_REMOVE_LEFT=1 + fi + if [ "${'$'}CURRENT_REMOVE_LEFT" != 0 ]; then + echo WDTT_ERROR=wireguard_vps_current_remove_failed + exit 3 + fi + echo WDTT_CURRENT_WG_REMOVED=1 + """ +) + +internal fun deleteWireGuardVpsForeignScript(): String = """ + set -e + WG_IFACE=wg-wdtt-exit + WG_CONF=/etc/wireguard/wg-wdtt-exit.conf + OWNED=0 + if [ -f "${'$'}WG_CONF" ]; then + if grep -q 'WDTT_EXIT_FOREIGN' "${'$'}WG_CONF" 2>/dev/null && + grep -Eq 'Address[[:space:]]*=[[:space:]]*10\\.77\\.77\\.1/30' "${'$'}WG_CONF" 2>/dev/null; then + OWNED=1 + else + echo WDTT_ERROR=foreign_wireguard_not_owned + exit 3 + fi + fi + if command -v iptables >/dev/null 2>&1 && + { iptables -S INPUT 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 + if [ "${'$'}OWNED" != 1 ]; then + echo WDTT_FOREIGN_WG_REMOVED=1 + echo "На дополнительном VPS созданная WDTT конфигурация WireGuard уже отсутствует." + exit 0 + fi + echo "WDTT_PROGRESS|0.72|Останавливаю WireGuard на дополнительном VPS..." + systemctl disable --now wg-quick@wg-wdtt-exit 2>/dev/null || true + 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 -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 + echo "WDTT_PROGRESS|0.86|Удаляю конфигурацию и ключи с дополнительного VPS..." + rm -f "${'$'}WG_CONF" \ + /etc/sysctl.d/99-wdtt-exit-forward.conf \ + /etc/wdtt-plus/wg-exit/private.key \ + /etc/wdtt-plus/wg-exit/public.key \ + /etc/wdtt-plus/wg-exit/owner \ + /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf + rm -rf /etc/wdtt-plus/wg-exit/transactions + rmdir /etc/wdtt-plus/wg-exit 2>/dev/null || true + FOREIGN_REMOVE_LEFT=0 + systemctl is-active --quiet wg-quick@wg-wdtt-exit 2>/dev/null && FOREIGN_REMOVE_LEFT=1 + systemctl is-enabled --quiet wg-quick@wg-wdtt-exit 2>/dev/null && FOREIGN_REMOVE_LEFT=1 + [ -e "${'$'}WG_CONF" ] && FOREIGN_REMOVE_LEFT=1 + [ -e /etc/wdtt-plus/wg-exit/private.key ] && FOREIGN_REMOVE_LEFT=1 + [ -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 -t nat -S POSTROUTING 2>/dev/null | grep -q WDTT_EXIT_FOREIGN; }; then + FOREIGN_REMOVE_LEFT=1 + fi + if [ "${'$'}FOREIGN_REMOVE_LEFT" != 0 ]; then + echo WDTT_ERROR=foreign_wireguard_remove_failed + exit 3 + fi + echo WDTT_FOREIGN_WG_REMOVED=1 + echo "WDTT_PROGRESS|1.0|Выход через другой сервер удалён с обоих VPS." +""".trimIndent() + +private suspend fun deleteWireGuardExitVps( + current: OutboundSshTarget, + foreignHost: String, + foreignPort: Int, + foreignUser: String, + foreignCredentials: SshCredentials +): String = withContext(Dispatchers.IO) { + require(foreignHost.isValidPublicHost()) { "укажите адрес дополнительного VPS" } + require(foreignPort in 1..65535) { "укажите корректный SSH-порт дополнительного VPS" } + require(foreignUser.isNotBlank()) { "укажите SSH-логин дополнительного VPS" } + require(foreignCredentials.hasAuthentication) { "добавьте пароль или SSH-ключ дополнительного VPS" } + var currentSession: Session? = null + var foreignSession: Session? = null try { - session = createSshSession(target.host, target.user, target.credentials, target.port) - val ssh = SSHClient(session, target.pass) - val script = shellScript( - outboundShellPrelude(), - """ - echo "WDTT_PROGRESS|0.25|Отключаю WireGuard-выход, если он запущен..." - wdtt_clear_external_out - echo "WDTT_PROGRESS|0.60|Удаляю сохранённый VPN/WireGuard-файл..." - rm -f /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf /etc/wireguard/wg-wdtt-exit.conf - if [ -f /etc/wdtt/outbound-profile.env ]; then - tmp_profile=/etc/wdtt/outbound-profile.env.tmp - grep -v '^IMPORTED_WG_CONFIG_B64=' /etc/wdtt/outbound-profile.env >"${'$'}tmp_profile" 2>/dev/null || true - chmod 600 "${'$'}tmp_profile" - mv "${'$'}tmp_profile" /etc/wdtt/outbound-profile.env - fi - echo "WDTT_PROGRESS|0.85|Возвращаю прямой выход через текущий сервер..." - wdtt_write_mode "direct" "прямой выход" - echo "WDTT_PROGRESS|1.0|VPN/WireGuard-файл удалён." - echo "VPN/WireGuard-файл удалён, выход WDTT возвращён напрямую через текущий сервер." - """ - ) - ssh.exec(rootCommand(script), timeout = 30000L).trim() + DeployManager.updateProgress(0.08f, "Проверяю SSH-доступ к обоим VPS...") + currentSession = createSshSession(current.host, current.user, current.credentials, current.port) + foreignSession = createSshSession(foreignHost, foreignUser, foreignCredentials, foreignPort) + val currentOutput = SSHClient(currentSession, current.pass) + .exec(rootCommand(deleteWireGuardVpsCurrentScript()), timeout = 30000L) + markerValue(currentOutput, "WDTT_ERROR")?.let { + throw IllegalStateException(currentOutput.take(1200)) + } + require(markerValue(currentOutput, "WDTT_CURRENT_WG_REMOVED") == "1") { + "текущий VPS не подтвердил удаление WireGuard-выхода" + } + val foreignOutput = SSHClient(foreignSession, foreignCredentials.password) + .exec(rootCommand(deleteWireGuardVpsForeignScript()), timeout = 30000L) + markerValue(foreignOutput, "WDTT_ERROR")?.let { + throw IllegalStateException(foreignOutput.take(1200)) + } + require(markerValue(foreignOutput, "WDTT_FOREIGN_WG_REMOVED") == "1") { + "дополнительный VPS не подтвердил удаление WireGuard" + } + "Выход через другой сервер удалён: текущий VPS использует прямой выход, созданные WDTT настройки дополнительного VPS очищены." } finally { - try { session?.disconnect() } catch (_: Exception) {} + try { currentSession?.disconnect() } catch (_: Exception) {} + try { foreignSession?.disconnect() } catch (_: Exception) {} } } @@ -7281,11 +8523,20 @@ private suspend fun installWireGuardExitVps( foreignPort: Int, foreignUser: String, foreignCredentials: SshCredentials, - wgPort: Int, - dns: String + wgPort: Int ): String = withContext(Dispatchers.IO) { + require(foreignHost.isValidPublicHost()) { "укажите домен или IPv4 дополнительного VPS без схемы и порта" } + require(foreignPort in 1..65535) { "SSH-порт дополнительного VPS должен быть от 1 до 65535" } + require(foreignUser.isNotBlank()) { "укажите SSH-логин дополнительного VPS" } + require(foreignCredentials.hasAuthentication) { "добавьте пароль или SSH-ключ дополнительного VPS" } + require(wgPort in 1..65535) { "порт WireGuard должен быть от 1 до 65535" } var currentSession: Session? = null var foreignSession: Session? = null + val transactionId = randomToken(12).lowercase() + val foreignBackupDir = "/etc/wdtt-plus/wg-exit/transactions/$transactionId/foreign" + val currentBackupDir = "/etc/wdtt-plus/wg-exit/transactions/$transactionId/current" + var foreignTouched = false + var currentTouched = false try { DeployManager.updateProgress(0.10f, "Подключаюсь к текущему серверу WDTT...") currentSession = createSshSession(current.host, current.user, current.credentials, current.port) @@ -7298,6 +8549,27 @@ private suspend fun installWireGuardExitVps( ) val currentSsh = SSHClient(currentSession, current.pass) val foreignSsh = SSHClient(foreignSession, foreignCredentials.password) + val previousHostOutput = currentSsh.exec( + rootCommand( + """ + SAVED_B64="${'$'}(grep '^WG_VPS_HOST_B64=' /etc/wdtt/outbound-profile.env 2>/dev/null | tail -n 1 | sed 's/^[^=]*=//')" + SAVED_HOST="" + [ -z "${'$'}SAVED_B64" ] || SAVED_HOST="${'$'}(printf '%s' "${'$'}SAVED_B64" | base64 -d 2>/dev/null || true)" + if [ -z "${'$'}SAVED_HOST" ] && [ -f /etc/wireguard/wg-wdtt-exit.conf ]; then + ENDPOINT="${'$'}(sed -n 's/^[[:space:]]*Endpoint[[:space:]]*=[[:space:]]*//Ip' /etc/wireguard/wg-wdtt-exit.conf | head -n 1 | tr -d ' ')" + SAVED_HOST="${'$'}{ENDPOINT%:*}" + SAVED_HOST="${'$'}{SAVED_HOST#[}" + SAVED_HOST="${'$'}{SAVED_HOST%]}" + fi + printf 'WDTT_PREVIOUS_WG_VPS_HOST=%s\n' "${'$'}SAVED_HOST" + """.trimIndent() + ), + timeout = 15000L + ) + val previousHost = markerValue(previousHostOutput, "WDTT_PREVIOUS_WG_VPS_HOST").orEmpty() + if (previousHost.isNotBlank() && !previousHost.equals(foreignHost, ignoreCase = true)) { + throw IllegalStateException("WDTT_ERROR=wireguard_vps_previous_server_requires_removal") + } val prepareKeys = """ echo "WDTT_PROGRESS|0.26|Готовлю WireGuard-инструменты и ключи..." @@ -7320,14 +8592,37 @@ private suspend fun installWireGuardExitVps( """ CURRENT_PUB=${shellQuote(currentPub)} WG_PORT=$wgPort + BACKUP_DIR=${shellQuote(foreignBackupDir)} """, outboundShellPrelude(), """ + command -v systemctl >/dev/null 2>&1 || { echo WDTT_ERROR=systemd_required; exit 2; } + command -v iptables >/dev/null 2>&1 || { echo WDTT_ERROR=iptables_required; exit 2; } echo "WDTT_PROGRESS|0.50|Определяю внешний интерфейс другого сервера..." EXT_IFACE="${'$'}(wdtt_ext_iface)" [ -n "${'$'}EXT_IFACE" ] || { echo WDTT_ERROR=foreign_ext_iface_not_found; exit 2; } + echo "WDTT_PROGRESS|0.53|Сохраняю прежнее состояние другого сервера для отката..." + rm -rf "${'$'}BACKUP_DIR" + mkdir -p "${'$'}BACKUP_DIR" + chmod 700 "${'$'}BACKUP_DIR" + [ ! -f /etc/wireguard/wg-wdtt-exit.conf ] || + { cp -a /etc/wireguard/wg-wdtt-exit.conf "${'$'}BACKUP_DIR/wg.conf"; touch "${'$'}BACKUP_DIR/had_wg_conf"; } + [ ! -f /etc/sysctl.d/99-wdtt-exit-forward.conf ] || + { cp -a /etc/sysctl.d/99-wdtt-exit-forward.conf "${'$'}BACKUP_DIR/sysctl.conf"; touch "${'$'}BACKUP_DIR/had_sysctl_conf"; } + sysctl -n net.ipv4.ip_forward >"${'$'}BACKUP_DIR/ip_forward" 2>/dev/null || printf '0\n' >"${'$'}BACKUP_DIR/ip_forward" + 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 -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 -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|Включаю пересылку трафика на другом сервере..." - sysctl -w net.ipv4.ip_forward=1 >/dev/null + sysctl -w net.ipv4.ip_forward=1 >/dev/null || + { echo WDTT_ERROR=foreign_ip_forward_failed; exit 3; } mkdir -p /etc/sysctl.d /etc/wireguard printf 'net.ipv4.ip_forward=1\n' >/etc/sysctl.d/99-wdtt-exit-forward.conf PRIV="${'$'}(cat /etc/wdtt-plus/wg-exit/private.key)" @@ -7337,6 +8632,10 @@ private suspend fun installWireGuardExitVps( Address = 10.77.77.1/30 ListenPort = ${'$'}WG_PORT 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 + 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 [Peer] PublicKey = ${'$'}CURRENT_PUB @@ -7344,25 +8643,58 @@ private suspend fun installWireGuardExitVps( EOF chmod 600 /etc/wireguard/wg-wdtt-exit.conf echo "WDTT_PROGRESS|0.68|Запускаю WireGuard на другом сервере..." - systemctl enable --now wg-quick@wg-wdtt-exit >/dev/null - echo "WDTT_PROGRESS|0.70|Открываю порт WireGuard и добавляю NAT на другом сервере..." - 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 - 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 + systemctl enable wg-quick@wg-wdtt-exit >/dev/null || + { echo WDTT_ERROR=foreign_wireguard_enable_failed; exit 3; } + systemctl restart wg-quick@wg-wdtt-exit >/dev/null || + { echo WDTT_ERROR=foreign_wireguard_start_failed; exit 3; } + 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 -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 echo "WireGuard на другом сервере запущен: ${'$'}EXT_IFACE" """ ) DeployManager.updateProgress(0.48f, "Настраиваю WireGuard на другом сервере...") - foreignSsh.exec(rootCommand(foreignConfigScript), timeout = CMD_TIMEOUT) + foreignTouched = true + val foreignOutput = foreignSsh.exec(rootCommand(foreignConfigScript), timeout = CMD_TIMEOUT) + markerValue(foreignOutput, "WDTT_ERROR")?.let { throw IllegalStateException(foreignOutput.trim().take(1200)) } + require(markerValue(foreignOutput, "WDTT_FOREIGN_READY") == "1") { + "другой сервер не подтвердил запуск WireGuard" + } val currentConfigScript = shellScript( """ FOREIGN_PUB=${shellQuote(foreignPub)} FOREIGN_HOST=${shellQuote(foreignHost)} WG_PORT=$wgPort - DNS_VALUE=${shellQuote(dns.ifBlank { "1.1.1.1,8.8.8.8" })} + CURRENT_BACKUP_DIR=${shellQuote(currentBackupDir)} """, outboundShellPrelude(), """ + echo "WDTT_PROGRESS|0.70|Сохраняю прежний режим выхода текущего сервера..." + rm -rf "${'$'}CURRENT_BACKUP_DIR" + mkdir -p "${'$'}CURRENT_BACKUP_DIR" + chmod 700 "${'$'}CURRENT_BACKUP_DIR" + touch "${'$'}CURRENT_BACKUP_DIR/created" + [ ! -f /etc/wireguard/wg-wdtt-exit.conf ] || + { cp -a /etc/wireguard/wg-wdtt-exit.conf "${'$'}CURRENT_BACKUP_DIR/wg.conf"; touch "${'$'}CURRENT_BACKUP_DIR/had_wg_conf"; } + [ ! -f /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf ] || + { cp -a /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf "${'$'}CURRENT_BACKUP_DIR/saved_wg.conf"; touch "${'$'}CURRENT_BACKUP_DIR/had_saved_wg_conf"; } + [ ! -f /etc/wdtt/outbound.json ] || + { cp -a /etc/wdtt/outbound.json "${'$'}CURRENT_BACKUP_DIR/outbound.json"; touch "${'$'}CURRENT_BACKUP_DIR/had_outbound_json"; } + [ ! -f "${'$'}WDTT_WG_OWNER_FILE" ] || + { cp -a "${'$'}WDTT_WG_OWNER_FILE" "${'$'}CURRENT_BACKUP_DIR/owner"; touch "${'$'}CURRENT_BACKUP_DIR/had_owner"; } + [ ! -f "${'$'}WDTT_WG_CONFIG_OWNER_FILE" ] || + { cp -a "${'$'}WDTT_WG_CONFIG_OWNER_FILE" "${'$'}CURRENT_BACKUP_DIR/config-owner"; touch "${'$'}CURRENT_BACKUP_DIR/had_config_owner"; } + systemctl is-active --quiet wdtt-wg-exit.service 2>/dev/null && touch "${'$'}CURRENT_BACKUP_DIR/wg_was_active" || true + systemctl is-enabled --quiet wdtt-wg-exit.service 2>/dev/null && touch "${'$'}CURRENT_BACKUP_DIR/wg_was_enabled" || true + systemctl is-active --quiet wdtt-redsocks.service 2>/dev/null && touch "${'$'}CURRENT_BACKUP_DIR/proxy_was_active" || true + systemctl is-enabled --quiet wdtt-redsocks.service 2>/dev/null && touch "${'$'}CURRENT_BACKUP_DIR/proxy_was_enabled" || true + systemctl is-active --quiet wdtt-warp-watchdog.timer 2>/dev/null && touch "${'$'}CURRENT_BACKUP_DIR/warp_timer_was_active" || true + systemctl is-enabled --quiet wdtt-warp-watchdog.timer 2>/dev/null && touch "${'$'}CURRENT_BACKUP_DIR/warp_timer_was_enabled" || true + chmod 600 "${'$'}CURRENT_BACKUP_DIR"/* echo "WDTT_PROGRESS|0.72|Записываю WireGuard-настройки текущего сервера..." mkdir -p /etc/wireguard /etc/wdtt-plus/wg-exit PRIV="${'$'}(cat /etc/wdtt-plus/wg-exit/private.key)" @@ -7370,7 +8702,6 @@ private suspend fun installWireGuardExitVps( [Interface] Address = 10.77.77.2/30 PrivateKey = ${'$'}PRIV - DNS = ${'$'}DNS_VALUE Table = off [Peer] @@ -7385,12 +8716,168 @@ private suspend fun installWireGuardExitVps( wireGuardPolicyScript("wireguard_vps", "другой сервер ${foreignHost}:${wgPort}") ) 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)) + 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 + foreignTouched = false DeployManager.updateProgress(1f, "WireGuard-выход через другой сервер включён.") output.trim().ifBlank { "Выход через WireGuard включён для WDTT-пользователей." } } catch (e: Exception) { - try { currentSession?.let { SSHClient(it, current.pass).exec(rootCommand("${outboundShellPrelude()}\nwdtt_clear_external_out\nwdtt_write_mode \"direct\" \"rollback\""), timeout = 30000L) } } catch (_: Exception) {} + var rollbackIncomplete = false + if (foreignTouched) { + val rollbackScript = shellScript( + "BACKUP_DIR=${shellQuote(foreignBackupDir)}", + """ + [ -d "${'$'}BACKUP_DIR" ] || { echo WDTT_ROLLBACK_OK=1; exit 0; } + systemctl disable --now wg-quick@wg-wdtt-exit 2>/dev/null || true + 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 -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 + if [ -f "${'$'}BACKUP_DIR/had_wg_conf" ]; then + install -m 600 "${'$'}BACKUP_DIR/wg.conf" /etc/wireguard/wg-wdtt-exit.conf + else + rm -f /etc/wireguard/wg-wdtt-exit.conf + fi + if [ -f "${'$'}BACKUP_DIR/had_sysctl_conf" ]; then + install -m 644 "${'$'}BACKUP_DIR/sysctl.conf" /etc/sysctl.d/99-wdtt-exit-forward.conf + else + rm -f /etc/sysctl.d/99-wdtt-exit-forward.conf + fi + PREVIOUS_FORWARD="${'$'}(cat "${'$'}BACKUP_DIR/ip_forward" 2>/dev/null || echo 0)" + sysctl -w "net.ipv4.ip_forward=${'$'}PREVIOUS_FORWARD" >/dev/null 2>&1 || true + if [ -f "${'$'}BACKUP_DIR/was_enabled" ]; then + systemctl enable wg-quick@wg-wdtt-exit >/dev/null 2>&1 || true + else + systemctl disable wg-quick@wg-wdtt-exit >/dev/null 2>&1 || true + fi + if [ -f "${'$'}BACKUP_DIR/was_active" ]; then + systemctl start wg-quick@wg-wdtt-exit >/dev/null 2>&1 || true + else + systemctl stop wg-quick@wg-wdtt-exit >/dev/null 2>&1 || true + fi + 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 -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" ] || iptables -t nat ${'$'}rule 2>/dev/null || true; done <"${'$'}BACKUP_DIR/nat.rules" + fi + if [ -f "${'$'}BACKUP_DIR/was_active" ] && + ! systemctl is-active --quiet wg-quick@wg-wdtt-exit 2>/dev/null; then + exit 3 + fi + rm -rf "${'$'}BACKUP_DIR" + echo WDTT_ROLLBACK_OK=1 + """ + ) + suspend fun rollbackForeign(session: Session): Boolean = runCatching { + val rollbackOutput = SSHClient(session, foreignCredentials.password) + .exec(rootCommand(rollbackScript), timeout = 45000L) + markerValue(rollbackOutput, "WDTT_ROLLBACK_OK") == "1" + }.getOrDefault(false) + val rolledBack = foreignSession?.let { rollbackForeign(it) } ?: false + if (!rolledBack) { + try { foreignSession?.disconnect() } catch (_: Exception) {} + foreignSession = runCatching { + createSshSession(foreignHost, foreignUser, foreignCredentials, foreignPort) + }.getOrNull() + if (foreignSession?.let { rollbackForeign(it) } != true) rollbackIncomplete = true + } + } + if (currentTouched) { + val rollbackCurrentScript = shellScript( + "BACKUP_DIR=${shellQuote(currentBackupDir)}", + outboundShellPrelude(), + """ + [ -d "${'$'}BACKUP_DIR" ] || { echo WDTT_ROLLBACK_OK=1; exit 0; } + wdtt_clear_external_out + if [ -f "${'$'}BACKUP_DIR/had_wg_conf" ]; then + install -m 600 "${'$'}BACKUP_DIR/wg.conf" /etc/wireguard/wg-wdtt-exit.conf + else + rm -f /etc/wireguard/wg-wdtt-exit.conf + fi + if [ -f "${'$'}BACKUP_DIR/had_saved_wg_conf" ]; then + install -m 600 "${'$'}BACKUP_DIR/saved_wg.conf" /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf + else + rm -f /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf + fi + if [ -f "${'$'}BACKUP_DIR/had_outbound_json" ]; then + install -m 600 "${'$'}BACKUP_DIR/outbound.json" /etc/wdtt/outbound.json + else + rm -f /etc/wdtt/outbound.json + fi + if [ -f "${'$'}BACKUP_DIR/had_owner" ]; then + install -m 600 "${'$'}BACKUP_DIR/owner" "${'$'}WDTT_WG_OWNER_FILE" + else + rm -f "${'$'}WDTT_WG_OWNER_FILE" + fi + if [ -f "${'$'}BACKUP_DIR/had_config_owner" ]; then + install -m 600 "${'$'}BACKUP_DIR/config-owner" "${'$'}WDTT_WG_CONFIG_OWNER_FILE" + else + rm -f "${'$'}WDTT_WG_CONFIG_OWNER_FILE" + fi + if [ -f "${'$'}BACKUP_DIR/wg_was_enabled" ]; then + systemctl enable wdtt-wg-exit.service >/dev/null 2>&1 || true + fi + if [ -f "${'$'}BACKUP_DIR/proxy_was_enabled" ]; then + systemctl enable wdtt-redsocks.service >/dev/null 2>&1 || true + fi + if [ -f "${'$'}BACKUP_DIR/wg_was_active" ]; then + systemctl restart wdtt-wg-exit.service >/dev/null 2>&1 || true + fi + if [ -f "${'$'}BACKUP_DIR/proxy_was_active" ]; then + systemctl restart wdtt-redsocks.service >/dev/null 2>&1 || true + fi + if [ -f "${'$'}BACKUP_DIR/warp_timer_was_enabled" ]; then + systemctl enable wdtt-warp-watchdog.timer >/dev/null 2>&1 || true + fi + if [ -f "${'$'}BACKUP_DIR/warp_timer_was_active" ]; then + systemctl start wdtt-warp-watchdog.timer >/dev/null 2>&1 || true + fi + if [ -f "${'$'}BACKUP_DIR/wg_was_active" ] && + ! systemctl is-active --quiet wdtt-wg-exit.service 2>/dev/null; then + exit 3 + fi + if [ -f "${'$'}BACKUP_DIR/proxy_was_active" ] && + ! systemctl is-active --quiet wdtt-redsocks.service 2>/dev/null; then + exit 3 + fi + if [ -f "${'$'}BACKUP_DIR/warp_timer_was_active" ] && + ! systemctl is-active --quiet wdtt-warp-watchdog.timer 2>/dev/null; then + exit 3 + fi + rm -rf ${shellQuote("/etc/wdtt-plus/wg-exit/transactions/$transactionId")} + echo WDTT_ROLLBACK_OK=1 + """ + ) + suspend fun rollbackCurrent(session: Session): Boolean = runCatching { + val rollbackOutput = SSHClient(session, current.pass) + .exec(rootCommand(rollbackCurrentScript), timeout = 45000L) + markerValue(rollbackOutput, "WDTT_ROLLBACK_OK") == "1" + }.getOrDefault(false) + var currentRollbackOk = currentSession?.let { rollbackCurrent(it) } ?: false + if (!currentRollbackOk) { + try { currentSession?.disconnect() } catch (_: Exception) {} + currentSession = runCatching { + createSshSession(current.host, current.user, current.credentials, current.port) + }.getOrNull() + currentRollbackOk = currentSession?.let { rollbackCurrent(it) } ?: false + } + if (!currentRollbackOk) rollbackIncomplete = true + } + if (rollbackIncomplete) { + throw IllegalStateException( + "${e.message.orEmpty()}\nWDTT_ERROR=outbound_rollback_incomplete", + e + ) + } throw e } finally { try { currentSession?.disconnect() } catch (_: Exception) {} @@ -7464,6 +8951,14 @@ private suspend fun checkExistingInstall( private fun markerValue(output: String, name: String): String? = Regex("^$name=(.*)$", setOf(RegexOption.MULTILINE)).find(output)?.groupValues?.getOrNull(1)?.trim() +internal fun shouldWriteRemoteErrorToUserLog(line: String): Boolean = + !line.startsWith("WDTT_ERROR=") && + ( + line.contains("[✗]") || + line.contains("FAIL") || + (line.contains("error", true) && !line.contains("2>/dev/null")) + ) + private fun compactRemoteTail(raw: String): String { val lines = raw.lineSequence() .map { it.trim() } @@ -7495,12 +8990,18 @@ private fun friendlyDeployError(error: Throwable, operation: String): String { "не удалось распаковать исходники 3proxy: на сервере нет gzip, и пакетный менеджер не смог его поставить." "3proxy_source_no_make" in lower -> "не удалось собрать 3proxy: на сервере нет make, и пакетный менеджер не смог его поставить." + "3proxy_source_no_sha256sum" in lower -> + "не удалось безопасно проверить архив 3proxy: на сервере нет sha256sum." "3proxy_source_no_compiler" in lower -> "не удалось собрать 3proxy: на сервере нет компилятора gcc/cc, и пакетный менеджер не смог его поставить." "3proxy_source_no_openssl_headers" in lower -> "не удалось собрать 3proxy: на сервере нет OpenSSL-заголовков. Нужен пакет libssl-dev, openssl-devel, libopenssl-devel или openssl-dev в зависимости от Linux-дистрибутива." + "3proxy_source_no_pcre2_headers" in lower -> + "не удалось собрать актуальный 3proxy: на сервере нет заголовков PCRE2. Нужен пакет libpcre2-dev или pcre2-devel в зависимости от Linux-дистрибутива." "3proxy_source_download_failed" in lower -> - "не удалось скачать исходники 3proxy с GitHub. Проверьте, открывается ли github.com с сервера и не блокирует ли сеть исходящие HTTPS-подключения." + "не удалось скачать закреплённый выпуск 3proxy с GitHub. Проверьте, открывается ли github.com с сервера и не блокирует ли сеть исходящие HTTPS-подключения." + "3proxy_source_checksum_failed" in lower -> + "контрольная сумма архива 3proxy не совпала с закреплённым выпуском. Архив не был распакован или запущен." "3proxy_source_unpack_failed" in lower -> "архив 3proxy скачался, но сервер не смог его распаковать. Возможен битый архив, нехватка места или проблема с tar/gzip." "3proxy_source_build_failed" in lower -> @@ -7510,7 +9011,7 @@ private fun friendlyDeployError(error: Throwable, operation: String): String { "3proxy_source_install_failed" in lower -> "3proxy собрался, но сервер не дал записать файл в /usr/local/bin. Проверьте root-права SSH-пользователя и sudo." "3proxy_install_failed" in lower || "3proxy_not_installed" in lower -> - "не удалось установить 3proxy: пакет не найден в репозиториях сервера, а сборка из исходников не дала готовый файл. Повторите установку: теперь приложение покажет конкретный шаг, на котором она сорвалась." + "не удалось установить закреплённый выпуск 3proxy из проверенных исходников. Повторите установку: приложение покажет конкретный шаг, на котором она сорвалась." "systemd_required" in lower -> "для прокси на этом сервере нужна systemd-служба. На сервере не найден systemctl, поэтому приложение не может безопасно запустить 3proxy как сервис." "curl_not_installed" in lower -> @@ -7520,13 +9021,23 @@ private fun friendlyDeployError(error: Throwable, operation: String): String { "local_proxy_service_inactive" in lower -> "служба wdtt-3proxy не запущена. Нажмите «Установить», чтобы создать или обновить прокси на сервере." "local_proxy_service_still_active" in lower -> - "приложение отправило команду остановки, но служба wdtt-3proxy всё ещё запущена. Проверьте права пользователя SSH или остановите службу вручную." + "приложение отправило команду остановки, но служба wdtt-3proxy всё ещё запущена или осталась в автозапуске. Проверьте права пользователя SSH." + "local_proxy_remove_failed" in lower -> + "сервер не подтвердил полное удаление локального прокси. Служба, конфигурация или правило firewall ещё остались; повторите удаление и откройте диагностику сервера." + "local_proxy_firewall_failed" in lower -> + "прокси запустился, но сервер не смог открыть его порты в firewall. Служба остановлена, чтобы интерфейс не показывал неработающий режим." "external_proxy_check_failed" in lower -> "внешний TCP-прокси не ответил на проверку. Проверьте адрес, порт, логин и пароль." "external_proxy_service_inactive" in lower -> "служба перенаправления через внешний TCP-прокси не запустилась. Приложение откатило правила и вернуло прямой выход, чтобы интернет через VPN не остался сломанным." + "external_proxy_route_install_failed" in lower -> + "служба внешнего прокси запустилась, но сервер не применил постоянное правило маршрутизации WDTT. Режим отключён и прямой выход сохранён." "external_proxy_apply_failed" in lower -> withTail("внешний TCP-прокси отвечает напрямую, но путь WDTT через redsocks не заработал. Приложение откатило правила и вернуло прямой выход, чтобы VPN-интернет не пропал.") + "external_proxy_test_rule_failed" in lower -> + "сервер не разрешил создать временное правило для проверки пути WDTT через внешний прокси. Режим не считается проверенным и был отключён." + "external_proxy_remove_failed" in lower -> + "сервер не подтвердил полное удаление внешнего TCP-прокси. Служба, конфигурация или правило перенаправления ещё остались." "redsocks_not_installed" in lower -> "не удалось установить компонент перенаправления через внешний TCP-прокси. Проверьте пакетный менеджер и доступ сервера к интернету." "iptables_required" in lower -> @@ -7538,11 +9049,27 @@ private fun friendlyDeployError(error: Throwable, operation: String): String { "wireguard_tools_required" in lower -> "на сервере не найдены инструменты WireGuard, без них этот режим не включить." "wireguard_exit_service_inactive" in lower -> - "служба WireGuard-выхода не запустилась. Приложение не будет оставлять неполные маршруты; проверьте конфигурацию и журнал systemd." + withTail("служба WireGuard-выхода не запустилась. Приложение удалило частично созданный интерфейс и маршруты и сохранило прямой выход. Откройте диагностику, чтобы увидеть причину запуска systemd.") + "direct_cleanup_failed" in lower -> + "сервер не подтвердил полную остановку прежнего WireGuard/прокси-выхода. Запустите «Диагностику» и не включайте другой режим, пока оставшийся маршрут не будет устранён." "wireguard_not_active" in lower -> "WireGuard-выход WDTT сейчас не запущен. Включите «Бесплатный WARP», «Другой сервер» или «VPN/WireGuard-файл», затем повторите проверку." "wireguard_exit_check_failed" in lower -> "WireGuard-интерфейс запущен, но проверочный сайт через него не открылся. Проверьте конфиг, endpoint, NAT и доступ второго сервера/VPN к интернету." + "wireguard_vps_current_remove_failed" in lower -> + "текущий VPS не подтвердил полное удаление WireGuard-выхода. Прямой маршрут, служба или рабочий конфиг ещё остались." + "wireguard_vps_previous_server_requires_removal" in lower -> + "на текущем VPS сохранён другой дополнительный сервер. Сначала откройте прежний адрес и нажмите «Удалить», чтобы не оставить на нём работающую WireGuard-службу, затем настройте новый." + "foreign_wireguard_not_owned" in lower -> + "на дополнительном VPS найден интерфейс wg-wdtt-exit, но приложение не подтвердило, что конфигурация была создана WDTT Plus. Файл не удалён, чтобы не повредить чужую настройку." + "foreign_wireguard_remove_failed" in lower -> + "дополнительный VPS не подтвердил полное удаление созданной WDTT конфигурации WireGuard или её правил firewall." + "imported_wireguard_remove_failed" in lower -> + "сервер не подтвердил удаление импортированного VPN/WireGuard-файла. Другие активные режимы выхода не очищались." + "warp_registration_reset_failed" in lower -> + "сервер не подтвердил удаление текущей регистрации и профиля WARP." + "warp_remove_failed" in lower -> + "сервер не подтвердил полное удаление WARP: остался профиль, инструмент или служба автоматической проверки." "warp_unsupported_arch" in lower -> "автоматический WARP поддерживает Linux amd64 — ту же архитектуру, для которой собирается сервер WDTT Plus. На этом сервере определена другая архитектура." "warp_download_tools_missing" in lower -> @@ -7569,8 +9096,18 @@ private fun friendlyDeployError(error: Throwable, operation: String): String { "на сервере не найдена регистрация бесплатного WARP. Нажмите «Установить / восстановить» и подтвердите условия Cloudflare." "warp_profile_missing" in lower -> "регистрация WARP есть, но WireGuard-профиль отсутствует. Нажмите «Установить / восстановить»." + "outbound_rollback_incomplete" in lower -> + "настройка не завершилась, и один из серверов не подтвердил автоматическое восстановление прежнего состояния. Проверьте оба VPS вручную перед повторной попыткой." "foreign_ext_iface_not_found" in lower -> "на другом сервере не удалось определить основной сетевой интерфейс." + "foreign_ip_forward_failed" in lower -> + "на другом сервере не удалось включить пересылку IPv4. Приложение попыталось восстановить его прежние настройки." + "foreign_wireguard_enable_failed" in lower -> + "на другом сервере не удалось включить автозапуск WireGuard. Приложение попыталось восстановить его прежние настройки." + "foreign_wireguard_start_failed" in lower -> + "WireGuard на другом сервере не запустился. Приложение попыталось восстановить прежний конфиг, службу и сетевые правила." + "foreign_firewall_failed" in lower -> + "WireGuard на другом сервере запустился, но правила порта или NAT не применились. Приложение попыталось восстановить прежнее состояние." "ssh-сервер отклонил приватный ключ" in lower || "ssh-сервер отклонил пароль" in lower || "не удалось расшифровать приватный ssh-ключ" in lower || @@ -7608,6 +9145,8 @@ private fun friendlyDeployError(error: Throwable, operation: String): String { "это не файл бэкапа" in lower || "format" in lower && "wdtt-server-backup" in lower -> "выбран файл не того формата. Нужен JSON-экспорт WDTT Plus." + "контрольн" in lower && ("не совпала" in lower || "нет" in lower) -> + "файл импорта повреждён или изменён: проверка целостности не пройдена." "passwords должен быть объектом" in lower || "devices должен быть объектом" in lower || "некоррект" in lower || @@ -7627,6 +9166,11 @@ private fun decodeBase64Text(value: String): String = private fun encodeBase64Text(value: String): String = Base64.getEncoder().encodeToString(value.toByteArray(Charsets.UTF_8)) +private fun sha256Text(value: String): String = + MessageDigest.getInstance("SHA-256") + .digest(value.toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + private fun JSONObject.childObject(name: String): JSONObject { val current = optJSONObject(name) if (current != null) return current @@ -7694,7 +9238,16 @@ private fun validatePasswordEntry(pass: String, entry: JSONObject) { entry.optStringLength("device_id", 256, "пароля $pass") entry.optStringLength("label", 120, "пароля $pass") entry.optStringLength("vk_hash", 512, "пароля $pass") - require(entry.optLong("expires_at", 0) >= 0) { "expires_at у пароля $pass должен быть >= 0" } + val expiresAt = entry.optLong("expires_at", 0) + val purgeAfter = entry.optLong("purge_after", 0) + require(expiresAt >= 0) { "expires_at у пароля $pass должен быть >= 0" } + require(purgeAfter >= 0) { "purge_after у пароля $pass должен быть >= 0" } + require(expiresAt != 0L || purgeAfter == 0L) { + "purge_after у бессрочного пароля $pass должен быть 0" + } + require(purgeAfter == 0L || purgeAfter >= expiresAt) { + "purge_after у пароля $pass не может быть раньше expires_at" + } require(entry.optLong("down_bytes", 0) >= 0) { "down_bytes у пароля $pass должен быть >= 0" } require(entry.optLong("up_bytes", 0) >= 0) { "up_bytes у пароля $pass должен быть >= 0" } val ports = entry.optString("ports", "") @@ -7717,6 +9270,31 @@ private fun validatePasswordEntry(pass: String, entry: JSONObject) { validateTrafficBucket("пароля $pass", i, bucket) } } + val trafficImports = if (entry.has("traffic_imports")) { + entry.optJSONObject("traffic_imports") + ?: throw IllegalArgumentException("traffic_imports у пароля $pass должен быть объектом") + } else { + null + } + if (trafficImports != null) { + require(trafficImports.length() <= 1_000) { "traffic_imports у пароля $pass слишком большой" } + trafficImports.keys().forEach { operationId -> + require(operationId.isNotBlank() && operationId.length <= 160) { + "некорректный operation-id в traffic_imports у пароля $pass" + } + val imported = trafficImports.optJSONObject(operationId) + ?: throw IllegalArgumentException("traffic_imports у пароля $pass должен содержать объекты") + require(imported.optLong("down_bytes", 0) >= 0) { + "down_bytes в traffic_imports у пароля $pass должен быть >= 0" + } + require(imported.optLong("up_bytes", 0) >= 0) { + "up_bytes в traffic_imports у пароля $pass должен быть >= 0" + } + require(imported.optLong("applied_at", 0) >= 0) { + "applied_at в traffic_imports у пароля $pass должен быть >= 0" + } + } + } } private fun validateDeviceEntry(deviceId: String, device: JSONObject) { @@ -7761,7 +9339,7 @@ private fun validateAdminProfile(profile: JSONObject?) { require(ports.isBlank() || ports.isValidPortsSpec()) { "ports в admin_profile некорректны" } require(profile.optLong("updated_at", 0L) >= 0L) { "updated_at в admin_profile должен быть >= 0" } profile.optJSONArray("device_ids")?.let { ids -> - require(ids.length() <= 500) { "слишком много device_ids в admin_profile" } + require(ids.length() <= 64) { "слишком много device_ids в admin_profile" } for (index in 0 until ids.length()) { require(ids.optString(index).length <= 256) { "device_id в admin_profile слишком длинный" } } @@ -7813,6 +9391,25 @@ internal fun validatePasswordsDbStructure(db: JSONObject) { } } +internal fun validatePasswordsDbForPreserving( + db: JSONObject, + replacementMainPassword: String +): Boolean { + val mainPasswordNeedsRecovery = + !db.has("main_password") || db.optString("main_password").isBlank() + if (!mainPasswordNeedsRecovery) { + validatePasswordsDbStructure(db) + return false + } + require(replacementMainPassword.isNotBlank()) { + "main_password пустой; укажите главный пароль в «Секретах»" + } + val validatedCopy = JSONObject(db.toString()) + .put("main_password", replacementMainPassword) + validatePasswordsDbStructure(validatedCopy) + return true +} + private fun validateWgKeysDat(value: String) { val lines = value.trim().lines().map { it.trim() }.filter { it.isNotBlank() } require(lines.size >= 4) { "wg-keys.dat должен содержать 4 ключа" } @@ -7821,7 +9418,20 @@ private fun validateWgKeysDat(value: String) { } } -private fun parseBackup(passwordsJson: String, wgKeysDat: String?, createdAt: String, sourceHost: String): ServerBackup { +internal fun parseBackup( + passwordsJson: String, + wgKeysDat: String?, + createdAt: String, + sourceHost: String, + formatVersion: Int = SERVER_BACKUP_FORMAT_VERSION, + integrityVerified: Boolean = true +): ServerBackup { + require(passwordsJson.length <= MAX_SERVER_DATABASE_CHARS) { "база в бэкапе слишком большая" } + require(wgKeysDat == null || wgKeysDat.length <= MAX_SERVER_WG_KEYS_CHARS) { + "wg-keys.dat в бэкапе слишком большой" + } + require(createdAt.length <= 64) { "дата создания бэкапа слишком длинная" } + require(sourceHost.length <= 253) { "адрес исходного сервера слишком длинный" } val db = dbSummary(passwordsJson) validatePasswordsDbStructure(db) if (!wgKeysDat.isNullOrBlank()) { @@ -7839,46 +9449,86 @@ private fun parseBackup(passwordsJson: String, wgKeysDat: String?, createdAt: St mainPassword = db.optString("main_password"), adminId = db.optString("admin_id"), botToken = db.optString("bot_token"), - dns = db.optString("dns") + dns = db.optString("dns"), + formatVersion = formatVersion, + integrityVerified = integrityVerified ) } -private fun backupToJson(backup: ServerBackup): String { +internal fun backupToJson(backup: ServerBackup): String { val obj = JSONObject() .put("format", "wdtt-server-backup") - .put("version", 1) + .put("version", SERVER_BACKUP_FORMAT_VERSION) .put("created_at", backup.createdAt) .put("source_host", backup.sourceHost) .put("passwords_json_b64", encodeBase64Text(backup.passwordsJson)) + .put("passwords_json_sha256", sha256Text(backup.passwordsJson)) .put("password_count", backup.passwordCount) .put("device_count", backup.deviceCount) if (!backup.wgKeysDat.isNullOrBlank()) { - obj.put("wg_keys_dat_b64", encodeBase64Text(backup.wgKeysDat)) + obj + .put("wg_keys_dat_b64", encodeBase64Text(backup.wgKeysDat)) + .put("wg_keys_dat_sha256", sha256Text(backup.wgKeysDat)) } return obj.toString(2) } -private fun parseBackupFile(raw: String): ServerBackup { +internal fun parseBackupFile(raw: String): ServerBackup { + require(raw.length <= MAX_SERVER_BACKUP_FILE_CHARS) { "файл бэкапа слишком большой" } val obj = JSONObject(raw) require(obj.optString("format") == "wdtt-server-backup") { "это не файл бэкапа WDTT Plus" } - require(obj.optInt("version", 0) == 1) { "неподдерживаемая версия бэкапа" } + val version = obj.optInt("version", 0) + require(version in 1..SERVER_BACKUP_FORMAT_VERSION) { "неподдерживаемая версия бэкапа" } val passwordsB64 = obj.optString("passwords_json_b64") require(passwordsB64.isNotBlank()) { "в бэкапе нет базы passwords.json" } + require(passwordsB64.length <= 6_700_000) { "база в бэкапе слишком большая" } val passwordsJson = decodeBase64Text(passwordsB64) - require(passwordsJson.length <= 5_000_000) { "база в бэкапе слишком большая" } + require(passwordsJson.length <= MAX_SERVER_DATABASE_CHARS) { "база в бэкапе слишком большая" } val wgKeysB64 = obj.optString("wg_keys_dat_b64") + require(wgKeysB64.length <= 5_500) { "wg-keys.dat в бэкапе слишком большой" } val wgKeys = if (wgKeysB64.isNotBlank()) decodeBase64Text(wgKeysB64) else null + if (version >= 2) { + val passwordsSha256 = obj.optString("passwords_json_sha256").lowercase() + require(Regex("^[0-9a-f]{64}$").matches(passwordsSha256)) { + "в бэкапе нет контрольной суммы базы" + } + require(sha256Text(passwordsJson) == passwordsSha256) { + "контрольная сумма базы не совпала" + } + if (wgKeys != null) { + val wgKeysSha256 = obj.optString("wg_keys_dat_sha256").lowercase() + require(Regex("^[0-9a-f]{64}$").matches(wgKeysSha256)) { + "в бэкапе нет контрольной суммы WireGuard-ключей" + } + require(sha256Text(wgKeys) == wgKeysSha256) { + "контрольная сумма WireGuard-ключей не совпала" + } + } + } return parseBackup( passwordsJson = passwordsJson, wgKeysDat = wgKeys, createdAt = obj.optString("created_at", "неизвестно"), - sourceHost = obj.optString("source_host", "неизвестно") + sourceHost = obj.optString("source_host", "неизвестно"), + formatVersion = version, + integrityVerified = version >= 2 ) } private suspend fun loadServerBackupFromUri(context: Context, uri: Uri): ServerBackup = withContext(Dispatchers.IO) { - val raw = context.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() } - ?: throw IllegalArgumentException("не удалось открыть файл") + val raw = context.contentResolver.openInputStream(uri)?.bufferedReader()?.use { reader -> + val result = StringBuilder() + val buffer = CharArray(16 * 1024) + while (true) { + val read = reader.read(buffer) + if (read < 0) break + require(result.length + read <= MAX_SERVER_BACKUP_FILE_CHARS) { + "файл бэкапа слишком большой" + } + result.append(buffer, 0, read) + } + result.toString() + } ?: throw IllegalArgumentException("не удалось открыть файл") parseBackupFile(raw) } @@ -7996,7 +9646,7 @@ private fun parseOwnerProfileFromDb(json: JSONObject?, defaultPorts: String): Se vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(), secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(), profileName = vpnProfileRestorableName(json?.optString("profile_name", "").orEmpty()), - workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128), + workersPerHash = (json?.optInt("workers_per_hash", 18) ?: 18).coerceIn(1, 128), protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp", listenPort = listenPort, sni = json?.optString("sni", "").orEmpty().trim(), @@ -8098,7 +9748,7 @@ private fun ownerProfileInstallDiffLines( if (localComparable.profileName.isNotBlank() && serverComparable.profileName != localComparable.profileName) { add("Название профиля: сервер — ${serverComparable.profileName.ifBlank { "стандартное" }}, приложение — ${localComparable.profileName}") } - if (localComparable.workersPerHash != 16 && serverComparable.workersPerHash != localComparable.workersPerHash) { + if (localComparable.workersPerHash != 18 && serverComparable.workersPerHash != localComparable.workersPerHash) { add("Потоки на хеш: сервер — ${serverComparable.workersPerHash}, приложение — ${localComparable.workersPerHash}") } if (localComparable.protocol != "udp" && serverComparable.protocol != localComparable.protocol) { @@ -8156,43 +9806,49 @@ private fun normalizeDnsValues(first: String, second: String = ""): String = .filter { it.isNotBlank() } .joinToString(",") -private fun outboundProfilesDiffer(server: OutboundServerSnapshot, local: OutboundProfileForms): Boolean { - fun value(raw: String): String = raw.trim().replace("\r\n", "\n") - val serverValues = listOf( - server.localProxyPort, - server.localProxyLogin, - server.localProxyPassword, - server.externalProxyKindName, - server.externalProxyHost, - server.externalProxyPort, - server.externalProxyLogin, - server.externalProxyPassword, - server.wireGuardExitHost, - server.wireGuardExitSshPort, - server.wireGuardExitUser, - server.wireGuardExitPassword, - server.wireGuardExitPort, - server.wireGuardExitDns, - server.importedWireGuardConfig - ).map(::value) - val localValues = listOf( - local.localProxyPort, - local.localProxyLogin, - local.localProxyPassword, - local.externalProxyKindName, - local.externalProxyHost, - local.externalProxyPort, - local.externalProxyLogin, - local.externalProxyPassword, - local.wireGuardExitHost, - local.wireGuardExitSshPort, - local.wireGuardExitUser, - local.wireGuardExitPassword, - local.wireGuardExitPort, - local.wireGuardExitDns, - local.importedWireGuardConfig - ).map(::value) - return serverValues != localValues +internal fun outboundProfilesDiffer( + server: OutboundServerSnapshot, + local: OutboundProfileForms +): Boolean { + fun text(raw: String): String = raw.trim().replace("\r\n", "\n").replace('\r', '\n') + fun port(raw: String): String = raw.filter(Char::isDigit).take(5) + // Не сравниваем автоматически созданные заготовки для ещё не настроенных режимов. + // Иначе новый логин/пароль прокси или стандартные порты чистой установки выглядят + // как пользовательское изменение, хотя на сервер они пока ни на что не влияют. + val localProxyDiffers = server.localProxyPresent && listOf( + port(server.localProxyPort) to port(local.localProxyPort), + text(server.localProxyLogin) to text(local.localProxyLogin), + text(server.localProxyPassword) to text(local.localProxyPassword) + ).any { (serverValue, localValue) -> serverValue != localValue } + + val externalProxyConfigured = server.externalProxyPresent || + local.externalProxyHost.isNotBlank() + val externalProxyDiffers = externalProxyConfigured && listOf( + text(server.externalProxyKindName) to text(local.externalProxyKindName), + text(server.externalProxyHost) to text(local.externalProxyHost), + port(server.externalProxyPort) to port(local.externalProxyPort), + text(server.externalProxyLogin) to text(local.externalProxyLogin), + text(server.externalProxyPassword) to text(local.externalProxyPassword) + ).any { (serverValue, localValue) -> serverValue != localValue } + + val wireGuardVpsConfigured = server.mode == "wireguard_vps" || + server.wireGuardExitHost.isNotBlank() || + local.wireGuardExitHost.isNotBlank() + val wireGuardVpsDiffers = wireGuardVpsConfigured && listOf( + text(server.wireGuardExitHost) to text(local.wireGuardExitHost), + port(server.wireGuardExitSshPort) to port(local.wireGuardExitSshPort), + text(server.wireGuardExitUser) to text(local.wireGuardExitUser), + port(server.wireGuardExitPort) to port(local.wireGuardExitPort) + ).any { (serverValue, localValue) -> serverValue != localValue } + + val importedWireGuardConfigured = server.mode == "imported_wg" || + server.importedWireGuardConfig.isNotBlank() || + local.importedWireGuardConfig.isNotBlank() + val importedWireGuardDiffers = importedWireGuardConfigured && + text(server.importedWireGuardConfig) != text(local.importedWireGuardConfig) + + return localProxyDiffers || externalProxyDiffers || + wireGuardVpsDiffers || importedWireGuardDiffers } private suspend fun compareDeployWithServer( @@ -8226,9 +9882,12 @@ private suspend fun compareDeployWithServer( val raw = readRemotePasswordsJson(ssh) ?: throw IllegalStateException("на сервере не найдена база доступа") val db = JSONObject(raw) - validatePasswordsDbStructure(db) + val mainPasswordNeedsRecovery = + validatePasswordsDbForPreserving(db, request.mainPass) - if (db.optString("main_password") != request.mainPass) { + if (mainPasswordNeedsRecovery) { + overwriteLines += "Главный пароль владельца (пустое поле сервера будет восстановлено)" + } else if (db.optString("main_password") != request.mainPass) { overwriteLines += "Главный пароль владельца" } if (request.adminId.isNotBlank() && db.optString("admin_id") != request.adminId) { @@ -8406,6 +10065,63 @@ internal fun mergeServerDatabaseEntries( } } +internal fun prepareServerDatabaseForTarget( + sourceJson: String, + currentDbJson: String?, + merge: Boolean, + portsSpec: String, + dnsValue: String, + publicHost: String, + mainPasswordOverride: String = "", + adminIdOverride: String = "", + botTokenOverride: String = "" +): String { + require(portsSpec.isValidPortsSpec()) { "некорректные порты целевого сервера" } + require(publicHost.isValidPublicHost()) { "некорректный адрес целевого сервера" } + val source = JSONObject(sourceJson) + validatePasswordsDbStructure(source) + val mergeIntoExisting = merge && !currentDbJson.isNullOrBlank() + val target = if (mergeIntoExisting) { + JSONObject(currentDbJson) + } else { + JSONObject(source.toString()) + } + + if (mergeIntoExisting) { + if (validatePasswordsDbForPreserving(target, source.optString("main_password"))) { + target.put("main_password", source.optString("main_password")) + } + mergeServerDatabaseEntries(source, target, portsSpec) + if (!target.has("admin_id") || target.optString("admin_id").isBlank()) { + target.put("admin_id", source.optString("admin_id")) + } + if (!target.has("bot_token") || target.optString("bot_token").isBlank()) { + target.put("bot_token", source.optString("bot_token")) + } + } else { + val passwords = target.optJSONObject("passwords") ?: JSONObject() + passwords.keys().forEach { key -> + passwords.optJSONObject(key)?.put("ports", portsSpec) + } + target.optJSONObject("admin_profile")?.apply { + put("ports", portsSpec) + put("listen_port", portsSpec.substringAfterLast(",").toInt()) + } + } + + if (mainPasswordOverride.isNotBlank()) target.put("main_password", mainPasswordOverride) + if (adminIdOverride.isNotBlank()) target.put("admin_id", adminIdOverride) + if (botTokenOverride.isNotBlank()) target.put("bot_token", botTokenOverride) + target.put("dns", dnsValue) + target.put("default_ports", portsSpec) + target.put("public_ip", publicHost) + if (!target.has("passwords")) target.put("passwords", JSONObject()) + if (!target.has("devices")) target.put("devices", JSONObject()) + if (!target.has("max_passwords")) target.put("max_passwords", 50) + validatePasswordsDbStructure(target) + return target.toString(2) +} + private fun normalizeDbForTarget( backup: ServerBackup, currentDbJson: String?, @@ -8413,43 +10129,21 @@ private fun normalizeDbForTarget( request: DeployRequest ): String { val portsSpec = "${request.dtlsPort},${request.wgPort},${request.localPort}" - val dnsValue = listOf(request.dns1, request.dns2).filter { it.isNotBlank() }.joinToString(",").ifBlank { backup.dns.ifBlank { "1.1.1.1,1.0.0.1" } } - val source = JSONObject(backup.passwordsJson) - val target = if (mode == ServerImportMode.Replace) { - JSONObject(source.toString()) - } else { - currentDbJson?.takeIf { it.isNotBlank() }?.let { JSONObject(it) } ?: JSONObject() - } - - if (mode == ServerImportMode.Merge) { - mergeServerDatabaseEntries(source, target, portsSpec) - if (!target.has("main_password") || target.optString("main_password").isBlank()) { - target.put("main_password", backup.mainPassword) - } - if (!target.has("admin_id") || target.optString("admin_id").isBlank()) { - target.put("admin_id", backup.adminId) - } - if (!target.has("bot_token") || target.optString("bot_token").isBlank()) { - target.put("bot_token", backup.botToken) - } - } else { - val passwords = target.optJSONObject("passwords") ?: JSONObject() - passwords.keys().forEach { key -> - passwords.optJSONObject(key)?.put("ports", portsSpec) - } - } - - if (request.mainPass.isNotBlank()) target.put("main_password", request.mainPass) - if (request.adminId.isNotBlank()) target.put("admin_id", request.adminId) - if (request.botToken.isNotBlank()) target.put("bot_token", request.botToken) - target.put("dns", dnsValue) - target.put("default_ports", portsSpec) - target.put("public_ip", request.host) - if (!target.has("passwords")) target.put("passwords", JSONObject()) - if (!target.has("devices")) target.put("devices", JSONObject()) - if (!target.has("max_passwords")) target.put("max_passwords", 50) - validatePasswordsDbStructure(target) - return target.toString(2) + val dnsValue = listOf(request.dns1, request.dns2) + .filter { it.isNotBlank() } + .joinToString(",") + .ifBlank { backup.dns.ifBlank { "1.1.1.1,1.0.0.1" } } + return prepareServerDatabaseForTarget( + sourceJson = backup.passwordsJson, + currentDbJson = currentDbJson, + merge = mode == ServerImportMode.Merge, + portsSpec = portsSpec, + dnsValue = dnsValue, + publicHost = request.host, + mainPasswordOverride = request.mainPass, + adminIdOverride = request.adminId, + botTokenOverride = request.botToken + ) } private fun applyServerImport( @@ -8464,21 +10158,23 @@ private fun applyServerImport( val preparedDb = normalizeDbForTarget(backup, currentDb, mode, request) val dbFile = File(context.cacheDir, "wdtt-import-passwords.json") val wgFile = File(context.cacheDir, "wdtt-import-wg-keys.dat") + val remoteDbFile = "/tmp/wdtt-import-passwords.json" + val remoteWgFile = "/tmp/wdtt-import-wg-keys.dat" dbFile.writeText(preparedDb) try { - ssh.upload(dbFile, "/tmp/wdtt-import-passwords.json") + ssh.upload(dbFile, remoteDbFile, permissions = 0b110000000) val replaceWgKeys = mode == ServerImportMode.Replace && backup.hasWgKeys if (replaceWgKeys) { wgFile.writeText(backup.wgKeysDat.orEmpty()) - ssh.upload(wgFile, "/tmp/wdtt-import-wg-keys.dat") + ssh.upload(wgFile, remoteWgFile, permissions = 0b110000000) } val command = buildString { append("systemctl stop wdtt 2>/dev/null || true; ") append("mkdir -p /etc/wdtt; ") - append("install -m 600 /tmp/wdtt-import-passwords.json /etc/wdtt/passwords.json; ") - append("rm -f /tmp/wdtt-import-passwords.json; ") + append("install -m 600 ${shellQuote(remoteDbFile)} /etc/wdtt/passwords.json; ") + append("rm -f ${shellQuote(remoteDbFile)}; ") if (replaceWgKeys) { - append("install -m 600 /tmp/wdtt-import-wg-keys.dat /etc/wdtt/wg-keys.dat; rm -f /tmp/wdtt-import-wg-keys.dat; ") + append("install -m 600 ${shellQuote(remoteWgFile)} /etc/wdtt/wg-keys.dat; rm -f ${shellQuote(remoteWgFile)}; ") } if (restartService) { append("systemctl restart wdtt 2>/dev/null || true; ") @@ -8490,6 +10186,12 @@ private fun applyServerImport( throw IllegalStateException("wdtt.service не стал active после импорта") } } finally { + runCatching { + ssh.exec( + rootCommand("rm -f ${shellQuote(remoteDbFile)} ${shellQuote(remoteWgFile)}"), + timeout = 10_000L + ) + } dbFile.delete() wgFile.delete() } @@ -8628,8 +10330,7 @@ private fun validatePreservedServerState(beforeJson: String, afterJson: String) val safeExpiryCutoff = System.currentTimeMillis() / 1000L + 300L beforePasswords.keys().forEach { password -> val oldEntry = beforePasswords.optJSONObject(password) ?: return@forEach - val expiresAt = oldEntry.optLong("expires_at", 0) - if (expiresAt != 0L && expiresAt <= safeExpiryCutoff) return@forEach + if (!passwordShouldRemainAfterImport(oldEntry, safeExpiryCutoff)) return@forEach val newEntry = afterPasswords.optJSONObject(password) ?: throw IllegalStateException("после обновления пропал действующий клиент ${password.take(4)}…") listOf("device_id", "label", "vk_hash", "ports").forEach { field -> @@ -8640,9 +10341,31 @@ private fun validatePreservedServerState(beforeJson: String, afterJson: String) require(oldEntry.optLong("expires_at", 0) == newEntry.optLong("expires_at", 0)) { "после обновления изменился срок клиента ${password.take(4)}…" } + require(oldEntry.optLong("purge_after", 0) == newEntry.optLong("purge_after", 0)) { + "после обновления изменился срок хранения записи клиента ${password.take(4)}…" + } require(oldEntry.optBoolean("is_deactivated", false) == newEntry.optBoolean("is_deactivated", false)) { "после обновления изменился статус клиента ${password.take(4)}…" } + listOf("down_bytes", "up_bytes").forEach { field -> + require(oldEntry.optLong(field, 0L) == newEntry.optLong(field, 0L)) { + "после обновления изменилось поле $field у клиента ${password.take(4)}…" + } + } + listOf("bind_history", "traffic").forEach { field -> + require( + oldEntry.optJSONArray(field)?.toString().orEmpty() == + newEntry.optJSONArray(field)?.toString().orEmpty() + ) { + "после обновления изменилась история $field у клиента ${password.take(4)}…" + } + } + require( + oldEntry.optJSONObject("traffic_imports")?.toString().orEmpty() == + newEntry.optJSONObject("traffic_imports")?.toString().orEmpty() + ) { + "после обновления изменилась история учёта перенесённого трафика клиента ${password.take(4)}…" + } val deviceId = oldEntry.optString("device_id", "") if (deviceId.isNotBlank()) { require(afterDevices.has(deviceId)) { "после обновления пропала привязка устройства клиента ${password.take(4)}…" } @@ -8650,6 +10373,53 @@ private fun validatePreservedServerState(beforeJson: String, afterJson: String) } } +private fun passwordShouldRemainAfterImport(entry: JSONObject, safeExpiryCutoff: Long): Boolean { + val expiresAt = entry.optLong("expires_at", 0L) + if (expiresAt == 0L) return true + val purgeAfter = entry.optLong("purge_after", 0L) + return maxOf(expiresAt, purgeAfter) > safeExpiryCutoff +} + +private fun validateImportedDevice( + deviceId: String, + expected: JSONObject, + actual: JSONObject, + allowIpReassignment: Boolean +) { + val stringFields = listOf( + "device_id", + "priv_key", + "pub_key", + "name", + "manufacturer", + "brand", + "model", + "android_version", + "abi", + "app_version", + "locale", + "country", + "time_zone", + "remote_ip" + ) + stringFields.forEach { field -> + require(expected.optString(field, "") == actual.optString(field, "")) { + "после импорта изменилось поле $field у устройства ${deviceId.take(8)}…" + } + } + if (!allowIpReassignment) { + require(expected.optString("ip", "") == actual.optString("ip", "")) { + "после импорта изменился внутренний IP устройства ${deviceId.take(8)}…" + } + } + require(expected.optInt("sdk", 0) == actual.optInt("sdk", 0)) { + "после импорта изменилось поле sdk у устройства ${deviceId.take(8)}…" + } + require(expected.optLong("last_seen_at", 0L) == actual.optLong("last_seen_at", 0L)) { + "после импорта изменилось поле last_seen_at у устройства ${deviceId.take(8)}…" + } +} + internal fun validateImportedServerState( sourceJson: String, beforeJson: String?, @@ -8667,14 +10437,14 @@ internal fun validateImportedServerState( val sourcePasswords = source.optJSONObject("passwords") ?: JSONObject() val beforePasswords = beforeJson?.let { JSONObject(it).optJSONObject("passwords") } ?: JSONObject() val afterPasswords = after.optJSONObject("passwords") ?: JSONObject() + val sourceDevices = source.optJSONObject("devices") ?: JSONObject() val afterDevices = after.optJSONObject("devices") ?: JSONObject() val safeExpiryCutoff = System.currentTimeMillis() / 1000L + 300L sourcePasswords.keys().forEach { password -> if (!replace && beforePasswords.has(password)) return@forEach val expected = sourcePasswords.optJSONObject(password) ?: return@forEach - val expiresAt = expected.optLong("expires_at", 0L) - if (expiresAt != 0L && expiresAt <= safeExpiryCutoff) return@forEach + if (!passwordShouldRemainAfterImport(expected, safeExpiryCutoff)) return@forEach val actual = afterPasswords.optJSONObject(password) ?: throw IllegalStateException("после импорта не найден клиент ${password.take(4)}…") listOf("device_id", "label", "vk_hash").forEach { field -> @@ -8682,7 +10452,7 @@ internal fun validateImportedServerState( "после импорта изменилось поле $field у клиента ${password.take(4)}…" } } - listOf("expires_at", "down_bytes", "up_bytes").forEach { field -> + listOf("expires_at", "purge_after", "down_bytes", "up_bytes").forEach { field -> require(expected.optLong(field, 0L) == actual.optLong(field, 0L)) { "после импорта изменилось поле $field у клиента ${password.take(4)}…" } @@ -8695,11 +10465,104 @@ internal fun validateImportedServerState( "после импорта изменилась история $field у клиента ${password.take(4)}…" } } + require( + expected.optJSONObject("traffic_imports")?.toString().orEmpty() == + actual.optJSONObject("traffic_imports")?.toString().orEmpty() + ) { + "после импорта изменилась история учёта перенесённого трафика у клиента ${password.take(4)}…" + } val deviceId = expected.optString("device_id", "") if (deviceId.isNotBlank()) { - require(afterDevices.has(deviceId)) { - "после импорта отсутствует привязанное устройство клиента ${password.take(4)}…" + val expectedDevice = sourceDevices.optJSONObject(deviceId) + ?: throw IllegalStateException("в бэкапе отсутствует устройство клиента ${password.take(4)}…") + val actualDevice = afterDevices.optJSONObject(deviceId) + ?: throw IllegalStateException("после импорта отсутствует привязанное устройство клиента ${password.take(4)}…") + validateImportedDevice( + deviceId = deviceId, + expected = expectedDevice, + actual = actualDevice, + allowIpReassignment = !replace + ) + } + } + + if (replace) { + require(source.optLong("admin_down_bytes", 0L) == after.optLong("admin_down_bytes", 0L)) { + "после импорта изменился входящий трафик владельца" + } + require(source.optLong("admin_up_bytes", 0L) == after.optLong("admin_up_bytes", 0L)) { + "после импорта изменился исходящий трафик владельца" + } + require( + source.optJSONArray("admin_traffic")?.toString().orEmpty() == + after.optJSONArray("admin_traffic")?.toString().orEmpty() + ) { + "после импорта изменилась история трафика владельца" + } + require(source.optInt("max_passwords", 50) == after.optInt("max_passwords", 50)) { + "после импорта изменился лимит клиентов" + } + + val expectedProfile = source.optJSONObject("admin_profile")?.let { JSONObject(it.toString()) } + val actualProfile = after.optJSONObject("admin_profile") + if (expectedProfile != null) { + val targetPorts = after.optString("default_ports", "56000,56001,9000") + expectedProfile.put("ports", targetPorts) + expectedProfile.put("listen_port", targetPorts.substringAfterLast(",").toInt()) + listOf( + "vk_hashes", + "secondary_vk_hash", + "profile_name", + "protocol", + "sni", + "ports" + ).forEach { field -> + require(expectedProfile.optString(field, "") == actualProfile?.optString(field, "").orEmpty()) { + "после импорта изменилось поле $field профиля владельца" + } } + listOf("workers_per_hash", "listen_port").forEach { field -> + require(expectedProfile.optInt(field, 0) == actualProfile?.optInt(field, 0)) { + "после импорта изменилось поле $field профиля владельца" + } + } + require(expectedProfile.optBoolean("no_dns", false) == actualProfile?.optBoolean("no_dns", false)) { + "после импорта изменилось поле no_dns профиля владельца" + } + require(expectedProfile.optLong("updated_at", 0L) == actualProfile?.optLong("updated_at", 0L)) { + "после импорта изменилось время профиля владельца" + } + require( + expectedProfile.optJSONArray("device_ids")?.toString().orEmpty() == + actualProfile?.optJSONArray("device_ids")?.toString().orEmpty() + ) { + "после импорта изменился список устройств владельца" + } + } + + val purgeableDeviceIds = sourcePasswords.keys() + .asSequence() + .mapNotNull { sourcePasswords.optJSONObject(it) } + .filterNot { passwordShouldRemainAfterImport(it, safeExpiryCutoff) } + .mapNotNull { it.optString("device_id", "").takeIf(String::isNotBlank) } + .toSet() + val retainedDeviceIds = sourcePasswords.keys() + .asSequence() + .mapNotNull { sourcePasswords.optJSONObject(it) } + .filter { passwordShouldRemainAfterImport(it, safeExpiryCutoff) } + .mapNotNull { it.optString("device_id", "").takeIf(String::isNotBlank) } + .toMutableSet() + expectedProfile?.optJSONArray("device_ids")?.let { ids -> + for (index in 0 until ids.length()) { + ids.optString(index).takeIf(String::isNotBlank)?.let(retainedDeviceIds::add) + } + } + sourceDevices.keys().forEach { deviceId -> + if (deviceId in purgeableDeviceIds && deviceId !in retainedDeviceIds) return@forEach + val expectedDevice = sourceDevices.optJSONObject(deviceId) ?: return@forEach + val actualDevice = afterDevices.optJSONObject(deviceId) + ?: throw IllegalStateException("после импорта отсутствует устройство ${deviceId.take(8)}…") + validateImportedDevice(deviceId, expectedDevice, actualDevice, allowIpReassignment = false) } } } @@ -8759,7 +10622,7 @@ private suspend fun performDeploy( if (mode == DeployMode.PreserveData || importPlan != null) { onProgress(0.055f, "Проверка сохранённых данных...") val currentDbJson = readRemotePasswordsJson(ssh)?.also { - validatePasswordsDbStructure(JSONObject(it)) + validatePasswordsDbForPreserving(JSONObject(it), mainPass) } if (mode == DeployMode.PreserveData) { if (importPlan == null) preservedDbJson = currentDbJson @@ -8825,10 +10688,11 @@ private suspend fun performDeploy( val verifyOutput = ssh.exec( rootCommand( "sleep 2; printf 'BINARY=%s\\n' \"$([ -x /usr/local/bin/wdtt-server ] && echo 1 || echo 0)\"; " + - "printf 'CONFIG=%s\\n' \"$([ -d /etc/wdtt ] && echo 1 || echo 0)\"; " + - "printf 'SERVICE=%s\\n' \"$(systemctl is-active wdtt 2>/dev/null || true)\"; " + - "printf 'ADMIN_SOCKET=%s\\n' \"$([ -S /run/wdtt/admin.sock ] && echo 1 || echo 0)\"; " + - "printf 'SERVER_SHA256=%s\\n' \"$(sha256sum /usr/local/bin/wdtt-server 2>/dev/null | awk '{print ${'$'}1}')\"" + "printf 'CONFIG=%s\\n' \"$([ -d /etc/wdtt ] && echo 1 || echo 0)\"; " + + "printf 'SERVICE=%s\\n' \"$(systemctl is-active wdtt 2>/dev/null || true)\"; " + + "printf 'ADMIN_SOCKET=%s\\n' \"$([ -S /run/wdtt/admin.sock ] && echo 1 || echo 0)\"; " + + "printf 'SERVER_SHA256=%s\\n' \"$(sha256sum /usr/local/bin/wdtt-server 2>/dev/null | awk '{print ${'$'}1}')\"; " + + "printf 'SERVER_VERSION=%s\\n' \"$(/usr/local/bin/wdtt-server --version 2>/dev/null | head -n 1)\"" ), timeout = 20000L ) @@ -8838,8 +10702,10 @@ private suspend fun performDeploy( val adminSocketOk = Regex("^ADMIN_SOCKET=1$", RegexOption.MULTILINE).containsMatchIn(verifyOutput) val installedSha256 = Regex("^SERVER_SHA256=([0-9a-fA-F]{64})$", RegexOption.MULTILINE) .find(verifyOutput)?.groupValues?.getOrNull(1)?.lowercase() + val installedServerVersion = Regex("^SERVER_VERSION=([0-9][0-9A-Za-z._-]*)$", RegexOption.MULTILINE) + .find(verifyOutput)?.groupValues?.getOrNull(1).orEmpty() val binaryCurrent = installedSha256 == expectedServerSha256 - if (!binaryOk || !configOk || !serviceActive || !adminSocketOk || !binaryCurrent) { + if (!binaryOk || !configOk || !serviceActive || !adminSocketOk || !binaryCurrent || installedServerVersion.isBlank()) { DeployManager.writeError("Deploy verify failed: ${verifyOutput.take(500)}") val missing = buildList { if (!binaryOk) add("бинарник") @@ -8847,6 +10713,7 @@ private suspend fun performDeploy( if (!serviceActive) add("служба wdtt") if (!adminSocketOk) add("admin-сокет новой версии") if (!binaryCurrent) add("актуальная версия бинарника") + if (installedServerVersion.isBlank()) add("версия серверной части") }.joinToString(", ") throw IllegalStateException("скрипт завершился, но проверка не прошла: $missing") } @@ -8866,8 +10733,9 @@ private suspend fun performDeploy( cleanupServerUpdateRollback(ssh) rollbackPrepared = false } + DeployManager.installedServerVersion.value = installedServerVersion DeployManager.stopDeploy("success") - TunnelManager.addDeploySuccessLog("Деплой успешно завершён. Сервис активен.") + TunnelManager.addDeploySuccessLog("Деплой успешно завершён. Серверная часть WDTT Plus $installedServerVersion, сервис активен.") return@withContext true } else if (output.contains("error:")) { DeployManager.writeError("Deploy script output contains error") @@ -8992,7 +10860,7 @@ private fun ServerImportConfirmDialog( ) { val portsSpec = "${request.dtlsPort},${request.wgPort},${request.localPort}" val dnsValue = listOf(request.dns1, request.dns2).filter { it.isNotBlank() }.joinToString(",") - val modeText = if (mode == ServerImportMode.Replace) "Заменить базу сервера бэкапом" else "Добавить отсутствующие пароли и устройства" + val modeText = if (mode == ServerImportMode.Replace) "Заменить базу сервера бэкапом" else "Добавить отсутствующих клиентов и устройства" val mainPasswordText = when { request.mainPass.isNotBlank() -> "из текущих секретов деплоя" mode == ServerImportMode.Replace && backup.mainPassword.isNotBlank() -> "из бэкапа" @@ -9055,7 +10923,7 @@ private fun ServerImportConfirmDialog( ) { ConfirmLine("Режим", modeText) ConfirmLine("Бэкап", "${backup.sourceHost}, ${backup.createdAt}") - ConfirmLine("Данные", "${backup.passwordCount} паролей, ${backup.deviceCount} устройств") + ConfirmLine("Данные", "${backup.passwordCount} клиентов, ${backup.deviceCount} устройств") ConfirmLine("Адрес сервера для ссылок", request.host) ConfirmLine("Порты быстрых ссылок", portsSpec) ConfirmLine("Главный пароль", mainPasswordText) @@ -9068,7 +10936,7 @@ private fun ServerImportConfirmDialog( if (mode == ServerImportMode.Replace) { "В режиме «Заменить» текущая база паролей и устройств на целевом сервере будет перезаписана. Используйте это для переезда на новый сервер." } else { - "В режиме «Добавить» совпадающие пароли и устройства не перезаписываются. Это безопаснее для уже используемого сервера." + "В режиме «Добавить» совпадающие клиенты и устройства не перезаписываются. Это безопаснее для уже используемого сервера." }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant @@ -10079,7 +11947,7 @@ private fun ExistingInstallDialog( Text("Будут заменены серверные значения:", fontWeight = FontWeight.SemiBold) comparison.overwriteLines.forEach { Text("• $it", style = MaterialTheme.typography.bodySmall) } Text( - "Если нужны значения сервера, отмените установку и сначала выполните «Подключиться (без установки)». Для выходного IP используйте «Заполнить».", + "Если нужны значения сервера, отмените установку и сначала выполните «Подключиться (без установки)». Для выходного IP используйте «Загрузить настройки».", style = MaterialTheme.typography.bodySmall ) } 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 e2c20ba..5ca12a9 100644 --- a/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt @@ -3,7 +3,9 @@ package com.wdtt.plus.ui import android.content.pm.PackageManager import androidx.compose.foundation.Image import androidx.compose.foundation.background -import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.rememberScrollableState +import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items @@ -57,76 +59,6 @@ object AppCache { var cachedList: List? = null } -private val VpnDetectionExactPackages = setOf( - "ru.sberbankmobile", - "ru.tinkoff.mb", - "ru.vtb24.mobilebanking.android", - "ru.alfabank.mobile.android", - "ru.ozon.app.android", - "com.wildberries.ru", - "ru.beru.android", - "ru.megamarket", - "ru.sbermarket", - "ru.samokat.android", - "com.avito.android", - "ru.yandex.searchplugin", - "ru.yandex.yandexmaps", - "ru.yandex.music", - "ru.kinopoisk", - "com.yandex.browser", - "ru.yandex.taxi", - "com.vkontakte.android", - "com.vk.vkvideo", - "ru.vk.music", - "ru.ok.android", - "ru.rutube.app", - "ru.mail.mailapp", - "ru.mail.cloud", - "ru.mts", - "ru.beeline.services", - "ru.tele2.mytele2", - "ru.megafon.mlk", - "ru.rostel", - "ru.gosuslugi.mobile", - "ru.vk.store", - "ru.dublgis.dgismobile", - "ru.maximoff.max" -) - -private val VpnDetectionKeywords = listOf( - "sber", "сбер", - "tinkoff", "t-bank", "tbank", "тинькофф", "тбанк", - "vtb", "втб", - "alfa", "alpha", "альфа", - "ozon", "озон", - "wildberries", "вайлдберриз", - "yandex", "яндекс", - "vkontakte", "вконтакте", - "rutube", "рутуб", - "gosuslugi", "госуслуг", - "dublgis", "2gis", "dgis", "дубльгис", - "avito", "авито", - "mts", "мтс", - "beeline", "билайн", - "megafon", "мегафон", - "tele2", "теле2", - "mail.ru", "mailapp", - "ok.ru", "odnoklassniki", - "kinopoisk", "кинопоиск", - "samokat", "самокат", - "megamarket", "sbermarket", - "rostel", "ростел", - "maximoff" -) - -private fun AppItem.matchesVpnDetectionApp(): Boolean { - val packageLower = packageName.lowercase() - if (packageLower in VpnDetectionExactPackages) return true - val titleLower = name.lowercase() - val haystack = "$packageLower $titleLower" - return VpnDetectionKeywords.any { keyword -> haystack.contains(keyword) } -} - @OptIn(ExperimentalMaterial3Api::class) @Composable fun ExceptionsTab( @@ -229,22 +161,50 @@ fun ExceptionsTab( } } - val collapsingHeaderConnection = remember(topBlockHeightPx) { + fun consumeHeaderScroll(deltaPx: Float, allowExpand: Boolean): Float { + val previousOffset = topBlockOffsetPx + val nextOffset = collapsingHeaderOffsetAfterScroll( + currentOffsetPx = previousOffset, + headerHeightPx = topBlockHeightPx, + deltaPx = deltaPx, + allowExpand = allowExpand, + ) + if (nextOffset != previousOffset) { + topBlockOffsetPx = nextOffset + topBlockPositionInitialized = true + } + return nextOffset - previousOffset + } + + val collapsingHeaderConnection = remember(topBlockHeightPx, listState) { object : NestedScrollConnection { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { if (topBlockHeightPx <= 0f) return Offset.Zero val delta = available.y - val canCollapse = delta < 0f && topBlockOffsetPx > -topBlockHeightPx - val canExpand = delta > 0f && topBlockOffsetPx < 0f - if (!canCollapse && !canExpand) return Offset.Zero + val consumed = consumeHeaderScroll( + deltaPx = delta, + allowExpand = !listState.canScrollBackward, + ) + return Offset(x = 0f, y = consumed) + } - val previousOffset = topBlockOffsetPx - topBlockOffsetPx = (previousOffset + delta).coerceIn(-topBlockHeightPx, 0f) - topBlockPositionInitialized = true - return Offset(x = 0f, y = topBlockOffsetPx - previousOffset) + override fun onPostScroll( + consumed: Offset, + available: Offset, + source: NestedScrollSource, + ): Offset { + if (available.y <= 0f) return Offset.Zero + val headerConsumed = consumeHeaderScroll( + deltaPx = available.y, + allowExpand = true, + ) + return Offset(x = 0f, y = headerConsumed) } } } + val searchHeaderScrollState = rememberScrollableState { deltaPx -> + consumeHeaderScroll(deltaPx = deltaPx, allowExpand = true) + } val collapseFraction = if (topBlockHeightPx > 0f) { (-topBlockOffsetPx / topBlockHeightPx).coerceIn(0f, 1f) } else { @@ -356,7 +316,12 @@ fun ExceptionsTab( OutlinedButton( onClick = { val detectedPackages = appsList - .filter { it.matchesVpnDetectionApp() } + .filter { + matchesQuickExclusionApp( + name = it.name, + packageName = it.packageName, + ) + } .map { it.packageName } .toSet() if (detectedPackages.isEmpty()) { @@ -383,7 +348,7 @@ fun ExceptionsTab( ) } Text( - "Банки, маркетплейсы и другие приложения, чувствительные к VPN. Поиск выполняется по известным названиям.", + "Приложения из белых списков мобильного интернета и другие сервисы, чувствительные к VPN. Выбираются только найденные на устройстве.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 6.dp) @@ -409,7 +374,11 @@ fun ExceptionsTab( modifier = Modifier .fillMaxWidth() .padding(top = 16.dp * collapseFraction, bottom = 12.dp) - .height(52.dp), + .height(52.dp) + .scrollable( + state = searchHeaderScrollState, + orientation = Orientation.Vertical, + ), shape = RoundedCornerShape(16.dp), leadingIcon = { Icon(Icons.Default.Search, null, modifier = Modifier.size(20.dp)) }, singleLine = true, 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 4eb27ab..23378b2 100644 --- a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt +++ b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt @@ -12,6 +12,7 @@ import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -19,7 +20,6 @@ import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.clickable import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll -import kotlinx.coroutines.launch import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape @@ -37,7 +37,11 @@ import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.wdtt.plus.SettingsStore +import com.wdtt.plus.TunnelManager +import com.wdtt.plus.TunnelStopCoordinator +import com.wdtt.plus.TunnelStopResult import com.wdtt.plus.sanitizeVpnProfileNameInput +import com.wdtt.plus.vpnProfileDefaultName import com.wdtt.plus.vpnProfileDisplayName import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight @@ -56,6 +60,12 @@ import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Share import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties +import android.widget.Toast +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull + +private const val PROFILE_RESET_TIMEOUT_MS = 10_000L @OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class) @Composable @@ -65,6 +75,7 @@ fun FloatingToolbar( onActiveProfileChange: (Int) -> Unit, onProfileNameChange: (Int, String) -> Unit, interfaceRole: String, + adminModeAllowed: Boolean, onInterfaceRoleChange: (String) -> Unit, currentTheme: String, onThemeChange: (String) -> Unit, @@ -80,10 +91,19 @@ fun FloatingToolbar( modifier: Modifier = Modifier ) { val context = LocalContext.current + val scope = rememberCoroutineScope() val settingsStore = remember { SettingsStore(context) } val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false) val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList()) val trustedWifiRuntime by com.wdtt.plus.TrustedWifiManager.state.collectAsStateWithLifecycle() + val customVkCredentialsEnabled by settingsStore.customVkCredentialsEnabled.collectAsStateWithLifecycle(initialValue = false) + val customVkCredentialsComplete by settingsStore.customVkCredentialsComplete.collectAsStateWithLifecycle(initialValue = false) + val savedToolbarYFraction by settingsStore.floatingToolbarYFraction.collectAsStateWithLifecycle( + initialValue = -2f + ) + val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle() + val tunnelTransition by TunnelManager.transition.collectAsStateWithLifecycle() + val connectedProfile by TunnelManager.activeTunnelProfile.collectAsStateWithLifecycle() val configuration = LocalConfiguration.current val density = LocalDensity.current val screenHeightPx = remember(configuration.screenHeightDp, density) { @@ -96,19 +116,39 @@ fun FloatingToolbar( var parentWidthPx by remember { mutableFloatStateOf(0f) } var parentHeightPx by remember { mutableFloatStateOf(0f) } - var offsetY by rememberSaveable { mutableFloatStateOf(-1f) } + var offsetY by remember { mutableFloatStateOf(-1f) } + var toolbarPositionRestored by remember { mutableStateOf(false) } var isRightSide by rememberSaveable { mutableStateOf(true) } var isExpanded by rememberSaveable { mutableStateOf(false) } var tabHeightPx by remember { mutableFloatStateOf(0f) } var panelHeightPx by remember { mutableFloatStateOf(0f) } var renamingProfile by remember { mutableStateOf(null) } + var resettingProfile by remember { mutableStateOf(null) } + var resetCountdown by remember { mutableIntStateOf(5) } + var resetInProgress by remember { mutableStateOf(false) } var profileNameInput by rememberSaveable { mutableStateOf("") } var showTrustedWifiSettings by rememberSaveable { mutableStateOf(false) } + var showVkClientSettings by rememberSaveable { mutableStateOf(false) } val tabWidthDp = 42.dp val tabHeightDp = 52.dp val panelWidthDp = 220.dp - val isAdminRole = interfaceRole != "user" + // Move the thumb immediately on tap instead of waiting for the DataStore round trip. + // The persisted value still remains the source of truth and resynchronizes this state. + var displayedInterfaceRole by remember(interfaceRole, adminModeAllowed) { + mutableStateOf(if (adminModeAllowed) interfaceRole else "user") + } + val isAdminRole = adminModeAllowed && displayedInterfaceRole == "admin" + + LaunchedEffect(resettingProfile) { + resetCountdown = 5 + if (resettingProfile != null) { + while (resetCountdown > 0) { + delay(1_000L) + resetCountdown-- + } + } + } val tabWidthPx = remember(density) { with(density) { tabWidthDp.toPx() } } val fallbackTabHeightPx = remember(density) { with(density) { tabHeightDp.toPx() } } @@ -128,7 +168,7 @@ fun FloatingToolbar( val minOffsetY = safeTopPx + edgePaddingPx val maxOffsetY = (currentParentHeight - safeBottomPx - floatingHeightPx - edgePaddingPx) .coerceAtLeast(minOffsetY) - val defaultOffsetY = (currentParentHeight * 0.24f).coerceIn(minOffsetY, maxOffsetY) + val defaultOffsetY = (currentParentHeight * 0.30f).coerceIn(minOffsetY, maxOffsetY) val targetXPx = if (isRightSide) currentParentWidth - tabWidthPx else 0f @@ -138,8 +178,29 @@ fun FloatingToolbar( label = "tab_shift" ) - LaunchedEffect(minOffsetY, maxOffsetY) { - offsetY = if (offsetY < 0f) defaultOffsetY else offsetY.coerceIn(minOffsetY, maxOffsetY) + LaunchedEffect(savedToolbarYFraction, minOffsetY, maxOffsetY) { + if (savedToolbarYFraction < -1f) return@LaunchedEffect + offsetY = if (!toolbarPositionRestored || offsetY < 0f) { + if (savedToolbarYFraction >= 0f && maxOffsetY > minOffsetY) { + minOffsetY + (maxOffsetY - minOffsetY) * savedToolbarYFraction + } else { + defaultOffsetY + } + } else { + offsetY.coerceIn(minOffsetY, maxOffsetY) + } + toolbarPositionRestored = true + } + + fun persistToolbarPosition() { + if (!toolbarPositionRestored) return + val availableRange = maxOffsetY - minOffsetY + val fraction = if (availableRange > 0f) { + ((offsetY - minOffsetY) / availableRange).coerceIn(0f, 1f) + } else { + 0f + } + scope.launch { settingsStore.saveFloatingToolbarYFraction(fraction) } } Box( @@ -159,6 +220,8 @@ fun FloatingToolbar( } .pointerInput(minOffsetY, maxOffsetY) { detectDragGestures( + onDragEnd = { persistToolbarPosition() }, + onDragCancel = { persistToolbarPosition() }, onDrag = { change, dragAmount -> change.consume() offsetY = (offsetY + dragAmount.y).coerceIn(minOffsetY, maxOffsetY) @@ -248,7 +311,10 @@ fun FloatingToolbar( .widthIn(min = 72.dp, max = 180.dp) .clip(profileShape) .combinedClickable( - onClick = { onActiveProfileChange(profile) }, + onClick = { + onActiveProfileChange(profile) + isExpanded = false + }, onLongClick = { renamingProfile = profile profileNameInput = profileLabel @@ -280,7 +346,7 @@ fun FloatingToolbar( shape = RoundedCornerShape(12.dp) ) { Icon(Icons.Filled.Share, contentDescription = null, modifier = Modifier.size(18.dp)) - Text(" Передать или получить", fontSize = 12.sp) + Text(" Получить или передать", fontSize = 12.sp) } HorizontalDivider( @@ -340,7 +406,14 @@ fun FloatingToolbar( color = MaterialTheme.colorScheme.onSurface ) Text( - if (isAdminRole) "VPN и настройка своего сервера" else "Подключение и работа VPN", + when { + !adminModeAllowed -> + "Режим «Админ» доступен для самостоятельного профиля" + isAdminRole -> + "VPN и настройка своего сервера" + else -> + "Подключение и работа VPN" + }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, lineHeight = 15.sp @@ -348,7 +421,14 @@ fun FloatingToolbar( } Switch( checked = isAdminRole, - onCheckedChange = { checked -> onInterfaceRoleChange(if (checked) "admin" else "user") }, + onCheckedChange = { checked -> + val role = if (checked) "admin" else "user" + if (role != displayedInterfaceRole) { + displayedInterfaceRole = role + onInterfaceRoleChange(role) + } + }, + enabled = adminModeAllowed, modifier = Modifier.scale(0.85f) ) } @@ -501,94 +581,41 @@ fun FloatingToolbar( color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) ) - Text( - "Client IDs", - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - fontWeight = FontWeight.SemiBold, - modifier = Modifier.padding(start = 4.dp, bottom = 4.dp) - ) - - val scope = rememberCoroutineScope() - val clientIdsList = activeClientIds.split(",").map { it.trim() }.filter { it.isNotEmpty() } - - val checkResultsJson by settingsStore.clientIdCheckResults.collectAsStateWithLifecycle(initialValue = "{}") - - var checkResults by remember(checkResultsJson) { - mutableStateOf(try { - val json = org.json.JSONObject(checkResultsJson) - val map = mutableMapOf() - val keys = json.keys() - while (keys.hasNext()) { - val key = keys.next() as String - map[key] = json.getBoolean(key) - } - map - } catch (e: Exception) { emptyMap() }) - } - - var isChecking by remember { mutableStateOf(false) } - - val knownIds = listOf("6287487", "8202606") - Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { - knownIds.forEach { id -> - Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Checkbox( - checked = clientIdsList.contains(id), - onCheckedChange = { checked -> - val newList = if (checked) { - if (!clientIdsList.contains(id)) clientIdsList + id else clientIdsList - } else { - clientIdsList - id - } - if (newList.isNotEmpty()) { - onClientIdsChange(newList.joinToString(",")) - } - }, - modifier = Modifier.scale(0.8f) - ) - Text( - text = id, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurface - ) - } - if (checkResults.containsKey(id)) { - Text( - text = if (checkResults[id] == true) "✅" else "❌", - fontSize = 12.sp - ) - } - } - } - - Button( - onClick = { - isChecking = true - scope.launch(kotlinx.coroutines.Dispatchers.IO) { - val results = checkResults.toMutableMap() - knownIds.forEach { id -> - results[id] = checkVkClientId(id) - } - - val newJson = org.json.JSONObject() - results.forEach { (k, v) -> newJson.put(k, v) } - settingsStore.saveClientIdCheckResults(newJson.toString()) - - isChecking = false - } - }, - modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp), - enabled = !isChecking, - contentPadding = PaddingValues(0.dp) - ) { - Text(if (isChecking) "Checking..." else "Проверить", fontSize = 12.sp) + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { showVkClientSettings = true } + .padding(horizontal = 4.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + 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 → свой → встроенный резерв" + else -> "Заполните резервные реквизиты" + }, + style = MaterialTheme.typography.bodySmall, + color = if (customVkCredentialsEnabled && !customVkCredentialsComplete) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + lineHeight = 15.sp + ) } + Switch( + checked = customVkCredentialsEnabled, + onCheckedChange = null, + modifier = Modifier.scale(0.85f) + ) } } } @@ -596,38 +623,72 @@ fun FloatingToolbar( } renamingProfile?.let { profile -> - AlertDialog( - onDismissRequest = { renamingProfile = null }, - title = { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text("Название профиля") - IconButton(onClick = { renamingProfile = null }) { - Icon(Icons.Filled.Close, contentDescription = "Закрыть") - } - } + ProfileMenuDialog( + profileNameInput = profileNameInput, + onProfileNameInputChange = { profileNameInput = sanitizeVpnProfileNameInput(it) }, + onResetRequested = { + resetCountdown = 5 + resettingProfile = profile }, - text = { - OutlinedTextField( - value = profileNameInput, - onValueChange = { profileNameInput = sanitizeVpnProfileNameInput(it) }, - label = { Text("Название") }, - singleLine = true, - modifier = Modifier.fillMaxWidth() - ) + onSave = { + onProfileNameChange(profile, profileNameInput) + renamingProfile = null }, - confirmButton = { - Button( - onClick = { - onProfileNameChange(profile, profileNameInput) + onDismiss = { renamingProfile = null } + ) + } + + resettingProfile?.let { profile -> + val profileLabel = vpnProfileDisplayName(profile, profileNames) + val potentiallyConnectedProfile = profile == (connectedProfile ?: activeProfile) + val resetsConnectedProfile = potentiallyConnectedProfile && + (tunnelRunning || tunnelTransition != com.wdtt.plus.TunnelTransition.IDLE) + ProfileResetDialog( + profileLabel = profileLabel, + defaultProfileLabel = vpnProfileDefaultName(profile), + countdown = resetCountdown, + inProgress = resetInProgress, + disconnectsActiveVpn = resetsConnectedProfile, + onConfirm = { + if (resetCountdown > 0 || resetInProgress) return@ProfileResetDialog + resetInProgress = true + scope.launch { + runCatching { + if (potentiallyConnectedProfile) { + val stopResult = TunnelStopCoordinator.stopAndAwait(context) + check(stopResult.succeeded) { + when (stopResult) { + TunnelStopResult.TIMED_OUT -> + "VPN не остановился за отведённое время" + else -> "Не удалось остановить VPN" + } + } + } + val resetCompleted = withTimeoutOrNull(PROFILE_RESET_TIMEOUT_MS) { + settingsStore.resetProfile(profile) + true + } == true + check(resetCompleted) { + "Очистка профиля не завершилась за 10 секунд. Повторите попытку." + } + }.onSuccess { + profileNameInput = vpnProfileDefaultName(profile) + resettingProfile = null renamingProfile = null + isExpanded = false + Toast.makeText(context, "Профиль «$profileLabel» очищен", Toast.LENGTH_SHORT).show() + }.onFailure { error -> + Toast.makeText( + context, + error.message ?: "Не удалось очистить профиль", + Toast.LENGTH_LONG + ).show() } - ) { - Text("Сохранить") + resetInProgress = false } + }, + onDismiss = { + if (!resetInProgress) resettingProfile = null } ) } @@ -638,36 +699,250 @@ fun FloatingToolbar( onDismiss = { showTrustedWifiSettings = false } ) } + + if (showVkClientSettings) { + VkClientSettingsDialog( + settingsStore = settingsStore, + activeClientIds = activeClientIds, + onClientIdsChange = onClientIdsChange, + onDismiss = { showVkClientSettings = false } + ) + } } } -private fun checkVkClientId(appId: String): Boolean { - for (i in 0..1) { - try { - val url = java.net.URL("https://oauth.vk.com/authorize?client_id=$appId&display=mobile&response_type=token") - val conn = url.openConnection() as java.net.HttpURLConnection - conn.requestMethod = "GET" - conn.connectTimeout = 5000 - conn.readTimeout = 5000 - - val code = conn.responseCode - val stream = if (code >= 400) conn.errorStream else conn.inputStream - val response = stream?.bufferedReader()?.readText() ?: "" - - // If it returns a json error like {"error":"invalid_client"...} - if (response.contains("\"error\"") && (response.contains("invalid_client") || response.contains("invalid_request"))) { - return false +@Composable +private fun ProfileMenuDialog( + profileNameInput: String, + onProfileNameInputChange: (String) -> Unit, + onResetRequested: () -> Unit, + onSave: () -> Unit, + onDismiss: () -> Unit +) { + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + BoxWithConstraints( + modifier = Modifier.fillMaxSize().padding(8.dp), + contentAlignment = Alignment.Center + ) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .widthIn(max = 560.dp) + .heightIn(max = maxHeight * 0.92f), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surface, + contentColor = MaterialTheme.colorScheme.onSurface, + tonalElevation = 8.dp + ) { + Box { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(22.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(14.dp) + ) { + Text( + "Профиль", + modifier = Modifier.padding(end = 48.dp), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary + ) + OutlinedTextField( + value = profileNameInput, + onValueChange = onProfileNameInputChange, + label = { Text("Название") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + OutlinedButton( + onClick = onResetRequested, + modifier = Modifier.weight(1f).heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.error), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + Text("Очистить", fontWeight = FontWeight.SemiBold) + } + Button( + onClick = onSave, + modifier = Modifier.weight(1f).heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + Text("Сохранить", fontWeight = FontWeight.SemiBold) + } + } + Spacer(Modifier.height(4.dp)) + } + + ProfileDialogCloseButton( + contentDescription = "Вернуться в настройки", + onClick = onDismiss, + modifier = Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 10.dp) + ) + } } - // If it returns HTML (login form or captcha), it's a valid client ID - return true - } catch (e: Exception) { - // Error, will retry } } - return false } +@Composable +private fun ProfileResetDialog( + profileLabel: String, + defaultProfileLabel: String, + countdown: Int, + inProgress: Boolean, + disconnectsActiveVpn: Boolean, + onConfirm: () -> Unit, + onDismiss: () -> Unit +) { + Dialog( + onDismissRequest = { if (!inProgress) onDismiss() }, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + BoxWithConstraints( + modifier = Modifier.fillMaxSize().padding(8.dp), + contentAlignment = Alignment.Center + ) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .widthIn(max = 560.dp) + .heightIn(max = maxHeight * 0.92f), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surface, + contentColor = MaterialTheme.colorScheme.onSurface, + tonalElevation = 8.dp + ) { + Box { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(22.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(14.dp) + ) { + Text( + "Очистить профиль?", + modifier = Modifier.padding(end = 48.dp), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.error + ) + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.errorContainer, + contentColor = MaterialTheme.colorScheme.onErrorContainer + ) { + Column( + modifier = Modifier.padding(15.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Text( + "Будет полностью очищена вся локальная информация профиля «$profileLabel».", + fontWeight = FontWeight.Bold, + style = MaterialTheme.typography.bodyLarge + ) + Text( + "Удалятся настройки подключения, VK-хеши, ссылки, пароли и SSH-ключи, параметры сервера, списки приложений и остальные данные этого профиля.", + style = MaterialTheme.typography.bodyMedium + ) + Text( + "Название вернётся к стандартному: «$defaultProfileLabel». Операция необратима. Вы уверены?", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold + ) + } + } + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.72f) + ) { + Text( + buildString { + append("На самом VPS и в других профилях ничего не удаляется.") + if (disconnectsActiveVpn) append(" Активное VPN-подключение этого профиля будет остановлено.") + }, + modifier = Modifier.padding(14.dp), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Button( + onClick = onConfirm, + enabled = countdown <= 0 && !inProgress, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), + shape = RoundedCornerShape(16.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error, + contentColor = MaterialTheme.colorScheme.onError, + disabledContainerColor = MaterialTheme.colorScheme.errorContainer, + disabledContentColor = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.68f) + ) + ) { + Text( + when { + inProgress -> "Очищаю профиль…" + countdown > 0 -> "Очистить через $countdown с" + else -> "Полностью очистить профиль" + }, + fontWeight = FontWeight.Bold + ) + } + Spacer(Modifier.height(4.dp)) + } + + ProfileDialogCloseButton( + contentDescription = "Вернуться к профилю", + onClick = onDismiss, + enabled = !inProgress, + modifier = Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 10.dp) + ) + } + } + } + } +} + +@Composable +private fun ProfileDialogCloseButton( + contentDescription: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true +) { + IconButton(onClick = onClick, modifier = modifier, enabled = enabled) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.78f), + modifier = Modifier.size(34.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + Icons.Filled.Close, + contentDescription = contentDescription, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + } + } + } +} @Composable private fun ThemeOption( 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 5689247..ac6736a 100644 --- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt @@ -52,11 +52,14 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.GenericShape import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material.icons.automirrored.filled.HelpOutline +import androidx.compose.material.icons.automirrored.filled.OpenInNew import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Cloud import androidx.compose.material.icons.filled.Code import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Info @@ -65,13 +68,17 @@ import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Update import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FilledTonalIconButton import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableIntState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf @@ -94,6 +101,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -104,6 +112,11 @@ import com.wdtt.plus.BuildConfig import com.wdtt.plus.DeviceCheckAction import com.wdtt.plus.DeviceCompatibility import com.wdtt.plus.R +import com.wdtt.plus.RemoteActionCatalogGateway +import com.wdtt.plus.RemoteActionForm +import com.wdtt.plus.RemoteContinuationLauncher +import com.wdtt.plus.RemoteUiAction +import com.wdtt.plus.RemoteUiActionLauncher import com.wdtt.plus.SettingsStore import com.wdtt.plus.TunnelManager import com.wdtt.plus.TrustedWifiManager @@ -114,7 +127,9 @@ import com.wdtt.plus.WDTTColors import com.wdtt.plus.AppReleaseInfo import com.wdtt.plus.AppUpdateCandidate import com.wdtt.plus.AppUpdateDownloadProgress +import com.wdtt.plus.ClientNetworkDiagnosticsReport import com.wdtt.plus.canRequestApkInstall +import com.wdtt.plus.collectClientNetworkDiagnostics import com.wdtt.plus.downloadUpdateApk import com.wdtt.plus.fetchLatestReleaseInfo import com.wdtt.plus.installUpdateApk @@ -123,6 +138,7 @@ import com.wdtt.plus.resolveAppUpdateCandidate import com.wdtt.plus.selectUpdateApkAsset import com.wdtt.plus.deviceCheckActionIntent import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -132,6 +148,7 @@ import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone +import java.util.UUID import kotlin.math.PI import kotlin.math.cos import kotlin.math.min @@ -142,7 +159,7 @@ private const val IssuesUrl = "https://github.com/Ivan4537/WDTT-Plus/issues/new/ private const val DeveloperProfileUrl = "https://github.com/Ivan4537" private const val RepositoryUrl = "https://github.com/Ivan4537/WDTT-Plus" private const val ChangelogUrl = "$RepositoryUrl/blob/main/CHANGELOG.md" -private const val DonateUrl = "https://yoomoney.ru/to/410012216336438" +private const val ProjectDonateFallbackUrl = "https://yoomoney.ru/to/410012216336438" private const val OriginalDonateUrl = "https://yoomoney.ru/to/4100119505530465/" private val DonateActionButtonColor = Color(0xFF00AEA5) @@ -221,7 +238,9 @@ private fun openDeviceCheckAction(context: Context, action: DeviceCheckAction) { fun InfoTab( actionsExpandedState: MutableState = rememberSaveable { mutableStateOf(true) }, projectExpandedState: MutableState = rememberSaveable { mutableStateOf(true) }, - scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) } + scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }, + projectSupportDialogRequest: Int = 0, + onProjectSupportDialogRequestConsumed: () -> Unit = {}, ) { val context = LocalContext.current val scope = rememberCoroutineScope() @@ -238,12 +257,23 @@ fun InfoTab( var updateDownloadStatus by rememberSaveable { mutableStateOf("") } var updateDownloadBusy by remember { mutableStateOf(false) } var pendingUpdateApkPath by rememberSaveable { mutableStateOf(null) } - var showHelpDialog by remember { mutableStateOf(false) } - var showSupportDialog by remember { mutableStateOf(false) } + var showHelpDialog by remember { mutableStateOf(false) } + var showQuestionDialog by remember { mutableStateOf(false) } + var showSupportDialog by remember { mutableStateOf(false) } + var pendingActionForm by remember { mutableStateOf(null) } + var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) } + var questionAction by remember { mutableStateOf(null) } + var questionActionLoading by remember { mutableStateOf(false) } var isCheckingDevice by remember { mutableStateOf(false) } var deviceCheckReport by remember { mutableStateOf(null) } var actionsExpanded by actionsExpandedState - var projectExpanded by projectExpandedState + var projectExpanded by projectExpandedState + LaunchedEffect(projectSupportDialogRequest) { + if (projectSupportDialogRequest > 0) { + showSupportDialog = true + onProjectSupportDialogRequestConsumed() + } + } val updateLatestVersion by settingsStore.updateLatestVersion.collectAsStateWithLifecycle(initialValue = "") val updateLastError by settingsStore.updateLastError.collectAsStateWithLifecycle(initialValue = "") val updateStatus = remember(isCheckingUpdates, updateLatestVersion, updateLastError, currentVersion) { @@ -276,6 +306,15 @@ fun InfoTab( } } + LaunchedEffect(Unit) { + actionCatalog = RemoteActionCatalogGateway.fetch() + } + LaunchedEffect(Unit) { + questionActionLoading = true + questionAction = RemoteActionCatalogGateway.fetchQuestionAction() + questionActionLoading = false + } + fun requestDownloadedUpdateInstall(apkFile: File) { pendingUpdateApkPath = apkFile.absolutePath if (!canRequestApkInstall(context)) { @@ -317,6 +356,25 @@ fun InfoTab( val diagnosticsSummary = withContext(Dispatchers.Default) { buildSupportReportSummary(context.applicationContext, settingsStore) } + val clientNetworkDiagnostics = try { + collectClientNetworkDiagnostics(context.applicationContext) + } catch (error: CancellationException) { + throw error + } catch (error: Throwable) { + ClientNetworkDiagnosticsReport( + summaryLines = listOf("Активная диагностика сети телефона: не выполнена"), + items = listOf( + com.wdtt.plus.DeviceCheckItem( + title = "Активная диагностика сети телефона", + status = "не выполнена", + details = error.message?.take(180) ?: error.javaClass.simpleName, + recommendation = "Повторите проверку устройства при активной сети.", + severity = com.wdtt.plus.DeviceCheckSeverity.Warning, + action = DeviceCheckAction.NetworkSettings + ) + ) + ) + } val report = withContext(Dispatchers.Default) { DeviceCompatibility.check( context = context.applicationContext, @@ -325,9 +383,10 @@ fun InfoTab( ) } return report.copy( - summaryLines = diagnosticsSummary, + summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines, items = listOf(versionItem) + - report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE } + report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE } + + clientNetworkDiagnostics.items ) } @@ -355,7 +414,9 @@ fun InfoTab( InfoHeroCard( currentVersion = currentVersion, releaseDate = releaseDate, - onSupportClick = { showSupportDialog = true } + onSupportClick = { + showSupportDialog = true + } ) ExpandableSectionCard( @@ -384,8 +445,17 @@ fun InfoTab( ) { WideActionTile( title = "Поднять вопрос", - subtitle = "Выбрать шаблон GitHub issue", - onClick = { openUrlInBrowser(context, IssuesUrl) }, + subtitle = "Выбрать подходящий способ обращения", + onClick = { + showQuestionDialog = true + if (questionAction == null && !questionActionLoading) { + scope.launch { + questionActionLoading = true + questionAction = RemoteActionCatalogGateway.fetchQuestionAction() + questionActionLoading = false + } + } + }, icon = { Icon( painter = painterResource(id = R.drawable.ic_github), @@ -672,12 +742,35 @@ fun InfoTab( } if (showHelpDialog) ImportantInfoDialog(onDismiss = { showHelpDialog = false }) + if (showQuestionDialog) { + QuestionDestinationDialog( + remoteAction = questionAction, + remoteActionLoading = questionActionLoading, + onDismiss = { showQuestionDialog = false }, + onGitHubClick = { + showQuestionDialog = false + openUrlInBrowser(context, IssuesUrl) + }, + onRemoteActionClick = { action -> + showQuestionDialog = false + scope.launch { + if (!RemoteUiActionLauncher.open(context, action)) { + Toast.makeText( + context, + "Не удалось открыть страницу. Проверьте браузер.", + Toast.LENGTH_LONG, + ).show() + } + } + }, + ) + } deviceCheckReport?.let { report -> DeviceCompatibilityDialog( report = report, title = "Проверка устройства", - subtitle = "Расширенная проверка не запускает VPN, но показывает совместимость устройства, настройки Android и статус подключения.", - note = "Кнопка «Скопировать отчёт» добавит в буфер версию приложения, Android, ABI, память, сеть, WebView, native-клиент и текущие настройки без секретных значений.", + subtitle = "Расширенная проверка не запускает VPN, но безопасно проверяет системный DNS, DNS-путь клиента и доступность узлов VK/OK.", + note = "Кнопка «Скопировать отчёт» повторит сетевые пробы и добавит их результат без VK-хешей, паролей, токенов и локальных IP-адресов телефона.", onDismiss = { deviceCheckReport = null }, onCopy = { scope.launch { @@ -696,18 +789,189 @@ fun InfoTab( ) } if (showSupportDialog) { - SupportProjectDialog( + AdditionalActionsDialog( onDismiss = { showSupportDialog = false }, - onDonateModClick = { openUrlInBrowser(context, DonateUrl) }, - onDonateOriginalClick = { openUrlInBrowser(context, OriginalDonateUrl) } + primaryAction = actionCatalog.at("about"), + secondaryAction = actionCatalog.at("tunnel"), + onActionClick = { action -> + if (action.form != null) { + showSupportDialog = false + pendingActionForm = action + } else { + showSupportDialog = false + scope.launch { + if (!RemoteUiActionLauncher.open(context, action)) { + Toast.makeText( + context, + "Не удалось открыть страницу. Проверьте браузер.", + Toast.LENGTH_LONG, + ).show() + } + } + } + }, + onProjectFallbackClick = { + showSupportDialog = false + openUrlInBrowser(context, ProjectDonateFallbackUrl) + }, + onDonateOriginalClick = { + showSupportDialog = false + openUrlInBrowser(context, OriginalDonateUrl) + } ) } + pendingActionForm?.form?.let { form -> + RemoteActionFormDialog( + form = form, + onDismiss = { + pendingActionForm = null + showSupportDialog = true + }, + onComplete = { + pendingActionForm = null + showSupportDialog = true + }, + onFallbackClick = { + openUrlInBrowser(context, ProjectDonateFallbackUrl) + pendingActionForm = null + showSupportDialog = true + }, + ) + } } @Composable -private fun SupportProjectDialog( +private fun QuestionDestinationDialog( + remoteAction: RemoteUiAction?, + remoteActionLoading: Boolean, + onDismiss: () -> Unit, + onGitHubClick: () -> Unit, + onRemoteActionClick: (RemoteUiAction) -> Unit, +) { + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false), + ) { + Box( + modifier = Modifier.fillMaxSize().padding(20.dp), + contentAlignment = Alignment.Center, + ) { + Surface( + shape = RoundedCornerShape(28.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 8.dp, + shadowElevation = 18.dp, + modifier = Modifier.fillMaxWidth().heightIn(max = 560.dp), + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(20.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Surface( + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.primaryContainer, + ) { + Box( + modifier = Modifier.size(42.dp), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(21.dp), + ) + } + } + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + "Поднять вопрос", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + ) + Text( + "Выберите подходящий вариант обращения.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + FilledTonalIconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = null) + } + } + + WideActionTile( + title = "Проблема в приложении", + subtitle = "Открыть шаблоны обращений GitHub", + onClick = onGitHubClick, + icon = { + Icon( + painter = painterResource(id = R.drawable.ic_github), + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = MaterialTheme.colorScheme.onPrimaryContainer, + ) + }, + ) + + remoteAction?.let { action -> + WideActionTile( + title = action.label, + subtitle = action.message, + onClick = { onRemoteActionClick(action) }, + icon = { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = MaterialTheme.colorScheme.onPrimaryContainer, + ) + }, + ) + } + if (remoteAction == null && remoteActionLoading) { + Surface( + shape = RoundedCornerShape(20.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.62f), + modifier = Modifier.fillMaxWidth(), + ) { + Row( + modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp), + strokeWidth = 2.dp, + ) + Text( + "Проверяем доступные способы помощи…", + style = MaterialTheme.typography.bodyMedium, + ) + } + } + } + } + } + } + } +} + +@Composable +private fun AdditionalActionsDialog( onDismiss: () -> Unit, - onDonateModClick: () -> Unit, + primaryAction: RemoteUiAction?, + secondaryAction: RemoteUiAction?, + onActionClick: (RemoteUiAction) -> Unit, + onProjectFallbackClick: () -> Unit, onDonateOriginalClick: () -> Unit ) { Dialog( @@ -766,15 +1030,35 @@ private fun SupportProjectDialog( } } - SupportDonateBlock( - title = "WDTT Plus", - body = "Поддержка этой версии помогает развивать доработки приложения, серверной части, Telegram-бота и удобство для пользователей.", - buttonText = "ЮMoney", - onClick = onDonateModClick, - emphasized = true - ) + if (primaryAction?.form != null) { + ExternalSupportBlock( + title = primaryAction.title, + body = primaryAction.message, + buttonText = primaryAction.label, + onClick = { onActionClick(primaryAction) }, + emphasized = true, + ) + } else { + ExternalSupportBlock( + title = "WDTT Plus", + body = ( + "Поддержка помогает развивать приложение, серверную " + + "часть и Telegram-бота." + ), + buttonText = "ЮMoney", + onClick = onProjectFallbackClick, + emphasized = true, + ) + } - SupportDonateBlock( + secondaryAction?.let { action -> + RemoteInfoActionBlock( + action = action, + onClick = { onActionClick(action) }, + ) + } + + ExternalSupportBlock( title = "Автор оригинального приложения", body = "Оригинальная основа проекта создана amurcanov. Можно отдельно поддержать автора исходного приложения.", buttonText = "ЮMoney", @@ -789,7 +1073,285 @@ private fun SupportProjectDialog( } @Composable -private fun SupportDonateBlock( +private fun RemoteActionFormDialog( + form: RemoteActionForm, + onDismiss: () -> Unit, + onComplete: () -> Unit, + onFallbackClick: () -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var valueText by rememberSaveable(form.token) { mutableStateOf(form.initialValue) } + var requestId by rememberSaveable(form.token) { mutableStateOf(UUID.randomUUID().toString()) } + var busy by remember(form.token) { mutableStateOf(false) } + var errorMessage by remember(form.token) { mutableStateOf("") } + var fallbackAvailable by remember(form.token) { mutableStateOf(false) } + val numericValue = valueText.toLongOrNull() + val valueValid = numericValue != null && numericValue in form.minimum..form.maximum + + fun selectValue(value: String) { + valueText = value + requestId = UUID.randomUUID().toString() + errorMessage = "" + fallbackAvailable = false + } + + Dialog( + onDismissRequest = { if (!busy) onDismiss() }, + properties = DialogProperties(usePlatformDefaultWidth = false), + ) { + Surface( + shape = RoundedCornerShape(28.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 8.dp, + shadowElevation = 18.dp, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Surface( + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.primaryContainer, + ) { + Box(Modifier.size(42.dp), contentAlignment = Alignment.Center) { + Icon( + Icons.Default.Favorite, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp), + ) + } + } + Text( + form.title, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + ) + FilledTonalIconButton( + onClick = onDismiss, + enabled = !busy, + ) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + + Text( + form.message, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 20.sp, + ) + + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + form.choices.chunked(2).forEach { rowChoices -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + rowChoices.forEach { choice -> + OutlinedButton( + onClick = { selectValue(choice.value) }, + enabled = !busy, + modifier = Modifier.weight(1f), + colors = if (valueText == choice.value) { + ButtonDefaults.outlinedButtonColors( + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + ) + } else { + ButtonDefaults.outlinedButtonColors() + }, + ) { + Text(choice.label, fontWeight = FontWeight.SemiBold) + } + } + if (rowChoices.size == 1) { + Spacer(Modifier.weight(1f)) + } + } + } + } + + OutlinedTextField( + value = valueText, + onValueChange = { raw -> + selectValue(raw.filter(Char::isDigit).take(form.maxCharacters)) + }, + enabled = !busy, + modifier = Modifier.fillMaxWidth(), + label = { Text(form.inputLabel) }, + suffix = { + if (form.inputSuffix.isNotBlank()) { + Text(form.inputSuffix) + } + }, + singleLine = true, + isError = valueText.isNotEmpty() && !valueValid, + supportingText = { + Text( + if (valueValid || valueText.isEmpty()) { + form.supportingText + } else { + form.invalidText + } + ) + }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + shape = RoundedCornerShape(16.dp), + ) + + if (errorMessage.isNotBlank()) { + Surface( + color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.64f), + shape = RoundedCornerShape(14.dp), + ) { + Text( + errorMessage, + modifier = Modifier.fillMaxWidth().padding(12.dp), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + ) + } + } + + Button( + onClick = { + if (!valueValid) return@Button + busy = true + errorMessage = "" + fallbackAvailable = false + scope.launch { + runCatching { + RemoteActionCatalogGateway.execute( + form = form, + requestId = requestId, + value = valueText, + ) + }.onSuccess { target -> + RemoteContinuationLauncher.launch(context, target) + onComplete() + }.onFailure { error -> + errorMessage = error.message ?: form.failureMessage + fallbackAvailable = true + } + busy = false + } + }, + enabled = valueValid && !busy, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), + shape = RoundedCornerShape(17.dp), + colors = ButtonDefaults.buttonColors( + containerColor = DonateActionButtonColor, + contentColor = Color.White, + ), + ) { + if (busy) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp), + strokeWidth = 2.dp, + color = Color.White, + ) + Spacer(Modifier.width(9.dp)) + Text(form.busyLabel, fontWeight = FontWeight.Bold) + } else { + Text( + form.submitLabel.replace("{value}", valueText), + fontWeight = FontWeight.Bold, + ) + } + } + + if (fallbackAvailable) { + OutlinedButton( + onClick = onFallbackClick, + enabled = !busy, + modifier = Modifier.fillMaxWidth().heightIn(min = 46.dp), + shape = RoundedCornerShape(16.dp), + ) { + Text(form.fallbackLabel, fontWeight = FontWeight.SemiBold) + Spacer(Modifier.width(6.dp)) + Icon( + Icons.AutoMirrored.Filled.OpenInNew, + contentDescription = null, + modifier = Modifier.size(17.dp), + ) + } + } + } + } + } +} + +@Composable +private fun RemoteInfoActionBlock( + action: RemoteUiAction, + onClick: () -> Unit, +) { + Surface( + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f), + contentColor = MaterialTheme.colorScheme.onSecondaryContainer, + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) + ) + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(14.dp), + verticalArrangement = Arrangement.spacedBy(9.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(9.dp) + ) { + Icon(Icons.Default.Cloud, contentDescription = null, modifier = Modifier.size(21.dp)) + Text( + action.title, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold + ) + } + Text( + action.message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.86f), + lineHeight = 18.sp + ) + OutlinedButton( + onClick = onClick, + modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), + shape = RoundedCornerShape(14.dp), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 7.dp) + ) { + Text(action.label, fontWeight = FontWeight.SemiBold) + Spacer(Modifier.width(6.dp)) + Icon( + Icons.AutoMirrored.Filled.OpenInNew, + contentDescription = null, + modifier = Modifier.size(17.dp) + ) + } + } + } +} + +@Composable +private fun ExternalSupportBlock( title: String, body: String, buttonText: String, @@ -834,7 +1396,11 @@ private fun SupportDonateBlock( onClick = onClick, shape = RoundedCornerShape(18.dp), colors = ButtonDefaults.buttonColors( - containerColor = if (emphasized) DonateActionButtonColor else MaterialTheme.colorScheme.primary, + containerColor = if (emphasized) { + DonateActionButtonColor + } else { + MaterialTheme.colorScheme.primary + }, contentColor = Color.White ), modifier = Modifier @@ -1428,6 +1994,11 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S .coerceAtMost(4) val hasSecondaryHash = runCatching { settingsStore.secondaryVkHash.first().isNotBlank() }.getOrNull() val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull() + val customVkCredentialsEnabled = runCatching { settingsStore.customVkCredentialsEnabled.first() }.getOrNull() + val customVkCredentialsComplete = runCatching { settingsStore.customVkCredentialsComplete.first() }.getOrNull() + val builtInVkClientCount = runCatching { + settingsStore.activeClientIds.first().split(',').count { it.trim().isNotEmpty() } + }.getOrNull() val captchaMode = runCatching { settingsStore.captchaMode.first() }.getOrNull() val fingerprint = runCatching { settingsStore.selectedFingerprint.first() }.getOrNull() val linkMode = runCatching { settingsStore.wdttLinkMode.first() }.getOrNull() @@ -1447,7 +2018,9 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S } else { "не требуется" } - val tunnelIssue = TunnelManager.connectionIssue.value?.title.orEmpty().ifBlank { "нет" } + val tunnelIssue = TunnelManager.connectionIssue.value?.let { issue -> + "${issue.title}: ${issue.action}" + }.orEmpty().ifBlank { "нет" } return buildString { appendLine("Версия приложения: ${BuildConfig.VERSION_NAME}") @@ -1498,8 +2071,12 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S appendLine("Профиль: ${activeProfile ?: "недоступно"}") appendLine("Потоки: ${workers ?: "недоступно"}") appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}") - appendLine("VKCalls: ${vkCallsEnabled ?: "недоступно"}") - appendLine("Captcha mode: ${captchaMode ?: "недоступно"}") + appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}") + appendLine( + "Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " + + "заполнены=${customVkCredentialsComplete ?: "недоступно"}, встроенных=${builtInVkClientCount ?: "недоступно"}" + ) + appendLine("Captcha mode (legacy): ${captchaMode ?: "недоступно"}") appendLine("TLS fingerprint: ${fingerprint ?: "недоступно"}") appendLine("Режим ссылки: ${linkMode ?: "недоступно"}") appendLine("Роль интерфейса: ${interfaceRole?.ifBlank { "не выбрана" } ?: "недоступно"}") diff --git a/app/src/main/java/com/wdtt/plus/ui/OutboundFormsStore.kt b/app/src/main/java/com/wdtt/plus/ui/OutboundFormsStore.kt new file mode 100644 index 0000000..fd5b0d6 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/OutboundFormsStore.kt @@ -0,0 +1,166 @@ +package com.wdtt.plus.ui + +import android.content.Context +import android.content.SharedPreferences +import com.wdtt.plus.SecureStringStore + +internal data class StoredOutboundForms( + val forms: OutboundProfileForms, + val warpMtu: String, +) + +/** + * Локальные черновики выходного IP относятся к конкретному VPN-профилю. + * Пароли и WireGuard-конфиг хранятся через Android Keystore. + */ +internal class OutboundFormsStore(context: Context) { + private val prefs = + context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + private val secureStore = SecureStringStore(context.applicationContext) + + init { + migrateLegacyValuesToProfileZero() + } + + fun load(profileIndex: Int): StoredOutboundForms { + val profile = profileIndex.coerceIn(0, 2) + return StoredOutboundForms( + forms = OutboundProfileForms( + localProxyPort = string(profile, LOCAL_PROXY_PORT, "1080"), + localProxyLogin = string(profile, LOCAL_PROXY_LOGIN, ""), + localProxyPassword = secret(profile, LOCAL_PROXY_PASSWORD), + externalProxyKindName = string(profile, EXTERNAL_PROXY_KIND, "Socks5"), + externalProxyHost = string(profile, EXTERNAL_PROXY_HOST, ""), + externalProxyPort = string(profile, EXTERNAL_PROXY_PORT, "1080"), + externalProxyLogin = string(profile, EXTERNAL_PROXY_LOGIN, ""), + externalProxyPassword = secret(profile, EXTERNAL_PROXY_PASSWORD), + wireGuardExitHost = string(profile, WG_EXIT_HOST, ""), + wireGuardExitSshPort = string(profile, WG_EXIT_SSH_PORT, "22"), + wireGuardExitUser = string(profile, WG_EXIT_USER, "root"), + wireGuardExitPassword = secret(profile, WG_EXIT_PASSWORD), + wireGuardExitPort = string(profile, WG_EXIT_PORT, "51820"), + wireGuardExitDns = string(profile, WG_EXIT_DNS, "1.1.1.1,8.8.8.8"), + importedWireGuardConfig = secret(profile, IMPORTED_WG_CONFIG), + ), + warpMtu = string(profile, WARP_MTU, "1280"), + ) + } + + fun save(profileIndex: Int, forms: OutboundProfileForms, warpMtu: String) { + val profile = profileIndex.coerceIn(0, 2) + val editor = prefs.edit() + .putString(key(profile, LOCAL_PROXY_PORT), forms.localProxyPort) + .putString(key(profile, LOCAL_PROXY_LOGIN), forms.localProxyLogin) + .putString(key(profile, EXTERNAL_PROXY_KIND), forms.externalProxyKindName) + .putString(key(profile, EXTERNAL_PROXY_HOST), forms.externalProxyHost) + .putString(key(profile, EXTERNAL_PROXY_PORT), forms.externalProxyPort) + .putString(key(profile, EXTERNAL_PROXY_LOGIN), forms.externalProxyLogin) + .putString(key(profile, WG_EXIT_HOST), forms.wireGuardExitHost) + .putString(key(profile, WG_EXIT_SSH_PORT), forms.wireGuardExitSshPort) + .putString(key(profile, WG_EXIT_USER), forms.wireGuardExitUser) + .putString(key(profile, WG_EXIT_PORT), forms.wireGuardExitPort) + .putString(key(profile, WG_EXIT_DNS), forms.wireGuardExitDns) + .putString(key(profile, WARP_MTU), warpMtu) + + editor.putSecret(profile, LOCAL_PROXY_PASSWORD, forms.localProxyPassword) + editor.putSecret(profile, EXTERNAL_PROXY_PASSWORD, forms.externalProxyPassword) + editor.putSecret(profile, WG_EXIT_PASSWORD, forms.wireGuardExitPassword) + editor.putSecret(profile, IMPORTED_WG_CONFIG, forms.importedWireGuardConfig) + editor.apply() + } + + private fun string(profile: Int, name: String, default: String): String = + prefs.getString(key(profile, name), default) ?: default + + private fun secret(profile: Int, name: String): String { + val encryptedKey = encryptedKey(profile, name) + secureStore.decrypt(prefs.getString(encryptedKey, null))?.let { return it } + return prefs.getString(key(profile, name), "").orEmpty() + } + + private fun SharedPreferences.Editor.putSecret(profile: Int, name: String, value: String) { + val plainKey = key(profile, name) + remove(plainKey) + if (value.isBlank()) { + remove(encryptedKey(profile, name)) + } else { + putString(encryptedKey(profile, name), secureStore.encrypt(value)) + } + } + + private fun migrateLegacyValuesToProfileZero() { + val legacyNames = NON_SECRET_NAMES + SECRET_NAMES + if (legacyNames.none(prefs::contains)) return + + val editor = prefs.edit() + NON_SECRET_NAMES.forEach { name -> + if (prefs.contains(name) && !prefs.contains(key(0, name))) { + editor.putString(key(0, name), prefs.getString(name, "").orEmpty()) + } + editor.remove(name) + } + SECRET_NAMES.forEach { name -> + val legacyValue = prefs.getString(name, "").orEmpty() + if ( + legacyValue.isNotBlank() && + !prefs.contains(encryptedKey(0, name)) && + !prefs.contains(key(0, name)) + ) { + editor.putString(encryptedKey(0, name), secureStore.encrypt(legacyValue)) + } + editor.remove(name) + } + editor.apply() + } + + companion object { + const val PREFS_NAME = "wdtt_outbound_forms" + + private const val LOCAL_PROXY_PORT = "local_proxy_port" + private const val LOCAL_PROXY_LOGIN = "local_proxy_login" + private const val LOCAL_PROXY_PASSWORD = "local_proxy_password" + private const val EXTERNAL_PROXY_KIND = "external_proxy_kind" + private const val EXTERNAL_PROXY_HOST = "external_proxy_host" + private const val EXTERNAL_PROXY_PORT = "external_proxy_port" + private const val EXTERNAL_PROXY_LOGIN = "external_proxy_login" + private const val EXTERNAL_PROXY_PASSWORD = "external_proxy_password" + private const val WG_EXIT_HOST = "wg_exit_host" + private const val WG_EXIT_SSH_PORT = "wg_exit_ssh_port" + private const val WG_EXIT_USER = "wg_exit_user" + private const val WG_EXIT_PASSWORD = "wg_exit_password" + private const val WG_EXIT_PORT = "wg_exit_port" + private const val WG_EXIT_DNS = "wg_exit_dns" + private const val WARP_MTU = "warp_mtu" + private const val IMPORTED_WG_CONFIG = "imported_wg_config" + + private val NON_SECRET_NAMES = listOf( + LOCAL_PROXY_PORT, + LOCAL_PROXY_LOGIN, + EXTERNAL_PROXY_KIND, + EXTERNAL_PROXY_HOST, + EXTERNAL_PROXY_PORT, + EXTERNAL_PROXY_LOGIN, + WG_EXIT_HOST, + WG_EXIT_SSH_PORT, + WG_EXIT_USER, + WG_EXIT_PORT, + WG_EXIT_DNS, + WARP_MTU, + ) + private val SECRET_NAMES = listOf( + LOCAL_PROXY_PASSWORD, + EXTERNAL_PROXY_PASSWORD, + WG_EXIT_PASSWORD, + IMPORTED_WG_CONFIG, + ) + + internal fun key(profile: Int, name: String): String = + "profile_${profile.coerceIn(0, 2)}_$name" + + internal fun encryptedKey(profile: Int, name: String): String = + "${key(profile, name)}_encrypted" + + internal fun isSecretPlainKey(key: String): Boolean = + SECRET_NAMES.any { key.endsWith("_$it") || key == it } + } +} diff --git a/app/src/main/java/com/wdtt/plus/ui/QuickExclusions.kt b/app/src/main/java/com/wdtt/plus/ui/QuickExclusions.kt new file mode 100644 index 0000000..108723e --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/QuickExclusions.kt @@ -0,0 +1,212 @@ +package com.wdtt.plus.ui + +/** + * Android-приложения сервисов, которые остаются доступными при ограничениях + * мобильного интернета, а также приложения, часто ограничивающие работу через VPN. + * + * Список пакетов и названий актуализирован по перечням Минцифры и карточкам + * приложений в российских магазинах. Поиск выполняется только среди уже + * установленных приложений, поэтому отсутствующие пакеты ни на что не влияют. + */ +internal val QuickExclusionExactPackages = setOf( + // Государственные и социальные сервисы + "ru.rostel", + "ru.gosuslugi.goskey", + "com.octopod.russianpost.client.android", + "ru.crptech.mark", + + // Банки и платежи + "ru.sberbankmobile", + "ru.tinkoff.mb", + "ru.vtb24.mobilebanking.android", + "ru.alfabank.mobile.android", + "logo.com.mbanking", + "ru.mts.bank", + "ru.lewis.dbo", + "ru.gazprombank.android.mobilebank.app", + "ru.nspk.mirpay", + "ru.nspk.sbpay", + + // Соцсети, связь и магазины приложений + "com.vkontakte.android", + "com.vk.im", + "com.vk.vkvideo", + "ru.vk.music", + "ru.ok.android", + "ru.oneme.app", + "ru.mail.mailapp", + "ru.mail.cloud", + "ru.vk.store", + + // Маркетплейсы, объявления и работа + "ru.ozon.app.android", + "com.wildberries.ru", + "ru.beru.android", + "ru.megamarket", + "ru.sbermarket", + "ru.instamart", + "ru.samokat.android", + "com.avito.android", + "ru.domclick.mortgage", + "ru.hh.android", + + // Яндекс + "ru.yandex.searchplugin", + "ru.yandex.yandexmaps", + "ru.yandex.music", + "ru.kinopoisk", + "com.yandex.browser", + "ru.yandex.taxi", + + // Операторы связи + "ru.mts", + "ru.beeline.services", + "ru.tele2.mytele2", + "ru.megafon.mlk", + + // Магазины, доставка и рестораны + "ru.vkusvill", + "com.icemobile.lenta.prod", + "ru.reksoft.okey", + "ru.myauchan.droid", + "www.metro.com", + "ru.tander.magnit", + "ru.pyaterochka.app.browser", + "ru.perekrestok.app", + "club.chizhik", + "com.logistic.sdek", + "ru.dodopizza.app", + "ru.burgerking", + "com.apegroup.mcdonaldsrussia", + + // Транспорт, навигация и путешествия + "ru.dublgis.dgismobile", + "ru.rzd.pass", + "ru.tutu.tutu_emp", + "com.carshering", + "youdrive.today", + "com.belkacar", + "ru.aeroflot", + "com.taxsee.taxsee", + "ru.maximoff.max", + + // Видео, музыка, новости и погода + "ru.rutube.app", + "ru.ivi.client", + "ru.more.play", + "ru.zen.android", + "gpm.tnt_premier", + "ru.mts.mtstv", + "ru.radioplayer", + "com.gismeteo.client", +) + +internal val QuickExclusionKeywords = listOf( + "sber", "сбер", + "tinkoff", "t-bank", "tbank", "тинькофф", "т-банк", "тбанк", + "vtb", "втб", + "alfa", "alpha", "альфа", + "psbank", "промсвязьбанк", "псб", + "gazprombank", "газпромбанк", + "mir pay", "mirpay", "мир пэй", + "sbpay", "сбпэй", + "ozon", "озон", + "wildberries", "вайлдберриз", + "yandex", "яндекс", + "vkontakte", "вконтакте", + "rutube", "рутуб", + "gosuslugi", "госуслуг", "госключ", + "честный знак", + "dublgis", "2gis", "dgis", "дубльгис", + "avito", "авито", + "domclick", "домклик", + "headhunter", "hh.ru", + "mts", "мтс", + "beeline", "билайн", + "megafon", "мегафон", + "tele2", "теле2", + "mail.ru", "mailapp", + "ok.ru", "odnoklassniki", "одноклассники", + "kinopoisk", "кинопоиск", + "samokat", "самокат", + "megamarket", "мегамаркет", "sbermarket", + "kuper", "купер", "instamart", + "rostel", "ростел", + "почта россии", "russianpost", + "max: общение", "макс: общение", "oneme", + "vkusvill", "вкусвилл", + "lenta.prod", "лента – доставка", "лента - доставка", + "okeydostavka", "гипермаркеты и доставка", + "myauchan", "мой ашан", + "metro: продукты", "метро: продукты", + "tander.magnit", "магнит: акции", + "pyaterochka", "пятёрочка:", "пятерочка:", + "perekrestok", "перекрёсток доставка", "перекресток доставка", + "club.chizhik", "чижик - доставка", "чижик — доставка", + "cdek", "сдэк", + "dostavista", "достависта", + "dodopizza", "додо пицца", + "burgerking", "бургер кинг", + "mcdonaldsrussia", "вкусно — и точка", "вкусно - и точка", + "детский мир", "detmir", + "петрович", "petrovich", + "spar —", "spar -", "мой spar", + "дикси", "dixy", + "vprok", "впрок", + "5post", "fivepost", + "много лосося", + "rzd.pass", "ржд пассажирам", + "tutu", "туту:", + "carshering", "делимобиль", + "citydrive", "ситидрайв", "youdrive", + "belkacar", "белкаcar", + "aeroflot", "аэрофлот", + "pobeda", "победа", + "s7 airlines", + "деловые линии", + "гранд сервис экспресс", + "taxsee", "maxim — заказ такси", "maxim - заказ такси", "maximoff", + "gismeteo", "гисметео", + "ivi.client", "иви:", + "more.play", "okko:", + "zen.android", "дзен", + "tnt_premier", "premier —", "premier -", + "mtstv", "кион", + "radioplayer", "радиоплеер", + "medsi", "медси", + "мать и дитя", + "iomt.istok", + "сателлит online", + "м-лайн", "m-line", + "inme", + "yuwell anytime", + "follow anytime", "anytime follow", + "ican health", "ican reach", + "mq cgm", + "freestyle libre", + "medtrum", + "syai link", + "poctech cgm", + "hematonix", + "дианянь", + "lumipod", "glutec", "lumiflex", + "trueconf", "труконф", + "лизаалерт", + "рувики", + "добро.рф", + "цезарь сателлит", + "тензор", + "скб контур", + "эвотор", + "мп. инспектор", + "1с:", + "hrlink", + "кхл", +) + +internal fun matchesQuickExclusionApp(name: String, packageName: String): Boolean { + val packageLower = packageName.lowercase() + if (packageLower in QuickExclusionExactPackages) return true + val haystack = "$packageLower ${name.lowercase()}" + return QuickExclusionKeywords.any(haystack::contains) +} 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 0cbf9d9..778529a 100644 --- a/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt +++ b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt @@ -128,6 +128,8 @@ import com.wdtt.plus.ServerClientCreateRequest import com.wdtt.plus.ServerClientInfo import com.wdtt.plus.ServerTrafficPeriod import com.wdtt.plus.TransferFiles +import com.wdtt.plus.WdttDocument +import com.wdtt.plus.VkJoinLink import com.wdtt.plus.WDTTColors import com.wdtt.plus.connectionLink import kotlinx.coroutines.Dispatchers @@ -163,6 +165,21 @@ private enum class ClientVkHashFilter { All, Present, Missing } private enum class ClientsServerRefreshState { Unknown, Ready, Error } +private data class ClientQrData( + val title: String, + val bitmap: Bitmap, + val missingVkHashes: Boolean +) + +private fun vkHashInputError(value: String): String? { + if (value.isBlank()) return null + return if (VkJoinLink.normalizeHashes(value) == null) { + "Проверьте VK-хеш: допустимы латинские буквы, цифры, _ и - либо ссылка VK-звонка." + } else { + null + } +} + internal fun serverClientsAccessIssue( host: String, hostValid: Boolean, @@ -354,7 +371,7 @@ fun ServerClientsSection( var changedPasswordClient by remember { mutableStateOf(null) } var pendingAction by remember { mutableStateOf(null) } var expiryClient by remember { mutableStateOf(null) } - var qrData by remember { mutableStateOf?>(null) } + var qrData by remember { mutableStateOf(null) } var detailsClient by remember { mutableStateOf(null) } var showServerTools by rememberSaveable { mutableStateOf(false) } var createdClient by remember { mutableStateOf(null) } @@ -814,10 +831,16 @@ fun ServerClientsSection( scope.launch { runCatching { withContext(Dispatchers.IO) { - TransferFiles.writeTransferText(context, "WDTT-Plus-${selectedClient.safeFileName()}.wdtt", link) + TransferFiles.writeTransferText( + context, + WdttDocument.fileName( + "WDTT-Plus-${selectedClient.safeFileName()}" + ), + link + ) } }.onSuccess { - shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") + shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus") }.onFailure { Toast.makeText(context, it.message ?: "Не удалось создать файл.", Toast.LENGTH_LONG).show() } @@ -827,7 +850,13 @@ fun ServerClientsSection( scope.launch { runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) } - }.onSuccess { qrData = selectedClient.displayName() to it } + }.onSuccess { + qrData = ClientQrData( + title = selectedClient.displayName(), + bitmap = it, + missingVkHashes = selectedClient.vkHash.isBlank() + ) + } .onFailure { Toast.makeText(context, it.message ?: "Не удалось создать QR.", Toast.LENGTH_LONG).show() } } }, @@ -1039,7 +1068,13 @@ fun ServerClientsSection( onQr = { scope.launch { runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, transfer) } } - .onSuccess { qrData = "Перенос: ${client.displayName()}" to it } + .onSuccess { + qrData = ClientQrData( + title = "Перенос: ${client.displayName()}", + bitmap = it, + missingVkHashes = client.vkHash.isBlank() + ) + } .onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" } } }, @@ -1050,7 +1085,12 @@ fun ServerClientsSection( TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt-client", transfer) } }.onSuccess { - shareUri(context, it, "application/vnd.wdtt.plus.client", "Передать клиента WDTT Plus") + shareUri( + context, + it, + WdttDocument.LEGACY_CLIENT_MIME_TYPE, + "Передать клиента WDTT Plus" + ) }.onFailure { status = "Ошибка: ${it.message ?: "файл клиента не создан"}" } } } @@ -1119,7 +1159,8 @@ fun ServerClientsSection( title = "Клиент создан", password = client.password, link = link, - noLinkText = "VK-хеш не задан. Пароль уже работает; ссылку, QR и файл можно создать после добавления хеша в «Подробнее».", + missingVkHashes = client.vkHash.isBlank(), + noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.", onDismiss = { createdClient = null }, onCopyPassword = { copyText(context, "Пароль WDTT", client.password) }, onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } }, @@ -1128,7 +1169,9 @@ fun ServerClientsSection( link?.let { value -> scope.launch { runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } } - .onSuccess { qrData = client.displayName() to it } + .onSuccess { + qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank()) + } .onFailure { Toast.makeText(context, it.message ?: "Не удалось создать QR.", Toast.LENGTH_LONG).show() } } } @@ -1137,8 +1180,14 @@ fun ServerClientsSection( link?.let { value -> scope.launch { runCatching { - withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) } - }.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") } + withContext(Dispatchers.IO) { + TransferFiles.writeTransferText( + context, + WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"), + value + ) + } + }.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus") } .onFailure { Toast.makeText(context, it.message ?: "Не удалось создать файл.", Toast.LENGTH_LONG).show() } } } @@ -1157,7 +1206,8 @@ fun ServerClientsSection( statusText = "Клиент импортирован и найден в списке.", password = client.password, link = link, - noLinkText = "VK-хеш не задан. Клиент добавлен; хеш можно указать в «Подробнее».", + missingVkHashes = client.vkHash.isBlank(), + noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.", onDismiss = { importedClient = null }, onCopyPassword = { copyText(context, "Пароль импортированного клиента", client.password) }, onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } }, @@ -1166,7 +1216,9 @@ fun ServerClientsSection( link?.let { value -> scope.launch { runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } } - .onSuccess { qrData = client.displayName() to it } + .onSuccess { + qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank()) + } .onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" } } } @@ -1175,8 +1227,14 @@ fun ServerClientsSection( link?.let { value -> scope.launch { runCatching { - withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) } - }.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") } + withContext(Dispatchers.IO) { + TransferFiles.writeTransferText( + context, + WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"), + value + ) + } + }.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus") } .onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" } } } @@ -1194,7 +1252,8 @@ fun ServerClientsSection( title = "Пароль изменён", password = client.password, link = link, - noLinkText = "VK-хеш не задан. Новый пароль уже работает; добавьте хеш в «Подробнее», чтобы сформировать ссылку.", + missingVkHashes = client.vkHash.isBlank(), + noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.", onDismiss = { changedPasswordClient = null }, onCopyPassword = { copyText(context, "Новый пароль WDTT", client.password) }, onCopyLink = { link?.let { copyText(context, "Новая ссылка WDTT", it) } }, @@ -1203,7 +1262,9 @@ fun ServerClientsSection( link?.let { value -> scope.launch { runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } } - .onSuccess { qrData = client.displayName() to it } + .onSuccess { + qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank()) + } .onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" } } } @@ -1212,8 +1273,14 @@ fun ServerClientsSection( link?.let { value -> scope.launch { runCatching { - withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) } - }.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать новое подключение WDTT Plus") } + withContext(Dispatchers.IO) { + TransferFiles.writeTransferText( + context, + WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"), + value + ) + } + }.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать новое подключение WDTT Plus") } .onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" } } } @@ -1287,17 +1354,18 @@ fun ServerClientsSection( } } - qrData?.let { (title, bitmap) -> + qrData?.let { qr -> ClientQrDialog( - title = title, - bitmap = bitmap, + title = qr.title, + bitmap = qr.bitmap, + missingVkHashes = qr.missingVkHashes, onDismiss = { qrData = null }, onShare = { scope.launch { val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()) - val fileName = "WDTT-Plus-QR-${title.safeQrFileName()}-$stamp.png" + val fileName = "WDTT-Plus-QR-${qr.title.safeQrFileName()}-$stamp.png" runCatching { - withContext(Dispatchers.IO) { TransferFiles.writeQrPng(context, fileName, bitmap) } + withContext(Dispatchers.IO) { TransferFiles.writeQrPng(context, fileName, qr.bitmap) } }.onSuccess { shareUri(context, it, "image/png", "Передать QR-код WDTT Plus") } .onFailure { Toast.makeText(context, it.message ?: "Не удалось поделиться QR.", Toast.LENGTH_LONG).show() } } @@ -1305,8 +1373,11 @@ fun ServerClientsSection( onSave = { scope.launch { val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()) + val fileName = "WDTT-Plus-QR-${qr.title.safeQrFileName()}-$stamp.png" runCatching { - withContext(Dispatchers.IO) { TransferFiles.saveQrToGallery(context, "WDTT-Plus-client-$stamp.png", bitmap) } + withContext(Dispatchers.IO) { + TransferFiles.saveQrToGallery(context, fileName, qr.bitmap) + } }.onSuccess { Toast.makeText(context, "QR-код сохранён.", Toast.LENGTH_SHORT).show() }.onFailure { @@ -1394,7 +1465,7 @@ private fun ServerClientCard( ) if (client.vkHash.isBlank()) { Text( - "VK-хеш не задан: быструю ссылку/QR создать нельзя, пока не обновить хеш.", + "VK-хеш не задан: доступ можно передать, но клиенту нужно добавить свой перед запуском.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error ) @@ -1684,6 +1755,7 @@ private fun AccessResultDialog( statusText: String? = null, password: String, link: String?, + missingVkHashes: Boolean, noLinkText: String, onDismiss: () -> Unit, onCopyPassword: () -> Unit, @@ -1718,7 +1790,15 @@ private fun AccessResultDialog( if (link == null) { Text(noLinkText, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } else { - Text("Ссылка содержит пароль и VK-хеш. Не публикуйте её.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + Text( + if (missingVkHashes) { + "VK-хеш не задан. Передать можно, но клиенту нужно добавить свой перед запуском." + } else { + "Ссылка содержит пароль и VK-хеш. Не публикуйте её." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) FlowRow( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), @@ -1754,6 +1834,7 @@ private fun ClientDetailsDialog( var hash by rememberSaveable(client.password) { mutableStateOf(client.vkHash) } var ports by rememberSaveable(client.password) { mutableStateOf(client.ports) } val portsValid = ports.isPortsSpec() + val hashError = vkHashInputError(hash) val link = remember(client, fallbackHost, publicHost, sourceProfileName) { client.connectionLink(fallbackHost, publicHost, sourceProfileName) } @@ -1854,8 +1935,10 @@ private fun ClientDetailsDialog( ) OutlinedTextField( value = hash, - onValueChange = { hash = it }, + onValueChange = { hash = it.take(4096) }, label = { Text("VK-хеш или ссылка") }, + supportingText = { hashError?.let { Text(it) } }, + isError = hashError != null, minLines = 2, modifier = Modifier.fillMaxWidth() ) @@ -1903,7 +1986,10 @@ private fun ClientDetailsDialog( }, confirmButton = { if (step == ClientDetailsStep.Edit) { - Button(onClick = { onSave(label, hash, ports) }, enabled = !busy && portsValid) { Text("Сохранить") } + Button( + onClick = { onSave(label, hash, ports) }, + enabled = !busy && portsValid && hashError == null + ) { Text("Сохранить") } } } ) @@ -1949,7 +2035,8 @@ private fun ServerToolsDialog( ServerToolsStep.Overview -> { Text("Состояние", fontWeight = FontWeight.Bold) InfoLine("Клиенты", "${state.passwordCount}/${state.maxPasswords}") - InfoLine("Устройства", state.deviceCount.toString()) + InfoLine("Устройства клиентов", state.deviceCount.toString()) + InfoLine("Устройства владельца", state.ownerDeviceCount.toString()) InfoLine("Истёкшие", state.expiredCount.toString()) InfoLine("Забытые устройства", state.orphanDeviceCount.toString()) InfoLine( @@ -2549,6 +2636,7 @@ private fun CreateClientWizardDialog( var customPassword by rememberSaveable { mutableStateOf("") } val effectivePorts = if (useDefaultPorts) defaultPorts else customPorts val portsValid = effectivePorts.isPortsSpec() + val hashError = vkHashInputError(vkHash) val passwordError = if (useAutoPassword || customPassword.isEmpty()) null else when { ClientPasswordRules.validate(customPassword) != null -> ClientPasswordRules.validate(customPassword) customPassword == mainPassword -> "Пароль клиента не должен совпадать с главным паролем." @@ -2614,11 +2702,16 @@ private fun CreateClientWizardDialog( } ClientWizardStep.Hash -> { Text("VK-хеш", fontWeight = FontWeight.Bold) - Text("Нужен для быстрой ссылки, QR и файла. Можно вставить сам хеш или ссылку приглашения.", style = MaterialTheme.typography.bodySmall) + Text( + "Лучше добавить перед передачей. Без хеша доступ тоже можно отправить, но клиенту придётся добавить свой.", + style = MaterialTheme.typography.bodySmall + ) OutlinedTextField( value = vkHash, - onValueChange = { vkHash = it }, + onValueChange = { vkHash = it.take(4096) }, label = { Text("Хеш или ссылка") }, + supportingText = { hashError?.let { Text(it) } }, + isError = hashError != null, minLines = 2, modifier = Modifier.fillMaxWidth() ) @@ -2682,6 +2775,13 @@ private fun CreateClientWizardDialog( Text("VK-хеш: ${if (vkHash.isBlank()) "не задан" else "задан"}") Text("Порты: $effectivePorts") Text("Пароль: ${if (useAutoPassword) "будет создан автоматически" else customPassword}") + if (vkHash.isBlank()) { + Text( + "Без VK-хеша клиент добавит свой перед запуском.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } Text( "Новый доступ начнёт работать сразу, текущие подключения не прервутся.", style = MaterialTheme.typography.bodySmall, @@ -2696,6 +2796,7 @@ private fun CreateClientWizardDialog( confirmButton = { Button( enabled = !busy && + (step != ClientWizardStep.Hash || hashError == null) && (step != ClientWizardStep.Ports || portsValid) && (step != ClientWizardStep.Password || passwordValid), onClick = { @@ -2811,6 +2912,7 @@ private fun ExtendClientDialog( private fun ClientQrDialog( title: String, bitmap: Bitmap, + missingVkHashes: Boolean, onDismiss: () -> Unit, onShare: () -> Unit, onSave: () -> Unit @@ -2837,7 +2939,15 @@ private fun ClientQrDialog( Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { Image(bitmap = bitmap.asImageBitmap(), contentDescription = "QR-код WDTT Plus", modifier = Modifier.fillMaxWidth()) } - Text("QR содержит пароль и VK-хеш. Не публикуйте изображение.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + Text( + if (missingVkHashes) { + "VK-хеш не задан. Клиенту нужно добавить свой перед запуском." + } else { + "QR содержит пароль и VK-хеш. Не публикуйте изображение." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedButton( modifier = Modifier.weight(1f).heightIn(min = 48.dp), 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 c372343..5af1095 100644 --- a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt @@ -2,7 +2,8 @@ package com.wdtt.plus.ui import android.content.ClipData import android.content.ClipboardManager -import androidx.compose.animation.animateContentSize +import android.content.Context +import android.content.ContextWrapper import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.animation.animateColorAsState @@ -20,12 +21,20 @@ 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.automirrored.filled.OpenInNew import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Cloud +import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.PowerSettingsNew +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Stop import androidx.compose.material.icons.filled.Tag +import androidx.compose.material.icons.filled.Update +import androidx.compose.material.icons.filled.WarningAmber import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable @@ -35,39 +44,82 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.focus.onFocusChanged +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.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.withLink import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration 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 +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.repeatOnLifecycle +import com.wdtt.plus.BuildConfig +import com.wdtt.plus.CachedRemoteAction +import com.wdtt.plus.AccessLifecycleCoordinator +import com.wdtt.plus.AccessLifecycleRefreshResult +import com.wdtt.plus.AccessLifecycleSeverity +import com.wdtt.plus.AccessLifecycleUiState +import com.wdtt.plus.AccessStartDecision import com.wdtt.plus.CaptchaWebViewManager +import com.wdtt.plus.ConnectionIssueKind +import com.wdtt.plus.DEFAULT_VK_CLIENT_IDS import com.wdtt.plus.ManlCaptchaWebViewManager +import com.wdtt.plus.MainActivity +import com.wdtt.plus.MANAGED_CONFIG_FIRST_START_EXTRA +import com.wdtt.plus.RemoteContinuation +import com.wdtt.plus.RemoteContinuationLauncher +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.SettingsStore import com.wdtt.plus.TunnelManager import com.wdtt.plus.TunnelService +import com.wdtt.plus.TunnelStopCoordinator +import com.wdtt.plus.TunnelStopResult +import com.wdtt.plus.TunnelTransition +import com.wdtt.plus.TUNNEL_PROFILE_INDEX_EXTRA +import com.wdtt.plus.normalizeTunnelWorkerCount +import com.wdtt.plus.shouldUseManagedConfigFirstStart import com.wdtt.plus.TrustedWifiManager import com.wdtt.plus.VkJoinLink import com.wdtt.plus.WDTTColors import com.wdtt.plus.WdttDeepLink +import com.wdtt.plus.WdttDeepLinkApplyPlan +import com.wdtt.plus.isValidVkClientId +import com.wdtt.plus.isStandaloneUiIssue +import com.wdtt.plus.accessLifecycleDismissalSignature +import com.wdtt.plus.fallbackTitle import com.wdtt.plus.vpnProfileDisplayName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import kotlinx.coroutines.CancellationException import android.content.Intent +import android.net.Uri import android.net.VpnService import android.os.Build import android.widget.Toast @@ -76,6 +128,95 @@ import androidx.activity.result.contract.ActivityResultContracts import kotlin.math.roundToInt private const val WORKERS_PER_GROUP = 9 +private const val REMOTE_ACTION_REFRESH_MS = 10 * 60 * 1000L + +private fun launchRemoteTarget(context: Context, target: RemoteLaunchTarget) { + var current: Context? = context + while (current != null) { + if (current is MainActivity) { + current.launchRemoteContinuation(target) + return + } + current = (current as? ContextWrapper)?.baseContext + } + RemoteContinuationLauncher.launch(context, target) +} + +internal fun usesCompactTunnelInterface(interfaceRole: String): Boolean = interfaceRole == "user" + +internal fun resolveConnectionInputMethod( + savedMethod: String, + hasStoredLink: Boolean, + hasManualConnection: Boolean, + userInterface: Boolean, +): String = when (savedMethod) { + "link", "manual" -> savedMethod + else -> when { + hasStoredLink -> "link" + hasManualConnection -> "manual" + userInterface -> "link" + else -> "manual" + } +} + +internal fun hasTunnelConnectionSource( + linkMode: Boolean, + linkValid: Boolean, + peer: String, + password: String, +): Boolean = (linkMode && linkValid) || peer.isNotBlank() && password.isNotBlank() + +internal fun shouldShowRemoteActionCard( + audience: Boolean, + hasConnectionSource: Boolean, + dismissed: Boolean, + dismissCountdown: Int, + actionResolved: Boolean, + actionAvailable: Boolean, +): Boolean = + audience && + !hasConnectionSource && + (!actionResolved || actionAvailable) && + (!dismissed || dismissCountdown > 0) + +internal fun shouldShowTunnelRemoteActionCard( + interfaceRole: String, + preview: Boolean, + hasConnectionSource: Boolean, + dismissed: Boolean, + dismissCountdown: Int, + actionResolved: Boolean, + actionAvailable: Boolean, +): Boolean { + val adminInterface = interfaceRole == "admin" + return shouldShowRemoteActionCard( + audience = preview || interfaceRole == "user" || adminInterface, + hasConnectionSource = hasConnectionSource && !adminInterface, + dismissed = dismissed, + dismissCountdown = dismissCountdown, + actionResolved = actionResolved, + actionAvailable = actionAvailable, + ) +} + +internal fun isSelectedCompactConnectionReady( + selectedMethod: String, + savedMethod: String, + storedLinkMode: Boolean, + linkPresent: Boolean, + linkValid: Boolean, + manualValid: Boolean, +): Boolean = when (selectedMethod) { + "link" -> when { + storedLinkMode && linkPresent -> linkValid + savedMethod == "link" -> manualValid + else -> false + } + "manual" -> !storedLinkMode && + (savedMethod == "manual" || savedMethod.isBlank()) && + manualValid + else -> false +} private fun isValidTunnelHost(value: String): Boolean { val host = value.trim() @@ -97,17 +238,26 @@ private fun isValidTunnelHost(value: String): Boolean { @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsTab( - scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) } + settingsStore: SettingsStore, + scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }, + onVkHashesSaved: (Int, List) -> Unit = { _, _ -> }, + onOpenProjectSupport: () -> Unit = {}, ) { val context = LocalContext.current val scope = rememberCoroutineScope() - val settingsStore = remember { SettingsStore(context) } val currentDensity = LocalDensity.current CompositionLocalProvider( LocalDensity provides Density(currentDensity.density, fontScale = 1f) ) { - SettingsTabContent(context, scope, settingsStore, scrollPosition) + SettingsTabContent( + context = context, + scope = scope, + settingsStore = settingsStore, + scrollPosition = scrollPosition, + onVkHashesSaved = onVkHashesSaved, + onOpenProjectSupport = onOpenProjectSupport, + ) } } @@ -117,61 +267,171 @@ fun SettingsTabContent( context: android.content.Context, scope: kotlinx.coroutines.CoroutineScope, settingsStore: SettingsStore, - scrollPosition: MutableIntState + scrollPosition: MutableIntState, + onVkHashesSaved: (Int, List) -> Unit, + onOpenProjectSupport: () -> Unit, ) { - val savedConnectionPassword by settingsStore.connectionPassword.collectAsStateWithLifecycle(initialValue = "") - val savedManualPortsEnabled 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 profileSnapshotState by + settingsStore.activeTunnelProfileUiSnapshot.collectAsStateWithLifecycle() + val profileSnapshot = profileSnapshotState ?: return + val savedConnectionPassword = profileSnapshot.connectionPassword + val savedPeer = profileSnapshot.peer + val savedWorkers = profileSnapshot.workersPerHash + val savedManualPortsEnabled = profileSnapshot.manualPortsEnabled + val savedServerDtlsPort = profileSnapshot.serverDtlsPort + val savedServerWgPort = profileSnapshot.serverWgPort + val savedListenPort = profileSnapshot.listenPort + val savedSni = profileSnapshot.sni + val savedCaptchaMode = profileSnapshot.captchaMode + val savedCaptchaMethod = profileSnapshot.captchaSolveMethod + val activeProfile = profileSnapshot.profileIndex + val profileNames = profileSnapshot.profileNames + val wdttLinkMode = profileSnapshot.linkMode + val wdttLink = profileSnapshot.link + val savedConnectionInputMethod = profileSnapshot.connectionInputMethod + val savedVkHashesState = profileSnapshot.vkHashes + val activeFingerprint = profileSnapshot.fingerprint + val activeClientIds = profileSnapshot.clientIds + val customVkCredentialsEnabled = profileSnapshot.customVkCredentialsEnabled + val customVkClientId = profileSnapshot.customVkClientId + val customVkClientSecret = profileSnapshot.customVkClientSecret + val vkCallsPreflight = profileSnapshot.vkCallsPreflight + val remoteActionKey = profileSnapshot.remoteActionKey + val remoteActionUrl = profileSnapshot.remoteActionUrl + val remoteManagedProfile = profileSnapshot.remoteManaged + val interfaceRole = if (remoteManagedProfile) "user" else profileSnapshot.interfaceRole + val cachedRemoteAction = profileSnapshot.cachedRemoteAction + val remoteCardDismissed = profileSnapshot.remoteCardDismissed + val accessLifecycle = profileSnapshot.accessLifecycle + val accessLifecycleDismissedSignature = + profileSnapshot.accessLifecycleDismissedSignature + val profileMaxWorkers = profileSnapshot.profileMaxWorkers + val refreshingProfiles by + AccessLifecycleCoordinator.refreshingProfiles.collectAsStateWithLifecycle() + val accessRefreshing = activeProfile in refreshingProfiles + var accessActionBusy by remember(activeProfile) { mutableStateOf(false) } + var accessManualRefreshBusy by remember(activeProfile) { mutableStateOf(false) } + var accessLifecycleDismissCountdown by remember(activeProfile) { mutableIntStateOf(0) } + val initialActionCatalog = remember { RemoteActionCatalogGateway.cached() } + var actionCatalog by remember { mutableStateOf(initialActionCatalog) } + var actionCatalogResolved by remember { + mutableStateOf(RemoteActionCatalogGateway.hasFreshCache()) + } + var remoteCardDismissCountdown by remember(activeProfile) { mutableIntStateOf(0) } + val lifecycleOwner = LocalLifecycleOwner.current - val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0) - val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) - val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false) - val wdttLink by settingsStore.wdttLink.collectAsStateWithLifecycle(initialValue = "") - val savedVkHashesState by remember(settingsStore) { - settingsStore.vkHashes.map { hashes -> hashes } - }.collectAsStateWithLifecycle(initialValue = null) + val compactTunnelInterface = usesCompactTunnelInterface(interfaceRole) + val remoteActionAudience = + compactTunnelInterface || + interfaceRole == "admin" || + BuildConfig.REMOTE_ACTION_PREVIEW + val remoteActionFetchAllowed = remoteActionAudience - val activeFingerprint by settingsStore.selectedFingerprint.collectAsStateWithLifecycle(initialValue = "firefox") - val activeClientIds by settingsStore.activeClientIds.collectAsStateWithLifecycle(initialValue = "6287487,8202606") - val vkCallsPreflight by settingsStore.vkCallsPreflight.collectAsStateWithLifecycle(initialValue = true) + LaunchedEffect(remoteActionFetchAllowed, lifecycleOwner) { + if (!remoteActionFetchAllowed) { + actionCatalog = com.wdtt.plus.RemoteActionCatalog.Empty + actionCatalogResolved = true + return@LaunchedEffect + } + if (RemoteActionCatalogGateway.hasFreshCache()) { + actionCatalog = RemoteActionCatalogGateway.cached() + actionCatalogResolved = true + } else { + actionCatalogResolved = false + } + lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { + while (isActive) { + actionCatalog = RemoteActionCatalogGateway.fetch(force = true) + actionCatalogResolved = true + delay(REMOTE_ACTION_REFRESH_MS) + } + } + } + + LaunchedEffect(activeProfile, remoteCardDismissCountdown > 0) { + if (remoteCardDismissCountdown <= 0) return@LaunchedEffect + while (remoteCardDismissCountdown > 0) { + delay(1_000) + remoteCardDismissCountdown-- + } + } + + LaunchedEffect(activeProfile, accessLifecycleDismissCountdown > 0) { + if (accessLifecycleDismissCountdown <= 0) return@LaunchedEffect + while (accessLifecycleDismissCountdown > 0) { + delay(1_000) + accessLifecycleDismissCountdown-- + } + } + + LaunchedEffect(activeProfile, accessLifecycle.managed) { + if (accessLifecycle.managed) { + AccessLifecycleCoordinator.refreshProfile(context, activeProfile, force = false) + } else { + TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS) + } + } val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle() + val tunnelTransition by TunnelManager.transition.collectAsStateWithLifecycle() val trustedWifiState by TrustedWifiManager.state.collectAsStateWithLifecycle() val trustedWifiWaiting = trustedWifiState.waiting val connectionIssue by TunnelManager.connectionIssue.collectAsStateWithLifecycle() + val standaloneConnectionIssue = + connectionIssue?.takeIf { it.isStandaloneUiIssue } val cooldownActive by TunnelManager.cooldownActive.collectAsStateWithLifecycle() - var wasRunning by remember { mutableStateOf(false) } - LaunchedEffect(tunnelRunning) { - if (wasRunning && !tunnelRunning) { - TunnelManager.startCooldown(1500L) - } - wasRunning = tunnelRunning + val loadedHashSlots = remember(profileSnapshot) { parseVkHashSlots(savedVkHashesState) } + var peerInput by remember(profileSnapshot) { mutableStateOf(savedPeer) } + var vkHash1 by remember(profileSnapshot) { mutableStateOf(loadedHashSlots.getOrElse(0) { "" }) } + var vkHash2 by remember(profileSnapshot) { mutableStateOf(loadedHashSlots.getOrElse(1) { "" }) } + var vkHash3 by remember(profileSnapshot) { mutableStateOf(loadedHashSlots.getOrElse(2) { "" }) } + var vkHash4 by remember(profileSnapshot) { mutableStateOf(loadedHashSlots.getOrElse(3) { "" }) } + val loadedWorkers = remember(profileSnapshot) { + val normalized = normalizeTunnelWorkerCount(savedWorkers, profileMaxWorkers) + roundToGroup( + normalized.toFloat(), + maxWorkersForHashSlots(loadedHashSlots, profileMaxWorkers) + ) } - - var peerInput by rememberSaveable { mutableStateOf("") } - var vkHash1 by rememberSaveable { mutableStateOf("") } - var vkHash2 by rememberSaveable { mutableStateOf("") } - var vkHash3 by rememberSaveable { mutableStateOf("") } - var vkHash4 by rememberSaveable { mutableStateOf("") } - var workersInput by rememberSaveable { mutableFloatStateOf(18f) } + var workersInput by remember(profileSnapshot) { mutableFloatStateOf(loadedWorkers) } var showHashesDialog by rememberSaveable { mutableStateOf(false) } - var autoCaptchaEnabled by rememberSaveable { mutableStateOf(true) } - var manualPortsEnabled by rememberSaveable { mutableStateOf(false) } + var autoCaptchaEnabled by remember(profileSnapshot) { + mutableStateOf(savedCaptchaMode != "wv" || savedCaptchaMethod != "manual") + } + var manualPortsEnabled by remember(profileSnapshot) { mutableStateOf(savedManualPortsEnabled) } var showPowerHelp by rememberSaveable { mutableStateOf(false) } var showVkCallsHelp by rememberSaveable { mutableStateOf(false) } var showAutoCaptchaHelp by rememberSaveable { mutableStateOf(false) } - var serverDtlsPortInput by rememberSaveable { mutableStateOf("56000") } - var serverWgPortInput by rememberSaveable { mutableStateOf("56001") } - var initialized by remember { mutableStateOf(false) } + var serverDtlsPortInput by remember(profileSnapshot) { mutableStateOf(savedServerDtlsPort.toString()) } + var serverWgPortInput by remember(profileSnapshot) { mutableStateOf(savedServerWgPort.toString()) } + var userConnectionEditor by remember(activeProfile) { mutableStateOf("") } + var userLinkInput by remember(activeProfile) { mutableStateOf("") } + val storedLinkSelected = remember(profileSnapshot) { + wdttLinkMode && WdttDeepLink.parse(wdttLink, allowMissingHashes = true) != null + } + val importedLinkStoredAsManualFields = remember(profileSnapshot) { + savedConnectionInputMethod == "link" && + !wdttLinkMode && + savedPeer.isNotBlank() && + savedConnectionPassword.isNotBlank() + } + var userConnectionMethod by remember(profileSnapshot) { + mutableStateOf( + resolveConnectionInputMethod( + savedMethod = savedConnectionInputMethod, + hasStoredLink = storedLinkSelected, + hasManualConnection = savedPeer.isNotBlank() && savedConnectionPassword.isNotBlank(), + userInterface = compactTunnelInterface, + ) + ) + } val allHashes = remember(vkHash1, vkHash2, vkHash3, vkHash4) { listOf(vkHash1, vkHash2, vkHash3, vkHash4).map { stripVkUrlStatic(it) } } - val validHashes = remember(allHashes) { allHashes.filter { it.isNotBlank() && it.length >= 16 } } + val validHashes = remember(allHashes) { allHashes.filter(VkJoinLink::isValidHash) } val uniqueHashes = remember(validHashes) { validHashes.distinct() } val wdttLinkValidation = remember(wdttLink) { WdttDeepLink.validate(wdttLink) } val parsedWdttLink = remember(wdttLinkValidation) { wdttLinkValidation.parts } @@ -183,18 +443,22 @@ fun SettingsTabContent( val hashSlotsForStorage = remember(vkHash1, vkHash2, vkHash3, vkHash4) { encodeVkHashSlots(vkHash1, vkHash2, vkHash3, vkHash4) } - val dynamicMaxWorkers = remember(filledHashCount) { maxWorkersForHashCount(filledHashCount) } - var portInput by rememberSaveable { mutableStateOf("9000") } - var sniInput by rememberSaveable { mutableStateOf("") } + val dynamicMaxWorkers = remember(filledHashCount, profileMaxWorkers) { + maxWorkersForHashCount(filledHashCount, profileMaxWorkers) + } + var portInput by remember(profileSnapshot) { mutableStateOf(savedListenPort.toString()) } + var sniInput by remember(profileSnapshot) { mutableStateOf(savedSni) } val currentWorkers = workersInput.coerceIn(WORKERS_PER_GROUP.toFloat(), dynamicMaxWorkers) val hashErrors = remember(vkHash1, vkHash2, vkHash3, vkHash4) { buildList { allHashes.forEachIndexed { i, h -> - if (h.isNotBlank() && h.length < 16) add("Хеш ${i + 1} — короткий") + if (h.isNotBlank() && !VkJoinLink.isValidHash(h)) { + add("Хеш ${i + 1} имеет неверный формат") + } } - val filled = allHashes.filter { it.isNotBlank() && it.length >= 16 } + val filled = allHashes.filter(VkJoinLink::isValidHash) if (filled.size != filled.distinct().size) add("Есть дубликаты хешей") } } @@ -202,82 +466,13 @@ fun SettingsTabContent( var showSecretsDialog by rememberSaveable { mutableStateOf(false) } - LaunchedEffect(activeProfile) { - initialized = false - val peer = settingsStore.peer.first() - val hashes = settingsStore.vkHashes.first() - val workers = settingsStore.workersPerHash.first() - val port = settingsStore.listenPort.first() - val manualPorts = settingsStore.manualPortsEnabled.first() - val serverDtlsPort = settingsStore.serverDtlsPort.first() - val serverWgPort = settingsStore.serverWgPort.first() - val sni = settingsStore.sni.first() - val captchaMode = settingsStore.captchaMode.first() - val captchaMethod = settingsStore.captchaSolveMethod.first() - val hashSlots = parseVkHashSlots(hashes) - - peerInput = peer - vkHash1 = hashSlots.getOrElse(0) { "" } - vkHash2 = hashSlots.getOrElse(1) { "" } - vkHash3 = hashSlots.getOrElse(2) { "" } - vkHash4 = hashSlots.getOrElse(3) { "" } - workersInput = roundToGroup( - workers.toFloat(), - maxWorkersForHashSlots(hashSlots) - ) - portInput = port.toString() - manualPortsEnabled = manualPorts - serverDtlsPortInput = serverDtlsPort.toString() - serverWgPortInput = serverWgPort.toString() - sniInput = sni - // В интерфейсе остаются только реально отличающиеся стратегии: - // комбинированная автоцепочка и немедленный ручной WebView. - // Устаревшие режимы rjs и wv+auto работают как автоматические. - autoCaptchaEnabled = captchaMode != "wv" || captchaMethod != "manual" - - initialized = true - } - - LaunchedEffect(savedVkHashesState) { - val savedVkHashes = savedVkHashesState ?: return@LaunchedEffect - if (initialized && normalizeVkHashSlots(savedVkHashes) != hashSlotsForStorage) { - val hashSlots = parseVkHashSlots(savedVkHashes) - vkHash1 = hashSlots.getOrElse(0) { "" } - vkHash2 = hashSlots.getOrElse(1) { "" } - vkHash3 = hashSlots.getOrElse(2) { "" } - vkHash4 = hashSlots.getOrElse(3) { "" } - val maxWorkers = maxWorkersForHashSlots(hashSlots) - if (workersInput > maxWorkers) { - val clamped = roundToGroup(workersInput, maxWorkers) - workersInput = clamped - settingsStore.saveWorkersPerHash(clamped.toInt()) - } + LaunchedEffect(activeProfile, savedWorkers, profileMaxWorkers) { + val normalizedWorkers = normalizeTunnelWorkerCount(savedWorkers, profileMaxWorkers) + if (normalizedWorkers != savedWorkers) { + settingsStore.saveWorkersPerHash(normalizedWorkers) } } - LaunchedEffect(savedManualPortsEnabled) { - manualPortsEnabled = savedManualPortsEnabled - } - - LaunchedEffect(savedServerDtlsPort) { - serverDtlsPortInput = savedServerDtlsPort.toString() - } - - LaunchedEffect(savedServerWgPort) { - serverWgPortInput = savedServerWgPort.toString() - } - - LaunchedEffect(savedListenPort) { - portInput = savedListenPort.toString() - } - - if (!initialized) { - Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) - } - return - } - var saveJob by remember { mutableStateOf(null) } fun saveTunnelSettingsNow( @@ -287,10 +482,15 @@ fun SettingsTabContent( ) { saveJob?.cancel() scope.launch { + val normalizedWorkers = normalizeTunnelWorkerCount(workers.toInt(), profileMaxWorkers) val savedLocalPort = if (manualPortsEnabled) portInput.toIntOrNull()?.coerceIn(1, 65535) ?: 9000 else 9000 settingsStore.save( peerInput, hashes, "", - workers.toInt(), "udp", savedLocalPort, sniInput, false + normalizedWorkers, "udp", savedLocalPort, sniInput, false + ) + onVkHashesSaved( + activeProfile, + parseVkHashSlots(hashes).filter { it.isNotBlank() }, ) onSaved?.invoke() } @@ -298,18 +498,21 @@ fun SettingsTabContent( fun saveWorkersNow(workers: Float) { scope.launch { - settingsStore.saveWorkersPerHash(workers.toInt()) + settingsStore.saveWorkersPerHash( + normalizeTunnelWorkerCount(workers.toInt(), profileMaxWorkers) + ) } } fun scheduleSave() { saveJob?.cancel() saveJob = scope.launch { + val normalizedWorkers = normalizeTunnelWorkerCount(workersInput.toInt(), profileMaxWorkers) delay(300) val savedLocalPort = if (manualPortsEnabled) portInput.toIntOrNull()?.coerceIn(1, 65535) ?: 9000 else 9000 settingsStore.save( peerInput, hashSlotsForStorage, "", - workersInput.toInt(), "udp", savedLocalPort, sniInput, false + normalizedWorkers, "udp", savedLocalPort, sniInput, false ) } } @@ -320,7 +523,25 @@ fun SettingsTabContent( val isHashesValid = combinedHashes.isNotBlank() val isLinkValid = wdttLinkValidation.canStartVpn val isManualValid = isPeerValid && isHashesValid && savedConnectionPassword.isNotBlank() && !hasInputHashErrors - val isValid = if (wdttLinkMode) isLinkValid else isManualValid + val linkConnectionPresent = remember(wdttLink) { + WdttDeepLink.parse(wdttLink, allowMissingHashes = true) != null + } + val selectedCompactMethodValid = isSelectedCompactConnectionReady( + selectedMethod = userConnectionMethod, + savedMethod = savedConnectionInputMethod, + storedLinkMode = wdttLinkMode, + linkPresent = linkConnectionPresent, + linkValid = isLinkValid, + manualValid = isManualValid, + ) + val isValid = selectedCompactMethodValid + val hasConnectionSource = hasTunnelConnectionSource( + linkMode = wdttLinkMode, + linkValid = linkConnectionPresent, + peer = peerInput, + password = savedConnectionPassword, + ) + val showManualConnectionFields = false val effectiveServerDtlsPort = if (manualPortsEnabled) serverDtlsPortInput.toIntOrNull()?.coerceIn(1, 65535) ?: 56000 else 56000 val effectiveLocalPort = if (manualPortsEnabled) portInput.toIntOrNull()?.coerceIn(1, 65535) ?: 9000 else 9000 var pendingStartAfterVpnPermission by remember { mutableStateOf(false) } @@ -328,11 +549,12 @@ fun SettingsTabContent( fun startTunnelService() { val effectiveCaptchaMode = if (autoCaptchaEnabled) "auto" else "wv" val effectiveCaptchaSolveMethod = if (autoCaptchaEnabled) "auto" else "manual" + val normalizedWorkers = normalizeTunnelWorkerCount(workersInput.toInt(), profileMaxWorkers) saveJob?.cancel() scope.launch { settingsStore.save( peerInput, hashSlotsForStorage, "", - workersInput.toInt(), "udp", effectiveLocalPort, sniInput, false + normalizedWorkers, "udp", effectiveLocalPort, sniInput, false ) settingsStore.saveCaptchaMode(effectiveCaptchaMode) settingsStore.saveCaptchaSolveMethod(effectiveCaptchaSolveMethod) @@ -357,7 +579,7 @@ fun SettingsTabContent( putExtra("peer", finalPeer) putExtra("vk_hashes", finalHashes) putExtra("secondary_vk_hash", "") - putExtra("workers_per_hash", workersInput.toInt()) + putExtra("workers_per_hash", normalizedWorkers) putExtra("port", finalLocalPort) putExtra("sni", sniInput) putExtra("connection_password", finalPassword) @@ -366,6 +588,18 @@ fun SettingsTabContent( putExtra("captcha_solve_method", effectiveCaptchaSolveMethod) putExtra("fingerprint", activeFingerprint) putExtra("client_ids", activeClientIds) + putExtra("custom_vk_credentials_enabled", customVkCredentialsEnabled) + putExtra("custom_vk_client_id", customVkClientId) + putExtra("custom_vk_client_secret", customVkClientSecret) + putExtra("profile_max_workers", profileMaxWorkers) + putExtra( + MANAGED_CONFIG_FIRST_START_EXTRA, + shouldUseManagedConfigFirstStart( + remoteManaged = remoteManagedProfile, + profileMaxWorkers = profileMaxWorkers, + ), + ) + putExtra(TUNNEL_PROFILE_INDEX_EXTRA, activeProfile) } if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent) @@ -384,6 +618,7 @@ fun SettingsTabContent( "VPN-разрешение не выдано", "Разрешите WDTT Plus создать VPN-подключение в системном окне Android и нажмите «Подключить» ещё раз." ) + TunnelManager.clearTransition() Toast.makeText(context, "VPN-разрешение не выдано", Toast.LENGTH_SHORT).show() } } @@ -400,10 +635,274 @@ fun SettingsTabContent( } } + fun checkAccessAndStart() { + TunnelManager.noteStartRequested() + scope.launch { + try { + when ( + val decision = AccessLifecycleCoordinator.prepareStart( + context, + activeProfile, + ) + ) { + AccessStartDecision.Allowed -> requestVpnAndStart() + is AccessStartDecision.Denied -> { + TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS) + TunnelManager.clearTransition() + } + } + } catch (cancelled: CancellationException) { + TunnelManager.clearTransition() + throw cancelled + } catch (error: Exception) { + TunnelManager.clearTransition() + TunnelManager.reportConnectionIssue( + if (accessLifecycle.managed) { + "Не удалось проверить доступ" + } else { + "Не удалось начать подключение" + }, + error.message ?: "Проверьте интернет и повторите попытку.", + ) + } + } + } + + fun openHashesSettings() { + if (!wdttLinkMode) { + showHashesDialog = true + return + } + scope.launch { + val parts = settingsStore.materializeActiveLinkProfile() + if (parts == null) { + Toast.makeText( + context, + "Не удалось подготовить профиль. Получите или добавьте ссылку подключения заново.", + Toast.LENGTH_LONG + ).show() + return@launch + } + val slots = parseVkHashSlots(parts.hashes) + vkHash1 = slots.getOrElse(0) { "" } + vkHash2 = slots.getOrElse(1) { "" } + vkHash3 = slots.getOrElse(2) { "" } + vkHash4 = slots.getOrElse(3) { "" } + userConnectionEditor = "" + showHashesDialog = true + } + } + + fun openUserLinkEditor() { + userConnectionMethod = "link" + userLinkInput = if (wdttLinkMode) wdttLink else "" + userConnectionEditor = "link" + } + + fun openRemoteUpdateEditor() { + userLinkInput = "" + userConnectionEditor = "remote-update" + } + + fun openUserManualEditor() { + userConnectionMethod = "manual" + scope.launch { + if (wdttLinkMode && linkConnectionPresent) { + val materialized = settingsStore.materializeActiveLinkProfile() + if (materialized == null) { + Toast.makeText( + context, + "Не удалось подготовить ссылку для ручного изменения.", + Toast.LENGTH_LONG + ).show() + return@launch + } + } else if (wdttLinkMode) { + settingsStore.saveWdttLinkMode(false) + settingsStore.saveWdttLink("") + } + userLinkInput = "" + userConnectionEditor = "manual" + } + } + + fun saveUserWdttLink() { + val cleanLink = userLinkInput.filterNot(Char::isWhitespace) + val remoteDocument = RemoteDocumentGateway.extractLink(cleanLink) + if (remoteManagedProfile && remoteDocument == null) { + Toast.makeText( + context, + "Вставьте короткую HTTPS-ссылку обновления для этого профиля.", + Toast.LENGTH_LONG + ).show() + return + } + if (remoteDocument != null) { + val opened = runCatching { + context.startActivity( + Intent(context, MainActivity::class.java) + .setAction(Intent.ACTION_VIEW) + .setData(Uri.parse(remoteDocument.url)) + .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) + ) + }.isSuccess + if (opened) { + userLinkInput = "" + userConnectionEditor = "" + } else { + Toast.makeText( + context, + "Не удалось открыть ссылку обновления.", + Toast.LENGTH_LONG + ).show() + } + return + } + if (WdttDeepLink.parse(cleanLink, allowMissingHashes = true) == null) return + scope.launch { + val result = settingsStore.applyWdttDeepLink( + plan = WdttDeepLinkApplyPlan( + link = cleanLink, + targetProfile = activeProfile, + requiresConfirmation = hasConnectionSource, + storeAsLink = false + ), + resetRemoteContinuation = true, + remoteManaged = false + ) + if (result == null) { + Toast.makeText(context, "Ссылка WDTT не распознана.", Toast.LENGTH_LONG).show() + } else { + userLinkInput = "" + userConnectionEditor = "" + Toast.makeText(context, "Подключение сохранено", Toast.LENGTH_SHORT).show() + } + } + } + // ═══ Dialogs ═══ + if (userConnectionEditor == "link" || userConnectionEditor == "remote-update") { + UserWdttLinkDialog( + linkText = userLinkInput, + onLinkTextChange = { userLinkInput = it.filterNot(Char::isWhitespace) }, + onPaste = { + val clipboard = context.getSystemService(ClipboardManager::class.java) + val pasted = clipboard + ?.primaryClip + ?.takeIf { it.itemCount > 0 } + ?.getItemAt(0) + ?.coerceToText(context) + ?.toString() + .orEmpty() + .filterNot(Char::isWhitespace) + if (pasted.isBlank()) { + Toast.makeText(context, "В буфере обмена нет ссылки", Toast.LENGTH_SHORT).show() + } else { + userLinkInput = pasted + } + }, + onSave = ::saveUserWdttLink, + allowMissingHashes = true, + importedLinkStoredAsManualFields = importedLinkStoredAsManualFields, + remoteUpdateOnly = userConnectionEditor == "remote-update" || remoteManagedProfile, + cachedAction = cachedRemoteAction, + onCachedAction = { + val clipboard = context.getSystemService(ClipboardManager::class.java) + clipboard?.setPrimaryClip( + ClipData.newPlainText( + cachedRemoteAction.clipboardLabel.ifBlank { "WDTT Plus" }, + cachedRemoteAction.payload, + ) + ) + val opened = runCatching { + launchRemoteTarget(context, cachedRemoteAction.target) + }.isSuccess + Toast.makeText( + context, + if (opened) { + cachedRemoteAction.copiedMessage.ifBlank { + "Данные скопированы. Продолжите в открывшемся приложении." + } + } else { + cachedRemoteAction.failedMessage.ifBlank { + "Данные скопированы, но страницу не удалось открыть." + } + }, + Toast.LENGTH_LONG, + ).show() + }, + title = if (userConnectionEditor == "remote-update" || remoteManagedProfile) { + "Обновить маршрут" + } else if (compactTunnelInterface) { + "Добавить ссылку WDTT" + } else { + "Ссылка WDTT" + }, + subtitle = if (userConnectionEditor == "remote-update" || remoteManagedProfile) { + "" + } else if (compactTunnelInterface) { + "Ссылку может бесплатно выдать владелец любого совместимого сервера." + } else { + "Вставьте ссылку подключения для текущего профиля." + }, + onDismiss = { + userLinkInput = "" + userConnectionEditor = "" + } + ) + } + + if (userConnectionEditor == "manual" && !remoteManagedProfile) { + UserManualConnectionDialog( + initialPeer = peerInput, + initialPassword = savedConnectionPassword, + initialManualPortsEnabled = manualPortsEnabled, + initialServerDtlsPort = serverDtlsPortInput, + initialServerWgPort = serverWgPortInput, + initialLocalPort = portInput, + portsHint = if (compactTunnelInterface) { + "Включите, только если владелец сервера выдал другие порты." + } else { + "Включите, если сервер настроен на другие порты." + }, + onSave = { draft -> + scope.launch { + settingsStore.saveManualTunnelConnection( + peer = draft.peer, + password = draft.password, + manualPortsEnabled = draft.manualPortsEnabled, + serverDtlsPort = draft.serverDtlsPort, + serverWgPort = draft.serverWgPort, + listenPort = draft.localPort, + ) + peerInput = draft.peer + manualPortsEnabled = draft.manualPortsEnabled + serverDtlsPortInput = draft.serverDtlsPort.toString() + serverWgPortInput = draft.serverWgPort.toString() + portInput = draft.localPort.toString() + userConnectionEditor = "" + Toast.makeText(context, "Подключение сохранено", Toast.LENGTH_SHORT).show() + } + }, + onDismiss = { userConnectionEditor = "" } + ) + } + if (showSecretsDialog) { SecretsDialog( settingsStore = settingsStore, + title = if (compactTunnelInterface) "Пароль и порты" else "Секреты", + passwordLabel = if (compactTunnelInterface) { + "Пароль подключения" + } else { + "Пароль туннеля" + }, + passwordPlaceholder = if (compactTunnelInterface) { + "Введите пароль, выданный владельцем сервера" + } else { + "Введите пароль туннеля" + }, + allowPortsSelection = compactTunnelInterface, initialPassword = savedConnectionPassword, manualPortsEnabled = manualPortsEnabled, initialServerDtlsPort = serverDtlsPortInput, @@ -421,15 +920,26 @@ fun SettingsTabContent( if (showHashesDialog) { val hashCheckCaptchaMode = if (autoCaptchaEnabled) "auto" else "wv" HashesDialog( + settingsStore = settingsStore, hash1 = vkHash1, hash2 = vkHash2, hash3 = vkHash3, hash4 = vkHash4, activeFingerprint = activeFingerprint, activeClientIds = activeClientIds, + customVkCredentialsEnabled = customVkCredentialsEnabled, + customVkClientId = customVkClientId, + customVkClientSecret = customVkClientSecret, + remoteContinuation = RemoteContinuation( + available = remoteActionKey.isNotBlank() && remoteActionUrl.isNotBlank(), + key = remoteActionKey, + url = remoteActionUrl + ), + remoteAction = actionCatalog.at("profile"), vkCallsPreflight = vkCallsPreflight, captchaMode = hashCheckCaptchaMode, selectedWebViewManual = !autoCaptchaEnabled, + onOpenProjectSupport = onOpenProjectSupport, onSave = { h1, h2, h3, h4 -> val cleaned1 = stripVkUrlStatic(h1) val cleaned2 = stripVkUrlStatic(h2) @@ -439,7 +949,10 @@ fun SettingsTabContent( vkHash2 = cleaned2 vkHash3 = cleaned3 vkHash4 = cleaned4 - val maxWorkers = maxWorkersForHashSlots(listOf(cleaned1, cleaned2, cleaned3, cleaned4)) + val maxWorkers = maxWorkersForHashSlots( + listOf(cleaned1, cleaned2, cleaned3, cleaned4), + profileMaxWorkers + ) val savedWorkers = if (workersInput > maxWorkers) { roundToGroup(workersInput, maxWorkers).also { workersInput = it } } else { @@ -463,16 +976,231 @@ fun SettingsTabContent( .padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { - Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - if (!wdttLinkMode) { - Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - // ═══ Заголовок раздела ═══ - Text( - "Настройки туннеля (${vpnProfileDisplayName(activeProfile, profileNames)})", - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurface - ) + Column { + val tunnelAction = actionCatalog.at("tunnel") + if (shouldShowTunnelRemoteActionCard( + interfaceRole = interfaceRole, + preview = BuildConfig.REMOTE_ACTION_PREVIEW, + hasConnectionSource = hasConnectionSource, + dismissed = remoteCardDismissed, + dismissCountdown = remoteCardDismissCountdown, + actionResolved = actionCatalogResolved, + actionAvailable = tunnelAction != null, + ) + ) { + Column { + if (remoteCardDismissCountdown > 0) { + DismissedNoticeCard( + title = "Предложение скрыто", + message = "Ссылку всегда можно найти в «Инфо» → «Поддержать проект».", + countdown = remoteCardDismissCountdown, + onProjectSupportClick = onOpenProjectSupport, + ) + } else if (tunnelAction != null) { + RemoteActionCard( + action = tunnelAction, + onLinkClick = onOpenProjectSupport, + onClick = { + scope.launch { + val opened = RemoteUiActionLauncher.open(context, tunnelAction) + if (!opened) { + Toast.makeText( + context, + "Не удалось открыть страницу. Проверьте браузер.", + Toast.LENGTH_LONG + ).show() + } + } + }, + onDismiss = { + remoteCardDismissCountdown = 5 + scope.launch { + settingsStore.saveRemoteCardDismissed(activeProfile, true) + } + } + ) + } + Spacer(Modifier.height(12.dp)) + } + } + Text( + "Настройки туннеля (${vpnProfileDisplayName(activeProfile, profileNames)})", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(bottom = 12.dp) + ) + + val accessDismissible = + accessLifecycle.allowConnect && + accessLifecycle.severity == AccessLifecycleSeverity.WARNING + val accessDismissSignature = accessLifecycleDismissalSignature(accessLifecycle) + val accessDismissed = + accessDismissible && + accessDismissSignature.isNotBlank() && + accessDismissSignature == accessLifecycleDismissedSignature + val routeUpdateAvailable = remoteManagedProfile + val accessCardDismissed = + accessDismissible && + accessDismissed && + accessLifecycleDismissCountdown <= 0 && + !routeUpdateAvailable + if ( + accessLifecycle.managed && + !accessCardDismissed + ) { + if (accessLifecycleDismissCountdown > 0 && !routeUpdateAvailable) { + DismissedNoticeCard( + title = "Напоминание скрыто", + message = "Действие для профиля остаётся доступно после следующей проверки.", + countdown = accessLifecycleDismissCountdown, + ) + } else { + AccessLifecycleCard( + lifecycle = accessLifecycle, + refreshing = accessRefreshing || accessManualRefreshBusy, + actionBusy = accessActionBusy, + onRouteUpdate = if (routeUpdateAvailable) { + ::openRemoteUpdateEditor + } else { + null + }, + onDismiss = if (accessDismissible) { + { + accessLifecycleDismissCountdown = 5 + scope.launch { + settingsStore.saveAccessLifecycleDismissedSignature( + activeProfile, + accessDismissSignature, + ) + } + } + } else { + null + }, + onRefresh = { + if (accessManualRefreshBusy) return@AccessLifecycleCard + accessManualRefreshBusy = true + scope.launch { + val startedAt = System.currentTimeMillis() + try { + when ( + val result = AccessLifecycleCoordinator.refreshProfile( + context, + activeProfile, + force = true, + ) + ) { + is AccessLifecycleRefreshResult.Success -> Toast.makeText( + context, + "Данные обновлены", + Toast.LENGTH_SHORT, + ).show() + is AccessLifecycleRefreshResult.Cached -> Toast.makeText( + context, + "Данные уже актуальны", + Toast.LENGTH_SHORT, + ).show() + is AccessLifecycleRefreshResult.Throttled -> Toast.makeText( + context, + "Проверено недавно. Повторите через несколько секунд", + Toast.LENGTH_SHORT, + ).show() + is AccessLifecycleRefreshResult.Failed -> Toast.makeText( + context, + result.message, + Toast.LENGTH_LONG, + ).show() + AccessLifecycleRefreshResult.Unmanaged -> Toast.makeText( + context, + "Проверка недоступна", + Toast.LENGTH_SHORT, + ).show() + } + } finally { + val visibleFor = System.currentTimeMillis() - startedAt + if (visibleFor < 450) delay(450 - visibleFor) + accessManualRefreshBusy = false + } + } + }, + onAction = { + if (accessActionBusy) return@AccessLifecycleCard + accessActionBusy = true + scope.launch { + runCatching { + AccessLifecycleCoordinator.beginAction( + context, + activeProfile, + ) + }.onSuccess { target -> + runCatching { + launchRemoteTarget(context, target) + }.onFailure { error -> + if (error is CancellationException) throw error + Toast.makeText( + context, + error.message ?: "Не удалось открыть страницу.", + Toast.LENGTH_LONG, + ).show() + } + }.onFailure { error -> + if (error is CancellationException) throw error + TunnelManager.noteAccessLifecycleEvent( + key = "action_unavailable_$activeProfile", + message = error.message ?: "Действие сейчас недоступно", + warning = true, + ) + Toast.makeText( + context, + error.message ?: "Действие сейчас недоступно.", + Toast.LENGTH_LONG, + ).show() + } + accessActionBusy = false + } + } + ) + } + Spacer(Modifier.height(12.dp)) + } + + if (!remoteManagedProfile) { + CompactTunnelProfileCard( + hasConnection = hasConnectionSource, + connectionMethod = userConnectionMethod, + savedConnectionMethod = savedConnectionInputMethod, + onConnectionMethodChange = { method -> + userConnectionMethod = method + userLinkInput = "" + userConnectionEditor = "" + }, + onAddLinkClick = ::openUserLinkEditor, + onManualClick = ::openUserManualEditor, + ) + Spacer(Modifier.height(12.dp)) + } + AppSectionCard( + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(0.dp) + ) { + OutlinedButton( + onClick = ::openHashesSettings, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + Icon(Icons.Default.Tag, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + FlexibleButtonText( + "Настройка VK Хешей ($filledHashCount/4)", + fontWeight = FontWeight.SemiBold + ) + } + } + + if (showManualConnectionFields) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { // ═══ Настройки туннеля ═══ AppSectionCard( contentPadding = PaddingValues(16.dp), @@ -497,7 +1225,7 @@ fun SettingsTabContent( ) OutlinedButton( - onClick = { showHashesDialog = true }, + onClick = ::openHashesSettings, modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp), shape = RoundedCornerShape(16.dp), contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), @@ -524,10 +1252,13 @@ fun SettingsTabContent( color = MaterialTheme.colorScheme.error ) } + } } } + Spacer(Modifier.height(12.dp)) + // ═══ Мощность + Капча ═══ AppSectionCard( contentPadding = PaddingValues(16.dp), @@ -573,20 +1304,32 @@ fun SettingsTabContent( val maxWorkers = dynamicMaxWorkers val minWorkers = WORKERS_PER_GROUP.toFloat() val currentWorkersVal = roundToGroup(currentWorkers.coerceIn(minWorkers, maxWorkers), maxWorkers) + val hasProfileWorkerLimit = profileMaxWorkers >= WORKERS_PER_GROUP CompactSteppedSlider( value = currentWorkersVal, onValueChange = { raw -> val rounded = roundToGroup(raw, maxWorkers) workersInput = rounded - saveWorkersNow(rounded) + }, + onValueChangeFinished = { selected -> + saveWorkersNow(roundToGroup(selected, maxWorkers)) }, valueRange = minWorkers..maxWorkers, stepSize = WORKERS_PER_GROUP.toFloat(), - enabled = !tunnelRunning, + enabled = !tunnelRunning && maxWorkers > minWorkers, modifier = Modifier.fillMaxWidth() ) + if (hasProfileWorkerLimit) { + Text( + text = "Для этого профиля доступно до $profileMaxWorkers потоков. Повысить значение выше нельзя.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(4.dp)) + } + // — Разделитель — HorizontalDivider( modifier = Modifier.padding(vertical = 4.dp), @@ -605,7 +1348,7 @@ fun SettingsTabContent( horizontalArrangement = Arrangement.spacedBy(6.dp) ) { Text( - "VKCalls", + "Быстрый VKCalls", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium ) @@ -672,77 +1415,12 @@ fun SettingsTabContent( onCheckedChange = { enabled -> autoCaptchaEnabled = enabled scope.launch { - if (enabled) { - settingsStore.saveCaptchaMode("auto") - settingsStore.saveCaptchaSolveMethod("auto") - } else { - settingsStore.saveCaptchaMode("wv") - settingsStore.saveCaptchaSolveMethod("manual") - settingsStore.saveWbvCaptchaSolveMethod("manual") - } + settingsStore.saveCaptchaPreference(enabled) } } ) } - HorizontalDivider( - modifier = Modifier.padding(vertical = 4.dp), - color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) - ) - - // — Режим ссылки — - Row( - modifier = Modifier - .fillMaxWidth() - .padding(top = 8.dp, bottom = 4.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween - ) { - Text( - "Режим ссылки", - style = MaterialTheme.typography.bodyMedium, - fontWeight = FontWeight.Medium, - modifier = Modifier.weight(1f) - ) - Switch( - checked = wdttLinkMode, - onCheckedChange = { enabled -> - scope.launch { - settingsStore.saveWdttLinkMode(enabled) - } - } - ) - } - - if (wdttLinkMode) { - Column { - var linkText by remember(wdttLink) { mutableStateOf(wdttLink) } - val linkValidation = remember(linkText) { WdttDeepLink.validate(linkText) } - val linkInvalid = linkText.isNotBlank() && !linkValidation.canStartVpn - OutlinedTextField( - value = linkText, - onValueChange = { - val cleaned = it.filter { c -> !c.isWhitespace() } - linkText = cleaned - scope.launch { settingsStore.saveWdttLink(cleaned) } - }, - label = { Text("Ссылка wdtt://") }, - placeholder = { Text("Ссылка wdtt://") }, - isError = linkInvalid, - supportingText = { - if (linkText.isNotBlank()) { - Text(linkValidation.userMessage()) - } - }, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = MaterialTheme.colorScheme.primary, - unfocusedBorderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f), - ) - ) - } - } } } @@ -753,7 +1431,7 @@ fun SettingsTabContent( modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { - if (!wdttLinkMode) { + if (showManualConnectionFields) { OutlinedButton( onClick = { showSecretsDialog = true }, modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 52.dp), @@ -770,7 +1448,10 @@ fun SettingsTabContent( ) { Icon(imageVector = Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) Spacer(modifier = Modifier.width(6.dp)) - FlexibleButtonText("Секреты", fontWeight = FontWeight.SemiBold) + FlexibleButtonText( + if (compactTunnelInterface) "Пароль и порты" else "Секреты", + fontWeight = FontWeight.SemiBold + ) } } @@ -782,16 +1463,19 @@ fun SettingsTabContent( Button( onClick = { + if (tunnelTransition != TunnelTransition.IDLE) return@Button if (tunnelRunning || trustedWifiWaiting) { + TunnelManager.noteStopRequested() context.startService( Intent(context, TunnelService::class.java).apply { action = "STOP" } ) } else { TunnelManager.clearConnectionIssue() - requestVpnAndStart() + checkAccessAndStart() } }, - enabled = (isValid && !cooldownActive) || tunnelRunning || trustedWifiWaiting, + enabled = tunnelTransition == TunnelTransition.IDLE && + ((isValid && !cooldownActive) || tunnelRunning || trustedWifiWaiting), modifier = Modifier .weight(1f) .fillMaxHeight() @@ -811,6 +1495,8 @@ fun SettingsTabContent( Spacer(Modifier.width(6.dp)) FlexibleButtonText( text = when { + tunnelTransition == TunnelTransition.STOPPING -> "Отключаю…" + tunnelTransition == TunnelTransition.STARTING -> "Подключаю…" tunnelRunning -> "Остановить" trustedWifiWaiting -> "Отменить ожидание" cooldownActive -> "Подождите..." @@ -849,7 +1535,7 @@ fun SettingsTabContent( } } - connectionIssue?.let { issue -> + standaloneConnectionIssue?.let { issue -> Surface( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), @@ -889,15 +1575,17 @@ fun SettingsTabContent( minWorkers = WORKERS_PER_GROUP, maxWorkers = dynamicMaxWorkers.toInt(), currentWorkers = currentWorkers.toInt(), + profileMaxWorkers = profileMaxWorkers, onDismiss = { showPowerHelp = false } ) } if (showVkCallsHelp) { SettingsHelpDialog( - title = "VKCalls", + title = "Быстрый VKCalls", paragraphs = listOf( - "Сначала приложение пробует получить TURN-учётные данные через анонимный режим VKCalls без VK Smart Captcha.", - "Обычно это быстрее и стабильнее. Если VKCalls не сработал, VK временно ограничил анонимный вход или всё равно запросил проверку, приложение автоматически переходит к обычной captcha-цепочке." + "Первым приложение пробует современный анонимный путь VKCalls через системный VK Connect. Ему не нужны ваш Client ID, Client secret или VK Smart Captcha — обычно это самый быстрый и стабильный вариант.", + "Если VKCalls временно недоступен, приложение автоматически пробует собственные legacy-реквизиты (если они включены), затем выбранные встроенные legacy Client ID. В legacy-ветке полностью сохраняется авторешение капчи.", + "Переключатель отключает только первый быстрый провайдер. Для обычной работы рекомендуется оставить VKCalls включённым." ), onDismiss = { showVkCallsHelp = false } ) @@ -906,14 +1594,199 @@ fun SettingsTabContent( SettingsHelpDialog( title = "Режим капчи", paragraphs = listOf( + "Эта настройка применяется только к резервным legacy-провайдерам: основной быстрый VKCalls обычно получает TURN-данные без капчи.", "Авто капча: каждый свежий challenge сначала решается через Auto WebView. Go v2 и ручной WebView используются как запасные этапы, если автоматический WebView не дал рабочий токен или VK потребовал более строгую проверку.", - "Всегда вручную: при запросе капчи приложение сразу открывает WebView для самостоятельного прохождения проверки." + "Всегда вручную: если legacy-провайдер получил капчу, приложение сразу открывает WebView для самостоятельного прохождения проверки." ), onDismiss = { showAutoCaptchaHelp = false } ) } } +@Composable +private fun AccessLifecycleCard( + lifecycle: AccessLifecycleUiState, + refreshing: Boolean, + actionBusy: Boolean, + onRouteUpdate: (() -> Unit)?, + onDismiss: (() -> Unit)?, + onRefresh: () -> Unit, + onAction: () -> Unit, +) { + val severity = lifecycle.severity + val accent = when { + severity == AccessLifecycleSeverity.ERROR -> MaterialTheme.colorScheme.error + severity == AccessLifecycleSeverity.WARNING -> MaterialTheme.colorScheme.tertiary + else -> MaterialTheme.colorScheme.primary + } + val container = when { + severity == AccessLifecycleSeverity.ERROR -> + MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.68f) + severity == AccessLifecycleSeverity.WARNING -> + MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.62f) + else -> MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.52f) + } + val icon = when { + lifecycle.checkedAtMillis <= 0 -> Icons.Default.Schedule + !lifecycle.allowConnect -> Icons.Default.Lock + severity == AccessLifecycleSeverity.WARNING -> Icons.Default.WarningAmber + else -> Icons.Default.CheckCircle + } + val title = lifecycle.title.ifBlank { + if (lifecycle.checkedAtMillis <= 0) { + "Проверяем профиль" + } else { + lifecycle.fallbackTitle() + } + } + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(20.dp), + color = container, + border = BorderStroke(1.dp, accent.copy(alpha = 0.36f)), + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(14.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = accent, + modifier = Modifier.size(23.dp), + ) + Text( + text = title, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f), + ) + if (onRouteUpdate != null) { + IconButton( + onClick = onRouteUpdate, + enabled = !actionBusy, + modifier = Modifier.size(36.dp), + ) { + Icon( + Icons.Default.WarningAmber, + contentDescription = "Обновить маршрут", + tint = accent, + modifier = Modifier.size(20.dp), + ) + } + } + IconButton( + onClick = onRefresh, + enabled = !refreshing && !actionBusy, + modifier = Modifier.size(36.dp), + ) { + if (refreshing) { + CircularProgressIndicator( + modifier = Modifier.size(19.dp), + strokeWidth = 2.dp, + color = accent, + ) + } else { + Icon( + Icons.Default.Refresh, + contentDescription = "Проверить профиль", + tint = accent, + modifier = Modifier.size(20.dp), + ) + } + } + if (onDismiss != null) { + CardDismissButton( + contentDescription = "Скрыть напоминание", + onClick = onDismiss, + ) + } + } + if (lifecycle.message.isNotBlank()) { + Text( + text = lifecycle.message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (lifecycle.actionMessage.isNotBlank() && !lifecycle.actionAvailable) { + Text( + text = lifecycle.actionMessage, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (lifecycle.detailValue.isNotBlank() || lifecycle.actionAvailable) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (lifecycle.detailValue.isNotBlank()) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + if (lifecycle.detailLabel.isNotBlank()) { + Text( + text = lifecycle.detailLabel, + style = MaterialTheme.typography.bodySmall, + color = accent.copy(alpha = 0.78f), + ) + } + Text( + text = lifecycle.detailValue, + style = MaterialTheme.typography.bodyMedium, + color = accent, + fontWeight = FontWeight.SemiBold, + ) + } + } else { + Spacer(Modifier.weight(1f)) + } + if (lifecycle.actionAvailable) { + Button( + onClick = onAction, + enabled = !refreshing && !actionBusy, + modifier = Modifier + .widthIn(min = 132.dp) + .heightIn(min = 46.dp), + shape = RoundedCornerShape(14.dp), + contentPadding = PaddingValues( + horizontal = 8.dp, + vertical = 6.dp, + ), + ) { + if (actionBusy) { + CircularProgressIndicator( + modifier = Modifier.size(17.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.onPrimary, + ) + } else { + if (lifecycle.actionIcon == "update") { + Icon(Icons.Default.Update, null, Modifier.size(17.dp)) + Spacer(Modifier.width(5.dp)) + } + FlexibleButtonText( + lifecycle.actionLabel.ifBlank { "Продолжить" } + ) + } + } + } + } + } + } + } +} + @Composable private fun SettingsHelpDialog( title: String, @@ -981,6 +1854,7 @@ private fun PowerHelpDialog( minWorkers: Int, maxWorkers: Int, currentWorkers: Int, + profileMaxWorkers: Int, onDismiss: () -> Unit ) { Dialog(onDismissRequest = onDismiss) { @@ -1032,6 +1906,14 @@ private fun PowerHelpDialog( 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, @@ -1067,6 +1949,16 @@ private fun FlexibleButtonText( ) } +@Composable +private fun FullWidthFieldMessage(text: String, color: Color) { + Text( + text = text, + modifier = Modifier.fillMaxWidth(), + style = MaterialTheme.typography.bodySmall, + color = color + ) +} + // ═══ Reusable mode chip ═══ @Composable private fun ProtocolChip(label: String, selected: Boolean, enabled: Boolean = true, isError: Boolean = false, onClick: () -> Unit) { @@ -1102,6 +1994,7 @@ private fun ProtocolChip(label: String, selected: Boolean, enabled: Boolean = tr private fun CompactSteppedSlider( value: Float, onValueChange: (Float) -> Unit, + onValueChangeFinished: (Float) -> Unit, valueRange: ClosedFloatingPointRange, stepSize: Float, enabled: Boolean, @@ -1113,6 +2006,9 @@ private fun CompactSteppedSlider( val density = LocalDensity.current val thumbRadiusPx = with(density) { 9.dp.toPx() } val trackWidthPx = with(density) { 5.dp.toPx() } + val currentValue by rememberUpdatedState(value) + val currentOnValueChange by rememberUpdatedState(onValueChange) + val currentOnValueChangeFinished by rememberUpdatedState(onValueChangeFinished) fun snap(raw: Float): Float { val min = valueRange.start @@ -1134,13 +2030,21 @@ private fun CompactSteppedSlider( .pointerInput(enabled, valueRange, stepSize) { if (!enabled) return@pointerInput detectTapGestures { offset -> - onValueChange(positionToValue(offset.x, size.width.toFloat())) + val selected = positionToValue(offset.x, size.width.toFloat()) + currentOnValueChange(selected) + currentOnValueChangeFinished(selected) } } .pointerInput(enabled, valueRange, stepSize) { if (!enabled) return@pointerInput - detectDragGestures { change, _ -> - onValueChange(positionToValue(change.position.x, size.width.toFloat())) + var selected = currentValue + detectDragGestures( + onDragStart = { selected = currentValue }, + onDragEnd = { currentOnValueChangeFinished(selected) }, + onDragCancel = { currentOnValueChangeFinished(selected) }, + ) { change, _ -> + selected = positionToValue(change.position.x, size.width.toFloat()) + currentOnValueChange(selected) } } ) { @@ -1231,7 +2135,7 @@ fun ImportantInfoDialog(onDismiss: () -> Unit) { InfoSection( "Профили VPN", - "В боковых настройках доступны VPN 1, VPN 2 и VPN 3. Короткое нажатие переключает профиль, долгое нажатие позволяет переименовать его." + "В боковых настройках доступны VPN 1, VPN 2 и VPN 3. Короткое нажатие выбирает профиль и закрывает настройки, долгое открывает переименование и полную локальную очистку профиля." ) InfoSection( "VK-хеши", @@ -1243,7 +2147,7 @@ fun ImportantInfoDialog(onDismiss: () -> Unit) { ) InfoSection( "Передача подключения", - "Обычное подключение передаётся через «Настройки» → «Передать или получить». Перенос отдельного клиента выполняется именно в блоке «Клиенты и сервер»." + "Обычное подключение передаётся через «Настройки» → «Получить или передать». Перенос отдельного клиента выполняется именно в блоке «Клиенты и сервер»." ) InfoSection( "После новых серверных функций", @@ -1251,7 +2155,7 @@ fun ImportantInfoDialog(onDismiss: () -> Unit) { ) InfoSection( "Капча и мощность", - "Авто-режим старается пройти капчу сам. Несколько VK-хешей распределяют нагрузку, а мощность лучше держать умеренной: чем она выше, тем больше расход батареи и шанс чаще видеть капчу." + "Сначала работает быстрый VKCalls без капчи; авторешение подключается только для резервного способа. Несколько VK-хешей распределяют нагрузку, а мощность лучше держать умеренной: чем она выше, тем больше расход батареи и шанс чаще видеть капчу." ) Spacer(Modifier.height(20.dp)) @@ -1291,16 +2195,25 @@ private fun roundToGroup(value: Float, maxW: Float = 96f): Float { return rounded.coerceIn(WORKERS_PER_GROUP.toFloat(), maxW) } -private fun maxWorkersForHashCount(hashCount: Int): Float { - return (hashCount.coerceAtLeast(1) * 27).toFloat() +private fun maxWorkersForHashCount(hashCount: Int, profileMaxWorkers: Int = 0): Float { + val hashMaximum = hashCount.coerceAtLeast(1) * 27 + return if (profileMaxWorkers >= WORKERS_PER_GROUP) { + minOf(hashMaximum, profileMaxWorkers).toFloat() + } else { + hashMaximum.toFloat() + } } -private fun maxWorkersForHashSlots(hashSlots: List): Float { +private fun maxWorkersForHashSlots( + hashSlots: List, + profileMaxWorkers: Int = 0 +): Float { return maxWorkersForHashCount( hashSlots.count { slot -> val hash = stripVkUrlStatic(slot) - hash.isNotBlank() && hash.length >= 16 - } + VkJoinLink.isValidHash(hash) + }, + profileMaxWorkers ) } @@ -1321,6 +2234,89 @@ private fun parseVkHashSlots(raw: String): List { .let { slots -> slots + List((4 - slots.size).coerceAtLeast(0)) { "" } } } +internal fun parseBulkVkHashes(raw: String): List { + val normalized = raw + .replace(Regex("(?i)%2c"), ",") + .replace(Regex("(?i)%3b"), ";") + .replace(Regex("(?i)%20"), " ") + .replace(Regex("(?i)%09"), " ") + .replace(Regex("(?i)%0d%0a|%0a|%0d"), "\n") + return normalized + .split(Regex("[,;\\s]+")) + .asSequence() + .map { stripVkUrlStatic(it) } + .filter(VkJoinLink::isValidHash) + .distinct() + .take(4) + .toList() +} + +internal enum class BulkVkHashPasteMode { + FillEmpty, + ReplaceAll +} + +internal data class BulkVkHashPasteResult( + val slots: List, + val insertedCount: Int, + val skippedCount: Int +) + +private data class PendingBulkVkHashes( + val hashes: List +) + +internal fun mergeBulkVkHashes( + existingSlots: List, + incomingHashes: List, + mode: BulkVkHashPasteMode +): BulkVkHashPasteResult { + val normalizedExisting = existingSlots + .map { stripVkUrlStatic(it) } + .take(4) + .let { values -> values + List((4 - values.size).coerceAtLeast(0)) { "" } } + val incoming = incomingHashes + .map { stripVkUrlStatic(it) } + .filter(VkJoinLink::isValidHash) + .distinct() + .take(4) + return when (mode) { + BulkVkHashPasteMode.ReplaceAll -> { + val slots = incoming + List((4 - incoming.size).coerceAtLeast(0)) { "" } + BulkVkHashPasteResult( + slots = slots, + insertedCount = incoming.size, + skippedCount = 0 + ) + } + BulkVkHashPasteMode.FillEmpty -> { + val slots = normalizedExisting.toMutableList() + var inserted = 0 + var skipped = 0 + val occupied = slots.filter(VkJoinLink::isValidHash).toMutableSet() + incoming.forEach { hash -> + if (hash in occupied) { + skipped++ + return@forEach + } + val emptyIndex = slots.indexOfFirst { !VkJoinLink.isValidHash(it) } + if (emptyIndex < 0) { + skipped++ + } else { + slots[emptyIndex] = hash + occupied += hash + inserted++ + } + } + BulkVkHashPasteResult( + slots = slots, + insertedCount = inserted, + skippedCount = skipped + ) + } + } +} + private fun encodeVkHashSlots(vararg hashes: String): String { val slots = hashes .map { stripVkUrlStatic(it) } @@ -1340,30 +2336,814 @@ private fun copyVkHashesToClipboard(context: android.content.Context, label: Str Toast.makeText(context, "Скопировано", Toast.LENGTH_SHORT).show() } +private fun Int.hashPlural(): String { + val mod100 = this % 100 + val mod10 = this % 10 + return when { + mod100 in 11..14 -> "хешей" + mod10 == 1 -> "хеш" + mod10 in 2..4 -> "хеша" + else -> "хешей" + } +} + +@Composable +private fun CompactTunnelProfileCard( + hasConnection: Boolean, + connectionMethod: String, + savedConnectionMethod: String, + onConnectionMethodChange: (String) -> Unit, + onAddLinkClick: () -> Unit, + onManualClick: () -> Unit, +) { + AppSectionCard( + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + Text( + "Способ подключения", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold + ) + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + listOf("link" to "Ссылка WDTT", "manual" to "Вручную") + .forEachIndexed { index, (mode, label) -> + SegmentedButton( + selected = connectionMethod == mode, + onClick = { onConnectionMethodChange(mode) }, + shape = SegmentedButtonDefaults.itemShape(index, 2), + icon = { + StableSegmentedButtonIcon(selected = connectionMethod == mode) + }, + ) { + Text(label, textAlign = TextAlign.Center) + } + } + } + val selectedMethodConfigured = hasConnection && ( + savedConnectionMethod == connectionMethod || + savedConnectionMethod.isBlank() && connectionMethod == "manual" + ) + if (connectionMethod == "link") { + OutlinedButton( + onClick = onAddLinkClick, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + FlexibleButtonText( + if (selectedMethodConfigured) "Изменить ссылку" else "Вставить ссылку WDTT", + fontWeight = FontWeight.SemiBold + ) + } + } else { + OutlinedButton( + onClick = onManualClick, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + FlexibleButtonText( + if (selectedMethodConfigured) "Изменить настройки" else "Настроить вручную", + fontWeight = FontWeight.SemiBold + ) + } + } + } +} + +private data class ManualTunnelConnectionDraft( + val peer: String, + val password: String, + val manualPortsEnabled: Boolean, + val serverDtlsPort: Int, + val serverWgPort: Int, + val localPort: Int, +) + +@Composable +private fun UserManualConnectionDialog( + initialPeer: String, + initialPassword: String, + initialManualPortsEnabled: Boolean, + initialServerDtlsPort: String, + initialServerWgPort: String, + initialLocalPort: String, + portsHint: String, + onSave: (ManualTunnelConnectionDraft) -> Unit, + onDismiss: () -> Unit, +) { + val focusManager = LocalFocusManager.current + var peer by rememberSaveable { mutableStateOf(initialPeer) } + var password by rememberSaveable { mutableStateOf(initialPassword) } + var passwordFocused by remember { mutableStateOf(false) } + var manualPortsEnabled by rememberSaveable { mutableStateOf(initialManualPortsEnabled) } + var serverDtlsPort by rememberSaveable { + mutableStateOf(initialServerDtlsPort.ifBlank { "56000" }) + } + var serverWgPort by rememberSaveable { + mutableStateOf(initialServerWgPort.ifBlank { "56001" }) + } + var localPort by rememberSaveable { + mutableStateOf(initialLocalPort.ifBlank { "9000" }) + } + + val passwordValid = password.isNotEmpty() && + password.matches(Regex("^[a-zA-Z0-9_.!?:#/-]+$")) + val parsedDtlsPort = serverDtlsPort.toIntOrNull() + val parsedWgPort = serverWgPort.toIntOrNull() + val parsedLocalPort = localPort.toIntOrNull() + val portsValid = !manualPortsEnabled || listOf( + parsedDtlsPort, + parsedWgPort, + parsedLocalPort + ).all { it != null && it in 1..65535 } + val canSave = isValidTunnelHost(peer) && passwordValid && portsValid + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + BoxWithConstraints( + modifier = Modifier + .fillMaxSize() + .padding(8.dp) + .pointerInput(focusManager) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Press) { + focusManager.clearFocus() + } + } + } + }, + contentAlignment = Alignment.Center + ) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .widthIn(max = 560.dp) + .heightIn(max = maxHeight * 0.92f), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surface, + contentColor = MaterialTheme.colorScheme.onSurface, + tonalElevation = 8.dp + ) { + Column( + modifier = Modifier.padding(22.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Text( + "Подключение вручную", + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary + ) + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Закрыть ручную настройку") + } + } + + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + val peerInvalid = peer.isNotBlank() && !isValidTunnelHost(peer) + OutlinedTextField( + value = peer, + onValueChange = { peer = it.filterNot(Char::isWhitespace) }, + label = { Text("IP сервера или домен") }, + placeholder = { Text("1.2.3.4 или server.example") }, + singleLine = true, + isError = peerInvalid, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp) + ) + if (peerInvalid) { + FullWidthFieldMessage( + text = "Укажите адрес без порта", + color = MaterialTheme.colorScheme.error + ) + } + } + + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + val passwordInvalid = password.isNotBlank() && !passwordValid + OutlinedTextField( + value = password, + onValueChange = { password = it.filterNot(Char::isWhitespace) }, + label = { Text("Пароль подключения") }, + placeholder = { Text("Введите пароль туннеля") }, + singleLine = true, + isError = passwordInvalid, + visualTransformation = if (passwordFocused) { + VisualTransformation.None + } else { + PasswordVisualTransformation() + }, + modifier = Modifier + .fillMaxWidth() + .onFocusChanged { passwordFocused = it.isFocused }, + shape = RoundedCornerShape(16.dp) + ) + if (passwordInvalid) { + FullWidthFieldMessage( + text = "Разрешены буквы, цифры и знаки . ! ? : # - _ /", + color = MaterialTheme.colorScheme.error + ) + } + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) { + Text("Нестандартные порты", fontWeight = FontWeight.SemiBold) + Text( + portsHint, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = manualPortsEnabled, + onCheckedChange = { manualPortsEnabled = it } + ) + } + + if (manualPortsEnabled) { + listOf( + Triple(serverDtlsPort, "Порт сервера DTLS", { value: String -> serverDtlsPort = value }), + Triple(serverWgPort, "Порт сервера WireGuard", { value: String -> serverWgPort = value }), + Triple(localPort, "Локальный порт VPN", { value: String -> localPort = value }), + ).forEach { (value, label, update) -> + val parsed = value.toIntOrNull() + OutlinedTextField( + value = value, + onValueChange = { update(it.filter(Char::isDigit).take(5)) }, + label = { Text(label) }, + singleLine = true, + isError = value.isNotBlank() && (parsed == null || parsed !in 1..65535), + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) + ) + } + } + + Button( + onClick = { + onSave( + ManualTunnelConnectionDraft( + peer = peer.trim(), + password = password, + manualPortsEnabled = manualPortsEnabled, + serverDtlsPort = if (manualPortsEnabled) parsedDtlsPort!! else 56000, + serverWgPort = if (manualPortsEnabled) parsedWgPort!! else 56001, + localPort = if (manualPortsEnabled) parsedLocalPort!! else 9000, + ) + ) + }, + enabled = canSave, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), + shape = RoundedCornerShape(16.dp) + ) { + FlexibleButtonText("Сохранить подключение", fontWeight = FontWeight.Bold) + } + Spacer(Modifier.height(2.dp)) + } + } + } + } +} + +@Composable +private fun UserWdttLinkDialog( + linkText: String, + onLinkTextChange: (String) -> Unit, + onPaste: () -> Unit, + onSave: () -> Unit, + allowMissingHashes: Boolean, + remoteUpdateOnly: Boolean, + cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable, + onCachedAction: () -> Unit = {}, + importedLinkStoredAsManualFields: Boolean, + title: String, + subtitle: String, + onDismiss: () -> Unit, +) { + var showRemoteUpdateHelp by rememberSaveable { mutableStateOf(false) } + val remoteDocument = remember(linkText) { + RemoteDocumentGateway.extractLink(linkText) != null + } + val parsed = remember(linkText, allowMissingHashes) { + if (remoteUpdateOnly) { + null + } else { + WdttDeepLink.parse(linkText, allowMissingHashes = allowMissingHashes) + } + } + val validation = remember(linkText, allowMissingHashes) { + WdttDeepLink.validate(linkText, allowMissingHashes = allowMissingHashes) + } + val invalid = + linkText.isNotBlank() && parsed == null && !remoteDocument + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + BoxWithConstraints( + modifier = Modifier.fillMaxSize().padding(8.dp), + contentAlignment = Alignment.Center + ) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .widthIn(max = 560.dp) + .heightIn(max = maxHeight * 0.92f), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surface, + contentColor = MaterialTheme.colorScheme.onSurface, + tonalElevation = 8.dp + ) { + Column( + modifier = Modifier.padding(22.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + 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 + ) + } + } + if (remoteUpdateOnly) { + IconButton( + onClick = { showRemoteUpdateHelp = true }, + modifier = Modifier.size(40.dp), + ) { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Как обновить маршрут", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp), + ) + } + } + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Закрыть ввод ссылки") + } + } + + if (remoteUpdateOnly && cachedAction.available) { + ElevatedCard( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.elevatedCardColors( + containerColor = + MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f) + ), + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (cachedAction.title.isNotBlank()) { + Text( + cachedAction.title, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSecondaryContainer, + ) + } + Text( + cachedAction.message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer, + ) + OutlinedButton( + onClick = onCachedAction, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + ) { + Icon( + Icons.AutoMirrored.Filled.OpenInNew, + contentDescription = null, + ) + Spacer(Modifier.width(8.dp)) + FlexibleButtonText( + cachedAction.label.ifBlank { "Открыть другой способ" } + ) + } + } + } + } + + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + if (!remoteUpdateOnly && importedLinkStoredAsManualFields && linkText.isBlank()) { + Text( + "Ссылка принята. Данные сохранены в «Вручную»: там их можно изменить, либо здесь вставить новую ссылку.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary + ) + } + OutlinedTextField( + value = linkText, + onValueChange = onLinkTextChange, + label = { + Text(if (remoteUpdateOnly) "Ссылка обновления" else "Ссылка wdtt://") + }, + placeholder = { + Text(if (remoteUpdateOnly) "https://…" else "wdtt://...") + }, + minLines = 2, + maxLines = 4, + isError = invalid, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp) + ) + if (linkText.isNotBlank()) { + FullWidthFieldMessage( + text = when { + remoteDocument -> + "Короткая ссылка откроет обновление в WDTT Plus." + remoteUpdateOnly -> + "Вставьте короткую HTTPS-ссылку обновления." + parsed == null -> validation.userMessage() + validation.canStartVpn -> "Ссылка распознана и готова к подключению." + else -> "Ссылка распознана. VK-хеши можно добавить после сохранения." + }, + color = if (invalid) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + } + ) + } + } + + OutlinedButton( + onClick = onPaste, + modifier = Modifier.fillMaxWidth().heightIn(min = 46.dp), + shape = RoundedCornerShape(14.dp) + ) { + Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + FlexibleButtonText("Вставить из буфера") + } + + Button( + onClick = onSave, + enabled = if (remoteUpdateOnly) { + remoteDocument + } else { + parsed != null || remoteDocument + }, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + FlexibleButtonText("Сохранить подключение", fontWeight = FontWeight.Bold) + } + + Text( + if (remoteUpdateOnly) { + "Ссылка предназначена только для этого профиля и устройства — не публикуйте её." + } else { + "Ссылку также можно отправить в WDTT Plus через системное меню «Поделиться». Она содержит пароль подключения — не публикуйте её." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(Modifier.height(2.dp)) + } + } + } + } + if (remoteUpdateOnly && showRemoteUpdateHelp) { + RemoteUpdateHelpDialog( + cachedAction = cachedAction, + onDismiss = { showRemoteUpdateHelp = false }, + ) + } +} + +@Composable +private fun RemoteUpdateHelpDialog( + cachedAction: CachedRemoteAction, + onDismiss: () -> Unit, +) { + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false), + ) { + BoxWithConstraints( + modifier = Modifier.fillMaxSize().padding(8.dp), + contentAlignment = Alignment.Center, + ) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .widthIn(max = 540.dp) + .heightIn(max = maxHeight * 0.92f), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surface, + contentColor = MaterialTheme.colorScheme.onSurface, + tonalElevation = 10.dp, + ) { + Column( + modifier = Modifier.padding(20.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + cachedAction.helpTitle.ifBlank { "Как обновить маршрут" }, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + ) + IconButton(onClick = onDismiss) { + Icon( + Icons.Default.Close, + contentDescription = "Вернуться к обновлению маршрута", + ) + } + } + Text( + cachedAction.helpIntro.ifBlank { + ("Обычно профиль обновляется автоматически. Это меню понадобится, " + + "если короткая ссылка не открыла WDTT Plus." + ) + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + cachedAction.helpSteps.ifBlank { + ("1. Откройте полученную короткую HTTPS-ссылку на телефоне с " + + "WDTT Plus.\n\n" + + "2. Если приложение не открылось автоматически, скопируйте " + + "эту же ссылку, вставьте её в поле «Ссылка обновления» и " + + "нажмите «Сохранить подключение».\n\n" + + "3. Если доступен другой способ, используйте отдельную кнопку " + + "над полем ссылки." + ) + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + } + } + } + } +} + +@Composable +private fun RemoteActionCard( + action: RemoteUiAction, + onClick: () -> Unit, + onLinkClick: (() -> Unit)? = null, + onDismiss: (() -> Unit)? = null, +) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f), + contentColor = MaterialTheme.colorScheme.onSecondaryContainer, + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) + ) + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(9.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(9.dp) + ) { + Icon(Icons.Default.Cloud, contentDescription = null, modifier = Modifier.size(21.dp)) + Text( + action.title, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold + ) + if (onDismiss != null) { + CardDismissButton( + contentDescription = "Скрыть карточку", + onClick = onDismiss, + ) + } + } + RemoteActionLinkedText( + text = action.compactMessage.ifBlank { action.message }, + linkText = action.compactLinkText, + color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.86f), + onClick = onLinkClick ?: onClick, + ) + if (action.compactButtonVisible) { + OutlinedButton( + onClick = onClick, + modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), + shape = RoundedCornerShape(14.dp), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 7.dp) + ) { + FlexibleButtonText( + action.compactLabel.ifBlank { action.label }, + fontWeight = FontWeight.SemiBold, + ) + Spacer(Modifier.width(6.dp)) + Icon( + Icons.AutoMirrored.Filled.OpenInNew, + contentDescription = null, + modifier = Modifier.size(17.dp), + ) + } + } + } + } +} + +@Composable +private fun RemoteActionLinkedText( + text: String, + linkText: String, + color: Color, + onClick: (() -> Unit)?, +) { + val linkStart = text.indexOf(linkText) + .takeIf { onClick != null && linkText.isNotBlank() && it >= 0 } + if (linkStart == null) { + Text(text = text, style = MaterialTheme.typography.bodySmall, color = color) + return + } + val linkColor = MaterialTheme.colorScheme.primary + val annotatedText = buildAnnotatedString { + append(text.substring(0, linkStart)) + withLink( + LinkAnnotation.Clickable( + tag = "remote-action", + styles = TextLinkStyles( + style = SpanStyle( + color = linkColor, + fontWeight = FontWeight.SemiBold, + textDecoration = TextDecoration.Underline, + ), + pressedStyle = SpanStyle(color = linkColor.copy(alpha = 0.68f)), + ), + linkInteractionListener = { onClick?.invoke() }, + ) + ) { + append(linkText) + } + append(text.substring(linkStart + linkText.length)) + } + Text( + text = annotatedText, + style = MaterialTheme.typography.bodySmall, + color = color, + ) +} + +@Composable +private fun CardDismissButton( + contentDescription: String, + onClick: () -> Unit, +) { + IconButton( + onClick = onClick, + modifier = Modifier.size(32.dp), + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = contentDescription, + modifier = Modifier.size(18.dp), + tint = MaterialTheme.colorScheme.onSecondaryContainer, + ) + } +} + +@Composable +private fun DismissedNoticeCard( + title: String, + message: String, + countdown: Int, + onProjectSupportClick: (() -> Unit)? = null, +) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f), + contentColor = MaterialTheme.colorScheme.onSecondaryContainer, + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) + ) + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(7.dp) + ) { + Text( + title, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold + ) + RemoteActionLinkedText( + text = message, + linkText = "«Инфо» → «Поддержать проект»", + color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.86f), + onClick = onProjectSupportClick, + ) + Text( + "Карточка исчезнет через $countdown с", + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.68f) + ) + } + } +} + // ═══ Модальное окно хешей ═══ @OptIn(ExperimentalMaterial3Api::class) @Composable fun HashesDialog( + settingsStore: SettingsStore, hash1: String, hash2: String, hash3: String, hash4: String, activeFingerprint: String, activeClientIds: String, + customVkCredentialsEnabled: Boolean, + customVkClientId: String, + customVkClientSecret: String, + remoteContinuation: RemoteContinuation, + remoteAction: RemoteUiAction?, vkCallsPreflight: Boolean, captchaMode: String, selectedWebViewManual: Boolean, + onOpenProjectSupport: () -> Unit, onSave: (String, String, String, String) -> Unit, onDismiss: () -> Unit ) { val context = LocalContext.current val scope = rememberCoroutineScope() - var h1 by remember { mutableStateOf(hash1) } - var h2 by remember { mutableStateOf(hash2) } - var h3 by remember { mutableStateOf(hash3) } - var h4 by remember { mutableStateOf(hash4) } + var h1 by remember(hash1) { mutableStateOf(hash1) } + var h2 by remember(hash2) { mutableStateOf(hash2) } + var h3 by remember(hash3) { mutableStateOf(hash3) } + var h4 by remember(hash4) { mutableStateOf(hash4) } var isChecking by remember { mutableStateOf(false) } var checkJob by remember { mutableStateOf(null) } + var isRemoteActionRunning by remember { mutableStateOf(false) } + var remoteActionJob by remember { mutableStateOf(null) } + 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 checkResults by remember { mutableStateOf>(emptyMap()) } var detailSlot by remember { mutableStateOf(null) } val dialogScrollState = rememberScrollState() @@ -1377,9 +3157,21 @@ fun HashesDialog( } val checkableHashes = remember(currentHashes) { currentHashes.mapIndexedNotNull { index, hash -> - if (hash.length >= 16) index + 1 to hash else null + if (VkJoinLink.isValidHash(hash)) index + 1 to hash else null } } + val dialogHashErrors = remember(currentHashes) { + buildList { + currentHashes.forEachIndexed { index, hash -> + if (hash.isNotBlank() && !VkJoinLink.isValidHash(hash)) { + add("VK Хеш ${index + 1} имеет неверный формат") + } + } + val filled = currentHashes.filter(VkJoinLink::isValidHash) + if (filled.size != filled.distinct().size) add("Есть дубликаты VK-хешей") + } + } + 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 } } @@ -1397,14 +3189,165 @@ fun HashesDialog( } } } + fun cancelRemoteAction(updateUi: Boolean = true) { + remoteActionJob?.cancel(CancellationException("Remote action cancelled by user")) + remoteActionJob = null + isRemoteActionRunning = false + if (updateUi) { + remoteActionMessage = remoteAction?.cancelledMessage + ?.takeIf { it.isNotBlank() } + ?: "Действие остановлено." + } + } + fun applyBulkHashes( + hashes: List, + mode: BulkVkHashPasteMode + ) { + val result = mergeBulkVkHashes( + existingSlots = listOf(h1, h2, h3, h4), + incomingHashes = hashes, + mode = mode + ) + h1 = result.slots[0] + h2 = result.slots[1] + h3 = result.slots[2] + h4 = result.slots[3] + bulkPasteHasError = when (mode) { + BulkVkHashPasteMode.ReplaceAll -> result.insertedCount < 4 + BulkVkHashPasteMode.FillEmpty -> result.insertedCount == 0 + } + bulkPasteMessage = when (mode) { + BulkVkHashPasteMode.ReplaceAll -> { + if (result.insertedCount == 4) { + "Готово: все четыре поля перезаписаны из буфера обмена." + } else { + "Перезаписал поля: найдено ${result.insertedCount} ${result.insertedCount.hashPlural()}." + } + } + BulkVkHashPasteMode.FillEmpty -> { + when { + result.insertedCount == 0 -> + "Пустых мест для новых хешей нет или все найденные хеши уже были в полях." + result.skippedCount > 0 -> + "Заполнил ${result.insertedCount} ${result.insertedCount.hashPlural()} в пустых полях, ${result.skippedCount} пропущено." + else -> + "Заполнил ${result.insertedCount} ${result.insertedCount.hashPlural()} в пустых полях." + } + } + } + pendingBulkPasteHashes = null + } + fun startRemoteAction() { + cancelHashCheck() + remoteActionJob?.cancel(CancellationException("Restarting remote action")) + if (!remoteContinuation.available) { + isRemoteActionRunning = false + remoteActionHasError = true + remoteActionMessage = remoteAction?.message + ?.takeIf { it.isNotBlank() } + ?: remoteContinuation.message.takeIf { it.isNotBlank() } + ?: "Автоматическое заполнение недоступно. Данные можно добавить вручную." + return + } + remoteActionJob = scope.launch { + val runningJob = coroutineContext[Job] + isRemoteActionRunning = true + remoteActionHasError = false + remoteActionMessage = remoteAction?.preparingMessage + ?.takeIf { it.isNotBlank() } + ?: "Подготавливаю переход..." + try { + if ( + TunnelManager.running.value || + TunnelManager.transition.value != TunnelTransition.IDLE + ) { + remoteActionMessage = remoteAction?.stoppingMessage + ?.takeIf { it.isNotBlank() } + ?: "Останавливаю VPN перед продолжением..." + } + val stopResult = TunnelStopCoordinator.stopAndAwait(context) + if (!stopResult.succeeded) { + throw IllegalStateException( + if (stopResult == TunnelStopResult.TIMED_OUT) { + "VPN не остановился за 20 секунд. Повторите попытку." + } else { + "Не удалось запросить остановку VPN. Остановите туннель и повторите попытку." + } + ) + } + if (stopResult == TunnelStopResult.STOPPED) { + delay(TunnelStopCoordinator.DIRECT_NETWORK_SETTLE_MS) + } + remoteActionMessage = remoteAction?.openingMessage + ?.takeIf { it.isNotBlank() } + ?: "Открываю продолжение..." + val target = RemoteContinuationLauncher.begin( + capability = remoteContinuation, + device = settingsStore.getOrCreateConnectDeviceId() + ) + 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() } + ?: "Действие остановлено." + } catch (error: Exception) { + remoteActionHasError = true + remoteActionMessage = error.message + ?: remoteAction?.failureMessage?.takeIf { it.isNotBlank() } + ?: "Не удалось выполнить действие." + } finally { + if (remoteActionJob === runningJob) { + isRemoteActionRunning = false + } + if (remoteActionJob === runningJob) { + remoteActionJob = null + } + } + } + } + fun pasteHashesFromClipboard() { + val clipboard = context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager + val raw = clipboard.primaryClip + ?.takeIf { it.itemCount > 0 } + ?.getItemAt(0) + ?.coerceToText(context) + ?.toString() + .orEmpty() + val hashes = parseBulkVkHashes(raw) + if (hashes.isEmpty()) { + bulkPasteHasError = true + bulkPasteMessage = "В буфере обмена не нашёл VK-хеши или ссылки VK Звонков." + return + } + val hasExistingHashes = listOf(h1, h2, h3, h4) + .map { stripVkUrlStatic(it) } + .any(VkJoinLink::isValidHash) + if (hasExistingHashes) { + pendingBulkPasteHashes = PendingBulkVkHashes(hashes) + } else { + applyBulkHashes(hashes, BulkVkHashPasteMode.ReplaceAll) + } + } fun closeDialog() { cancelHashCheck() + cancelRemoteAction(updateUi = false) onDismiss() } DisposableEffect(Unit) { onDispose { cancelHashCheck(updateUi = false) + cancelRemoteAction(updateUi = false) } } @@ -1433,6 +3376,127 @@ 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( + onDismissRequest = { pendingBulkPasteHashes = null }, + title = { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text(titleText) + IconButton( + onClick = { pendingBulkPasteHashes = null }, + modifier = Modifier.size(42.dp) + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.72f), + modifier = Modifier.size(32.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + Icons.Default.Close, + contentDescription = "Отмена", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + } + } + } + } + }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text("В полях уже есть сохранённые хеши. $sourceText ${hashes.size} ${hashes.size.hashPlural()}.") + Text("«Заполнить пустые» сохранит уже заполненные поля и вставит новые хеши только в свободные места.") + Text( + if (hashes.size >= 4) { + "«Перезаписать все 4» полностью заменит текущие четыре поля хешами из буфера." + } else { + "«Перезаписать» заменит поля найденными хешами, а оставшиеся позиции очистит." + }, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + }, + confirmButton = { + TextButton( + onClick = { applyBulkHashes(hashes, BulkVkHashPasteMode.ReplaceAll) }, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + FlexibleButtonText( + if (hashes.size >= 4) "Перезаписать все 4" else "Перезаписать", + color = MaterialTheme.colorScheme.error + ) + } + }, + dismissButton = { + TextButton( + onClick = { applyBulkHashes(hashes, BulkVkHashPasteMode.FillEmpty) }, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + FlexibleButtonText("Заполнить пустые") + } + } + ) + } + Dialog( onDismissRequest = { closeDialog() }, properties = DialogProperties(usePlatformDefaultWidth = false) @@ -1469,9 +3533,45 @@ fun HashesDialog( 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) + Spacer(Modifier.width(4.dp)) + IconButton( + onClick = { showHashesHelp = true }, + modifier = Modifier.size(36.dp) + ) { + 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) + ) + } + } + } } - IconButton(onClick = { closeDialog() }) { - Icon(Icons.Default.Close, contentDescription = "Закрыть") + IconButton( + onClick = { closeDialog() }, + 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) + ) + } + } } } @@ -1479,6 +3579,10 @@ fun HashesDialog( text = if (isChecking) { val current = currentCheckSlot?.let { " Сейчас: VK Хеш $it." } ?: "" "Проверено $completedChecks из ${checkableHashes.size}.$current" + } else if (isRemoteActionRunning) { + remoteActionMessage + ?: remoteAction?.progressLabel?.takeIf { it.isNotBlank() } + ?: "Выполняется…" } else { "Больше хешей — выше лимит потоков и лучшее распределение нагрузки." }, @@ -1487,8 +3591,66 @@ 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) + ) { + 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(), + 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 + } + ) { + Text( + text = message, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp), + style = MaterialTheme.typography.bodySmall + ) + } + } + listOf( - Triple("VK Хеш 1 *", h1) { v: String -> h1 = v }, + 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 } @@ -1506,7 +3668,12 @@ fun HashesDialog( result = checkResults[slot], onInfoClick = { detailSlot = slot }, canCopy = cleanedValue.isNotBlank(), - onCopyClick = { copyVkHashesToClipboard(context, "VK Хеш $slot", cleanedValue) } + onCopyClick = { copyVkHashesToClipboard(context, "VK Хеш $slot", cleanedValue) }, + canClear = value.isNotBlank(), + onClearClick = { + onChange("") + checkResults = checkResults - slot + } ) } @@ -1522,6 +3689,72 @@ fun HashesDialog( FlexibleButtonText("Скопировать все хеши", fontWeight = FontWeight.SemiBold) } + if (remoteContinuation.available) { + OutlinedButton( + onClick = { showRemoteActionInfo = true }, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + enabled = !isChecking && !isRemoteActionRunning, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + if (isRemoteActionRunning) { + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.primary + ) + Spacer(Modifier.width(6.dp)) + FlexibleButtonText( + remoteAction?.progressLabel + ?.takeIf { it.isNotBlank() } + ?: "Выполняется…", + ) + } 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 (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")) @@ -1536,6 +3769,9 @@ fun HashesDialog( hashes = checkableHashes, fingerprint = activeFingerprint, clientIds = activeClientIds, + customVkCredentialsEnabled = customVkCredentialsEnabled, + customVkClientId = customVkClientId, + customVkClientSecret = customVkClientSecret, vkCallsPreflight = vkCallsPreflight, captchaMode = captchaMode, selectedWebViewManual = selectedWebViewManual, @@ -1588,6 +3824,14 @@ fun HashesDialog( } } + dialogHashErrors.firstOrNull()?.let { error -> + Text( + text = error, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall + ) + } + Button( onClick = { cancelHashCheck() @@ -1595,7 +3839,7 @@ fun HashesDialog( }, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), shape = RoundedCornerShape(16.dp), - enabled = h1.isNotBlank() && h1.length >= 16, + enabled = canSaveHashes, contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary) ) { @@ -1604,9 +3848,245 @@ fun HashesDialog( } } } + + if (showHashesHelp) { + VkHashesInstructionDialog( + remoteAction = remoteAction, + onOpenProjectSupport = { + showHashesHelp = false + closeDialog() + onOpenProjectSupport() + }, + onDismiss = { showHashesHelp = false }, + ) + } } } +@Composable +private fun VkHashesInstructionDialog( + remoteAction: RemoteUiAction?, + onOpenProjectSupport: () -> Unit, + onDismiss: () -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + BoxWithConstraints( + modifier = Modifier.fillMaxSize().padding(8.dp), + contentAlignment = Alignment.Center + ) { + Surface( + modifier = 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 + ) { + Box { + Column( + modifier = Modifier + .padding(22.dp) + .fillMaxWidth() + .verticalScroll(rememberScrollState()), + 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) + ) { + 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) + ) + } + } + } + } + } + } + } +} + +@Composable +private fun VkHashInstructionStep(number: Int, text: String) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.Top, + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.size(28.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Text( + number.toString(), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.Bold + ) + } + } + Text( + text, + modifier = Modifier.weight(1f).padding(top = 3.dp), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } +} + private data class HashCheckResult( val hash: String, val status: String, @@ -1622,13 +4102,15 @@ private fun HashInputField( result: HashCheckResult?, onInfoClick: () -> Unit, canCopy: Boolean, - onCopyClick: () -> Unit + onCopyClick: () -> Unit, + canClear: Boolean, + onClearClick: () -> Unit ) { - val isShort = value.isNotBlank() && value.length < 16 + val isInvalid = value.isNotBlank() && !VkJoinLink.isValidHash(value) val visibleResult = result?.takeIf { it.status != "pending" } val statusColor = visibleResult?.let { hashStatusColor(it.status) } val borderColor = when { - isShort -> MaterialTheme.colorScheme.error + isInvalid -> MaterialTheme.colorScheme.error statusColor != null -> statusColor else -> MaterialTheme.colorScheme.outline.copy(alpha = 0.45f) } @@ -1636,27 +4118,35 @@ private fun HashInputField( ?.takeIf { it.status in setOf("checking", "solving_captcha") } ?.message - OutlinedTextField( - value = value, - onValueChange = onValueChange, - label = { Text(label) }, - placeholder = { Text("Ссылка звонка или хеш") }, - singleLine = true, - isError = isShort, - supportingText = when { - isShort -> { - { Text("Хеш $slot — короткий (мин. 16)", color = MaterialTheme.colorScheme.error) } - } - progressMessage != null -> { - { Text(progressMessage, color = borderColor) } - } - else -> null - }, - trailingIcon = { + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + OutlinedTextField( + value = value, + onValueChange = onValueChange, + label = { Text(label) }, + placeholder = { Text("Ссылка звонка или хеш") }, + singleLine = true, + isError = isInvalid, + trailingIcon = { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp) ) { + if (canClear) { + IconButton( + onClick = onClearClick, + modifier = Modifier.size(34.dp) + ) { + Icon( + Icons.Default.Close, + contentDescription = "Очистить VK Хеш $slot", + modifier = Modifier.size(18.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } IconButton( onClick = onCopyClick, enabled = canCopy, @@ -1692,25 +4182,38 @@ private fun HashInputField( } } } - }, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(16.dp), - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = borderColor, - unfocusedBorderColor = borderColor, - errorBorderColor = MaterialTheme.colorScheme.error, - focusedLabelColor = borderColor, - cursorColor = MaterialTheme.colorScheme.primary + }, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = borderColor, + unfocusedBorderColor = borderColor, + errorBorderColor = MaterialTheme.colorScheme.error, + focusedLabelColor = MaterialTheme.colorScheme.onSurfaceVariant, + unfocusedLabelColor = MaterialTheme.colorScheme.onSurfaceVariant, + errorLabelColor = MaterialTheme.colorScheme.error, + cursorColor = MaterialTheme.colorScheme.primary + ) ) - ) + when { + isInvalid -> FullWidthFieldMessage( + text = "Хеш $slot имеет неверный формат", + color = MaterialTheme.colorScheme.error + ) + progressMessage != null -> FullWidthFieldMessage( + text = progressMessage, + color = borderColor + ) + } + } } @Composable private fun hashStatusColor(status: String): Color { return when (status) { "ok" -> WDTTColors.connected - "dead" -> MaterialTheme.colorScheme.error - "captcha", "solving_captcha", "limited", "network" -> WDTTColors.warning + "dead", "blocked" -> MaterialTheme.colorScheme.error + "full", "captcha", "solving_captcha", "limited", "network" -> WDTTColors.warning "checking" -> MaterialTheme.colorScheme.primary "pending" -> MaterialTheme.colorScheme.outline "cancelled" -> MaterialTheme.colorScheme.outline @@ -1722,6 +4225,8 @@ private fun hashStatusLabel(status: String): String { return when (status) { "ok" -> "живой" "dead" -> "закрыт" + "blocked" -> "вход запрещён" + "full" -> "заполнен" "captcha" -> "капча" "solving_captcha" -> "решаем капчу" "limited" -> "лимит VK" @@ -1771,12 +4276,18 @@ private suspend fun checkVkHashes( hashes: List>, fingerprint: String, clientIds: String, + customVkCredentialsEnabled: Boolean, + customVkClientId: String, + customVkClientSecret: String, vkCallsPreflight: Boolean, captchaMode: String, selectedWebViewManual: Boolean, onUpdate: (Int, HashCheckResult) -> Unit ): Map = withContext(Dispatchers.IO) { if (hashes.isEmpty()) return@withContext emptyMap() + if (customVkCredentialsEnabled && (!isValidVkClientId(customVkClientId) || customVkClientSecret.isBlank())) { + error("Заполните Client ID и Client secret в настройках собственных резервных реквизитов") + } val binaryPath = context.applicationInfo.nativeLibraryDir + "/libclient.so" val command = mutableListOf( binaryPath, @@ -1787,10 +4298,7 @@ private suspend fun checkVkHashes( captchaMode, "-vkcalls-preflight=$vkCallsPreflight", "-device-id", - android.provider.Settings.Secure.getString( - context.contentResolver, - android.provider.Settings.Secure.ANDROID_ID - ) ?: "unknown" + SettingsStore(context).getOrCreateTunnelDeviceId() ) if (fingerprint.isNotBlank()) { command += listOf("-fingerprint", fingerprint) @@ -1803,6 +4311,13 @@ private suspend fun checkVkHashes( .redirectErrorStream(true) .apply { environment()["LD_LIBRARY_PATH"] = context.applicationInfo.nativeLibraryDir + if (customVkCredentialsEnabled) { + environment()["WDTT_CUSTOM_VK_CLIENT_ID"] = customVkClientId + environment()["WDTT_CUSTOM_VK_CLIENT_SECRET"] = customVkClientSecret + } else { + environment().remove("WDTT_CUSTOM_VK_CLIENT_ID") + environment().remove("WDTT_CUSTOM_VK_CLIENT_SECRET") + } } .start() @@ -1963,6 +4478,8 @@ private fun hashStatusMessage(status: String): String { return when (status) { "ok" -> "Хеш работает, TURN-креды получены" "dead" -> "Звонок не найден или закрыт" + "blocked" -> "Звонок существует, но в нём запрещён анонимный вход" + "full" -> "Звонок существует, но сейчас в нём нет свободных мест" "captcha" -> "VK запросил капчу, но решить её не удалось" "limited" -> "VK временно ограничил запросы" "network" -> "Сетевая ошибка при проверке" @@ -1976,6 +4493,10 @@ private fun hashStatusMessage(status: String): String { @Composable fun SecretsDialog( settingsStore: SettingsStore, + title: String = "Секреты", + passwordLabel: String = "Заданный пароль туннеля", + passwordPlaceholder: String = "Придумайте надежный пароль", + allowPortsSelection: Boolean = false, initialPassword: String, manualPortsEnabled: Boolean, initialServerDtlsPort: String, @@ -1990,6 +4511,7 @@ fun SecretsDialog( var serverDtlsPort by rememberSaveable { mutableStateOf(initialServerDtlsPort.ifBlank { "56000" }) } var serverWgPort by rememberSaveable { mutableStateOf(initialServerWgPort.ifBlank { "56001" }) } var localPort by rememberSaveable { mutableStateOf(initialLocalPort.ifBlank { "9000" }) } + var portsEnabled by rememberSaveable { mutableStateOf(manualPortsEnabled) } fun normalizePort(value: String, fallback: String): String { return value.toIntOrNull()?.takeIf { it in 1..65535 }?.toString() ?: fallback @@ -2023,7 +4545,7 @@ fun SecretsDialog( modifier = Modifier.size(24.dp) ) Spacer(modifier = Modifier.width(8.dp)) - Text("Секреты", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + Text(title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) } IconButton(onClick = onDismiss) { Icon(imageVector = Icons.Default.Close, contentDescription = "Закрыть") @@ -2034,24 +4556,59 @@ fun SecretsDialog( val isPasswordValid = passwordInput.isNotEmpty() && passwordInput.matches(Regex("^[a-zA-Z0-9_.!?:#/-]+$")) - OutlinedTextField( - value = passwordInput, - onValueChange = { passwordInput = it.filter { c -> !c.isWhitespace() } }, - label = { Text("Заданный пароль туннеля") }, - placeholder = { Text("Придумайте надежный пароль") }, - singleLine = true, - isError = passwordInput.isNotEmpty() && !isPasswordValid, - supportingText = if (passwordInput.isNotEmpty() && !isPasswordValid) { - { Text("Разрешены только буквы, цифры и знаки . ! ? : # - _ /", color = MaterialTheme.colorScheme.error) } - } else null, - visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(), - modifier = Modifier - .fillMaxWidth() - .onFocusChanged { passwordFocused = it.isFocused }, - shape = RoundedCornerShape(16.dp), - ) + val passwordInvalid = passwordInput.isNotEmpty() && !isPasswordValid + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + OutlinedTextField( + value = passwordInput, + onValueChange = { passwordInput = it.filter { c -> !c.isWhitespace() } }, + label = { Text(passwordLabel) }, + placeholder = { Text(passwordPlaceholder) }, + singleLine = true, + isError = passwordInvalid, + visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(), + modifier = Modifier + .fillMaxWidth() + .onFocusChanged { passwordFocused = it.isFocused }, + shape = RoundedCornerShape(16.dp), + ) + if (passwordInvalid) { + FullWidthFieldMessage( + text = "Разрешены только буквы, цифры и знаки . ! ? : # - _ /", + color = MaterialTheme.colorScheme.error + ) + } + } - if (manualPortsEnabled) { + if (allowPortsSelection) { + Spacer(modifier = Modifier.height(12.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) { + Text( + "Нестандартные порты", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold + ) + Text( + "Включите, если владелец сервера выдал порты, отличающиеся от стандартных.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = portsEnabled, + onCheckedChange = { portsEnabled = it } + ) + } + } + + if (portsEnabled) { Spacer(modifier = Modifier.height(16.dp)) HorizontalDivider() Spacer(modifier = Modifier.height(8.dp)) @@ -2100,6 +4657,9 @@ fun SecretsDialog( val finalLocal = normalizePort(localPort, "9000") scope.launch { settingsStore.saveConnectionPassword(passwordInput) + if (allowPortsSelection) { + settingsStore.saveManualPortsEnabled(portsEnabled) + } settingsStore.savePorts(finalDtls.toInt(), finalWg.toInt(), finalLocal.toInt()) onSaved(finalDtls, finalWg, finalLocal) onDismiss() diff --git a/app/src/main/java/com/wdtt/plus/ui/StableSegmentedButtonIcon.kt b/app/src/main/java/com/wdtt/plus/ui/StableSegmentedButtonIcon.kt new file mode 100644 index 0000000..007fe44 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/StableSegmentedButtonIcon.kt @@ -0,0 +1,35 @@ +package com.wdtt.plus.ui + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp + +@Composable +internal fun StableSegmentedButtonIcon(selected: Boolean) { + Box( + modifier = Modifier.size(18.dp), + contentAlignment = Alignment.Center + ) { + AnimatedVisibility( + visible = selected, + enter = fadeIn(tween(120)), + exit = fadeOut(tween(90)) + ) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + } + } +} 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 8408f32..23f8b34 100644 --- a/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt +++ b/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt @@ -64,6 +64,7 @@ import com.journeyapps.barcodescanner.ScanOptions import com.wdtt.plus.SettingsStore import com.wdtt.plus.TransferFiles import com.wdtt.plus.WdttTransferCodec +import com.wdtt.plus.WdttDocument import com.wdtt.plus.QrCaptureActivity import com.wdtt.plus.vpnProfileDisplayName import kotlinx.coroutines.Dispatchers @@ -112,7 +113,7 @@ fun TransferCenterDialog( onIncomingContent(text) } } - val fileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> + val fileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> if (uri != null) runCatchingUi { val text = withContext(Dispatchers.IO) { TransferFiles.readText(context, uri) } onIncomingContent(text) @@ -129,6 +130,12 @@ fun TransferCenterDialog( verticalArrangement = Arrangement.spacedBy(12.dp) ) { Box(modifier = Modifier.fillMaxWidth()) { + Text( + "Получение/Передача", + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + modifier = Modifier.align(androidx.compose.ui.Alignment.CenterStart), + ) IconButton( onClick = onDismiss, enabled = !busy, @@ -137,7 +144,14 @@ fun TransferCenterDialog( Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp)) } } - Text("Получение VPN", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text("Получить профиль", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text( + "Добавьте профиль через камеру, изображение или файл. " + + "Если сервис выдал обновление, приложение применит его " + + "к связанному профилю.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) FlowRow( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), @@ -154,11 +168,13 @@ fun TransferCenterDialog( ) } TransferButton("Галерея", Icons.Default.Image, busy) { galleryLauncher.launch("image/*") } - TransferButton("Файл", Icons.Default.FileOpen, busy) { fileLauncher.launch("*/*") } + TransferButton("Файл", Icons.Default.FileOpen, busy) { + fileLauncher.launch(WdttDocument.acceptedMimeTypes()) + } } HorizontalDivider() - Text("Передача $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text("Передать $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) Text( "Ссылка содержит пароль подключения и VK-хеши. Передавайте её только тому, кому доверяете.", style = MaterialTheme.typography.bodySmall, @@ -185,9 +201,15 @@ fun TransferCenterDialog( runCatchingUi { val link = settingsStore.connectionLinkForProfile(activeProfile) val uri = withContext(Dispatchers.IO) { - TransferFiles.writeTransferText(context, "WDTT-Plus-${activeProfileLabel.safeTransferFileName()}.wdtt", link) + TransferFiles.writeTransferText( + context, + WdttDocument.fileName( + "WDTT-Plus-${activeProfileLabel.safeTransferFileName()}" + ), + link + ) } - shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") + shareUri(context, uri, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus") } } } @@ -253,7 +275,12 @@ fun TransferCenterDialog( val uri = withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-admin-$stamp.wdtt-backup", encrypted) } - shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать настройки WDTT Plus") + shareUri( + context, + uri, + WdttDocument.LEGACY_TRANSFER_MIME_TYPE, + "Передать настройки WDTT Plus" + ) } } } @@ -279,9 +306,10 @@ fun TransferCenterDialog( onSave = { scope.launch { val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()) + val fileName = "WDTT-Plus-QR-${title.safeQrFileName()}-$stamp.png" runCatching { withContext(Dispatchers.IO) { - TransferFiles.saveQrToGallery(context, "WDTT-Plus-QR-$stamp.png", bitmap) + TransferFiles.saveQrToGallery(context, fileName, bitmap) } }.onSuccess { Toast.makeText(context, "QR-код сохранён в галерею.", Toast.LENGTH_SHORT).show() diff --git a/app/src/main/java/com/wdtt/plus/ui/VkClientSettingsDialog.kt b/app/src/main/java/com/wdtt/plus/ui/VkClientSettingsDialog.kt new file mode 100644 index 0000000..1b61f3a --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/VkClientSettingsDialog.kt @@ -0,0 +1,940 @@ +package com.wdtt.plus.ui + +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import android.widget.Toast +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.HelpOutline +import androidx.compose.material.icons.filled.Cancel +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.VpnKey +import androidx.compose.material.icons.filled.WarningAmber +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.wdtt.plus.BUILT_IN_VK_CLIENT_IDS +import com.wdtt.plus.SettingsStore +import com.wdtt.plus.TunnelManager +import com.wdtt.plus.isValidVkClientId +import com.wdtt.plus.normalizeVkClientId +import com.wdtt.plus.normalizeVkClientSecret +import java.security.MessageDigest +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.json.JSONObject +import kotlin.math.ceil +import kotlin.math.max + +private const val VK_CLIENT_ID_PROBE_VERSION = 3 +internal const val VK_CLIENT_ID_PROBE_COOLDOWN_MS = 10_000L +private const val VK_CLIENT_ID_PROBE_CHECKED_AT = "_checked_at" +private const val VK_ID_CABINET_URL = "https://id.vk.ru/about/business/go/" + +internal enum class VkClientIdProbeStatus { + LegacyCompatible, + LegacyRejected, + CheckFailed +} + +internal data class VkClientIdProbeCache( + val results: Map, + val checkedAt: Long +) + +internal fun vkClientIdProbeCooldownRemainingMillis(now: Long, lastStartedAt: Long): Long { + if (lastStartedAt <= 0L) return 0L + val elapsed = (now - lastStartedAt).coerceAtLeast(0L) + return (VK_CLIENT_ID_PROBE_COOLDOWN_MS - elapsed).coerceAtLeast(0L) +} + +internal fun vkClientIdAvailabilityMessage( + ids: List, + results: Map +): String { + val cleanIds = ids.map(String::trim).filter(String::isNotEmpty).distinct() + val available = cleanIds.filter { results[it] == VkClientIdProbeStatus.LegacyCompatible } + val rejected = cleanIds.filter { results[it] == VkClientIdProbeStatus.LegacyRejected } + val failed = cleanIds.filter { results[it] == VkClientIdProbeStatus.CheckFailed } + return when { + cleanIds.size == 1 && available.isNotEmpty() -> + "Client ID ${cleanIds.first()} принимается резервным способом" + cleanIds.size == 1 && rejected.isNotEmpty() -> + "Client ID ${cleanIds.first()} не принимается резервным способом" + cleanIds.size == 1 -> + "Не удалось проверить Client ID ${cleanIds.first()}: сеть или временная ошибка VK" + rejected.isEmpty() && failed.isEmpty() -> "Все встроенные Client ID доступны для резервного способа" + else -> buildList { + if (available.isNotEmpty()) add("Доступны: ${available.joinToString(", ")}") + if (rejected.isNotEmpty()) add("Не принимаются: ${rejected.joinToString(", ")}") + if (failed.isNotEmpty()) add("Не удалось проверить: ${failed.joinToString(", ")}") + }.joinToString(". ", postfix = ".") + } +} + +internal fun vkClientIdsForAutomaticProbe( + customCredentialsEnabled: Boolean, + customClientId: String, + customClientSecret: String +): List = if (customCredentialsEnabled) { + customClientId.trim().takeIf(::isValidVkClientId) + ?.takeIf { customClientSecret.trim().isNotEmpty() } + ?.let(::listOf) + .orEmpty() +} else { + BUILT_IN_VK_CLIENT_IDS +} + +private object VkClientIdProbeRateLimiter { + private var lastStartedAt = 0L + + @Synchronized + fun acquire(now: Long, persistedCheckedAt: Long): Long { + val effectiveLastStartedAt = max(lastStartedAt, persistedCheckedAt) + val remaining = vkClientIdProbeCooldownRemainingMillis(now, effectiveLastStartedAt) + if (remaining == 0L) lastStartedAt = now + return remaining + } +} + +@Composable +fun VkClientSettingsDialog( + settingsStore: SettingsStore, + activeClientIds: String, + onClientIdsChange: (String) -> Unit, + onDismiss: () -> Unit +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val configuration = LocalConfiguration.current + val enabledState by remember(settingsStore) { + settingsStore.customVkCredentialsEnabled.map { it as Boolean? } + }.collectAsStateWithLifecycle(initialValue = null) + val savedClientIdState by remember(settingsStore) { + settingsStore.customVkClientId.map { it as String? } + }.collectAsStateWithLifecycle(initialValue = null) + val savedClientSecretState by remember(settingsStore) { + settingsStore.customVkClientSecret.map { it as String? } + }.collectAsStateWithLifecycle(initialValue = null) + val checkResultsJsonState by remember(settingsStore) { + settingsStore.clientIdCheckResults.map { it as String? } + }.collectAsStateWithLifecycle(initialValue = null) + val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle() + + val enabled = enabledState == true + val savedClientId = savedClientIdState.orEmpty() + val savedClientSecret = savedClientSecretState.orEmpty() + val settingsReady = enabledState != null && savedClientIdState != null && + savedClientSecretState != null && checkResultsJsonState != null + val probeCache = remember(checkResultsJsonState) { + parseVkClientIdCheckResults(checkResultsJsonState.orEmpty()) + } + val checkResults = probeCache.results + val builtInSelection = remember(activeClientIds) { + activeClientIds.split(',').map { it.trim() }.filter { it.isNotEmpty() } + } + + var clientIdInput by rememberSaveable { mutableStateOf("") } + var clientSecretInput by rememberSaveable { mutableStateOf("") } + var inputsInitialized by rememberSaveable { mutableStateOf(false) } + var secretFocused by remember { mutableStateOf(false) } + var checkingIds by remember { mutableStateOf>(emptySet()) } + var showHelp by rememberSaveable { mutableStateOf(false) } + + LaunchedEffect(settingsReady) { + if (settingsReady && !inputsInitialized) { + clientIdInput = savedClientId + clientSecretInput = savedClientSecret + inputsInitialized = true + } + } + + val normalizedClientId = normalizeVkClientId(clientIdInput) + val normalizedClientSecret = normalizeVkClientSecret(clientSecretInput) + val customInputComplete = isValidVkClientId(normalizedClientId) && normalizedClientSecret.isNotBlank() + val hasUnsavedChanges = inputsInitialized && ( + normalizedClientId != savedClientId || normalizedClientSecret != savedClientSecret + ) + + fun checkIds(ids: List, manual: Boolean) { + val cleanIds = ids.map(String::trim).filter(::isValidVkClientId).distinct() + if (cleanIds.isEmpty()) return + if (checkingIds.isNotEmpty()) { + if (manual) Toast.makeText(context, "Проверка уже выполняется", Toast.LENGTH_SHORT).show() + return + } + val startedAt = System.currentTimeMillis() + val cooldownRemaining = VkClientIdProbeRateLimiter.acquire(startedAt, probeCache.checkedAt) + if (cooldownRemaining > 0L) { + if (manual) { + val seconds = ceil(cooldownRemaining / 1_000.0).toInt().coerceAtLeast(1) + Toast.makeText( + context, + "Повторная проверка будет доступна через $seconds с", + Toast.LENGTH_SHORT + ).show() + } + return + } + checkingIds = cleanIds.toSet() + scope.launch { + try { + val checkedNow = withContext(Dispatchers.IO) { + buildMap { + cleanIds.forEach { id -> + put(id, checkVkClientId(id)) + } + } + } + val freshResults = checkResults.toMutableMap().apply { putAll(checkedNow) } + settingsStore.saveClientIdCheckResults( + encodeVkClientIdCheckResults(freshResults, startedAt) + ) + Toast.makeText( + context, + vkClientIdAvailabilityMessage(cleanIds, checkedNow), + Toast.LENGTH_LONG + ).show() + } finally { + checkingIds = emptySet() + } + } + } + + LaunchedEffect(settingsReady, enabled, savedClientId, savedClientSecret) { + if (settingsReady) { + checkIds( + vkClientIdsForAutomaticProbe(enabled, savedClientId, savedClientSecret), + manual = false + ) + } + } + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .fillMaxHeight(0.9f) + .heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)), + shape = RoundedCornerShape(30.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 8.dp, + shadowElevation = 8.dp + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(18.dp), + verticalArrangement = Arrangement.spacedBy(14.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.primaryContainer + ) { + Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) { + Icon(Icons.Default.VpnKey, contentDescription = null, modifier = Modifier.size(25.dp)) + } + } + Column(modifier = Modifier.weight(1f)) { + Text( + "Клиенты VK", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + Text( + "Настройка для текущего VPN-профиля", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + + if (!settingsReady) { + Box( + modifier = Modifier.fillMaxWidth().height(180.dp), + contentAlignment = Alignment.Center + ) { + CircularProgressIndicator() + } + } else { + if (tunnelRunning) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.errorContainer + ) { + Text( + "VPN сейчас работает. Чтобы изменить резервные Client ID, сначала выключите VPN. Проверка доступности остаётся доступной.", + modifier = Modifier.padding(14.dp), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + fontWeight = FontWeight.SemiBold + ) + } + } + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f) + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text("Собственные резервные реквизиты", fontWeight = FontWeight.SemiBold) + Text( + if (enabled) { + "После быстрого VKCalls сначала пробуется ваш Client ID." + } else { + "После быстрого VKCalls используются встроенные Client ID." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = enabled, + enabled = !tunnelRunning, + onCheckedChange = { checked -> + scope.launch { settingsStore.saveCustomVkCredentialsEnabled(checked) } + } + ) + } + } + + if (enabled) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(modifier = Modifier.weight(1f)) { + Text("Резервные реквизиты приложения VK", fontWeight = FontWeight.Bold) + Text( + "Оба поля обязательны", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + IconButton(onClick = { showHelp = true }) { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Как получить Client ID и secret" + ) + } + } + + OutlinedTextField( + value = clientIdInput, + onValueChange = { clientIdInput = normalizeVkClientId(it) }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Client ID") }, + supportingText = { Text("ID приложения из кабинета VK ID") }, + enabled = !tunnelRunning, + singleLine = true, + keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( + keyboardType = KeyboardType.Number + ) + ) + + OutlinedTextField( + value = clientSecretInput, + onValueChange = { clientSecretInput = it.take(512) }, + modifier = Modifier + .fillMaxWidth() + .onFocusChanged { secretFocused = it.isFocused }, + label = { Text("Client secret") }, + supportingText = { + Text("Защищённый ключ скрывается после выхода из поля") + }, + enabled = !tunnelRunning, + singleLine = true, + keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( + keyboardType = KeyboardType.Password + ), + visualTransformation = if (secretFocused) { + VisualTransformation.None + } else { + PasswordVisualTransformation() + } + ) + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.45f) + ) { + Text( + "Защищённый ключ сохраняется в зашифрованном виде через Android Keystore и не добавляется в журналы.", + modifier = Modifier.padding(13.dp), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer + ) + } + + if (hasUnsavedChanges) { + Text( + "Есть несохранённые изменения", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.tertiary, + fontWeight = FontWeight.SemiBold + ) + } + + Button( + onClick = { + scope.launch { + settingsStore.saveCustomVkCredentials( + normalizedClientId, + normalizedClientSecret + ) + clientIdInput = normalizedClientId + clientSecretInput = normalizedClientSecret + Toast.makeText(context, "Реквизиты сохранены", Toast.LENGTH_SHORT).show() + } + }, + enabled = !tunnelRunning && customInputComplete && hasUnsavedChanges, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), + shape = RoundedCornerShape(16.dp) + ) { + Text("Сохранить") + } + + val customProbeResult = checkResults[normalizedClientId] + OutlinedButton( + onClick = { checkIds(listOf(normalizedClientId), manual = true) }, + enabled = isValidVkClientId(normalizedClientId) && checkingIds.isEmpty(), + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), + shape = RoundedCornerShape(16.dp) + ) { + Text(if (normalizedClientId in checkingIds) "Проверка…" else "Проверить Client ID") + } + + if (customProbeResult != null && normalizedClientId !in checkingIds) { + val statusColor = when (customProbeResult) { + VkClientIdProbeStatus.LegacyCompatible -> MaterialTheme.colorScheme.primaryContainer + VkClientIdProbeStatus.LegacyRejected -> MaterialTheme.colorScheme.errorContainer + VkClientIdProbeStatus.CheckFailed -> MaterialTheme.colorScheme.tertiaryContainer + } + val statusContentColor = when (customProbeResult) { + VkClientIdProbeStatus.LegacyCompatible -> MaterialTheme.colorScheme.onPrimaryContainer + VkClientIdProbeStatus.LegacyRejected -> MaterialTheme.colorScheme.onErrorContainer + VkClientIdProbeStatus.CheckFailed -> MaterialTheme.colorScheme.onTertiaryContainer + } + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = statusColor + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(13.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + Icon( + imageVector = when (customProbeResult) { + VkClientIdProbeStatus.LegacyCompatible -> Icons.Default.CheckCircle + VkClientIdProbeStatus.LegacyRejected -> Icons.Default.Cancel + VkClientIdProbeStatus.CheckFailed -> Icons.Default.WarningAmber + }, + contentDescription = null, + tint = statusContentColor + ) + Text( + text = when (customProbeResult) { + VkClientIdProbeStatus.LegacyCompatible -> + "Client ID принимается резервным способом" + VkClientIdProbeStatus.LegacyRejected -> + "Client ID не принимается резервным способом" + VkClientIdProbeStatus.CheckFailed -> + "Проверку выполнить не удалось: сеть или временная ошибка VK" + }, + style = MaterialTheme.typography.bodySmall, + color = statusContentColor, + fontWeight = FontWeight.SemiBold + ) + } + } + } + + Text( + "Сохранённый собственный Client ID проверяется автоматически при входе. Это второй вариант после VKCalls. Такая проверка подтверждает только приём ID старым способом VK; получение TURN-данных окончательно проверяется при подключении.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Text("Встроенный резерв", fontWeight = FontWeight.Bold) + Text( + if (enabled) { + "Используется, если VKCalls и собственные реквизиты не сработали. Встроенный ID можно проверить нажатием на строку." + } else { + "Используется, если VKCalls не сработал. Проверка запускается автоматически при входе; нажмите на строку для повтора." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + BUILT_IN_VK_CLIENT_IDS.forEach { id -> + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.42f), + onClick = { checkIds(listOf(id), manual = true) } + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox( + checked = id in builtInSelection, + enabled = !tunnelRunning, + onCheckedChange = { checked -> + val updated = if (checked) { + (builtInSelection + id).distinct() + } else { + builtInSelection - id + } + if (updated.isNotEmpty()) { + onClientIdsChange(updated.joinToString(",")) + } else { + Toast.makeText( + context, + "Нельзя отключить все Client ID: без них программа перестанет работать", + Toast.LENGTH_LONG + ).show() + } + } + ) + Column(modifier = Modifier.weight(1f)) { + Text(id, fontWeight = FontWeight.SemiBold) + Text( + if (id in builtInSelection) "Выбран для резерва" else "Отключён", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Box( + modifier = Modifier.size(36.dp), + contentAlignment = Alignment.Center + ) { + when { + id in checkingIds -> CircularProgressIndicator( + modifier = Modifier.size(22.dp), + strokeWidth = 2.5.dp + ) + checkResults[id] == VkClientIdProbeStatus.LegacyCompatible -> Icon( + Icons.Default.CheckCircle, + contentDescription = "Client ID доступен для резервного способа", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(24.dp) + ) + checkResults[id] == VkClientIdProbeStatus.LegacyRejected -> Icon( + Icons.Default.Cancel, + contentDescription = "Client ID недоступен для резервного способа", + tint = MaterialTheme.colorScheme.error, + modifier = Modifier.size(24.dp) + ) + checkResults[id] == VkClientIdProbeStatus.CheckFailed -> Icon( + Icons.Default.WarningAmber, + contentDescription = "Не удалось проверить Client ID", + tint = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.size(24.dp) + ) + else -> Text( + "—", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontWeight = FontWeight.Bold + ) + } + } + } + } + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f)) + Text( + if (enabled) { + "Порядок подключения: быстрый VKCalls без капчи → собственные реквизиты → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически." + } else { + "Порядок подключения: быстрый VKCalls без капчи → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } + } + + if (showHelp) { + VkClientCredentialsHelpDialog(onDismiss = { showHelp = false }) + } +} + +@Composable +private fun VkClientCredentialsHelpDialog(onDismiss: () -> Unit) { + val context = LocalContext.current + val clipboard = LocalClipboardManager.current + val configuration = LocalConfiguration.current + val packageName = context.packageName + val signingSha1 = remember(context) { appSigningSha1(context) } + + fun copy(value: String, message: String) { + clipboard.setText(AnnotatedString(value)) + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + } + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .fillMaxHeight(0.9f) + .heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)), + shape = RoundedCornerShape(30.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 10.dp, + shadowElevation = 10.dp + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(18.dp), + verticalArrangement = Arrangement.spacedBy(14.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + "Резервные реквизиты VK", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + Text( + "Резервный провайдер через кабинет VK ID", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.65f) + ) { + Text( + "Собственные реквизиты относятся только к резервному legacy-провайдеру. Для основного быстрого VKCalls они не нужны. Понадобятся ID приложения и Защищённый ключ из одного приложения VK; сервисный ключ доступа не подходит.", + modifier = Modifier.padding(14.dp), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onPrimaryContainer + ) + } + + HelpStep( + number = 1, + title = "Откройте кабинет VK ID", + text = "Войдите в аккаунт владельца приложения, откройте раздел «Мои приложения» и нажмите «Добавить приложение»." + ) + Button( + onClick = { + runCatching { + context.startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse(VK_ID_CABINET_URL))) + } + }, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp) + ) { + Text("Открыть кабинет VK ID") + } + + HelpStep( + number = 2, + title = "Создайте Android-приложение", + text = "Укажите понятное название, выберите платформу Android, затем заполните имя пакета и SHA-1 подписи установленного APK." + ) + CopyValueCard( + label = "Название пакета", + value = packageName, + onCopy = { copy(packageName, "Название пакета скопировано") } + ) + CopyValueCard( + label = "SHA-1 подписи этого APK", + value = signingSha1.ifBlank { "Не удалось определить" }, + onCopy = signingSha1.takeIf(String::isNotBlank)?.let { sha1 -> + { copy(sha1, "SHA-1 скопирован") } + } + ) + + HelpStep( + number = 3, + title = "Скопируйте реквизиты", + text = "После создания откройте карточку приложения → «Приложение» → «Информация о приложении». Поле «ID приложения» вставьте как Client ID, а поле «Защищённый ключ» — как Client secret." + ) + + HelpStep( + number = 4, + title = "Сохраните и проверьте", + text = "Вернитесь в WDTT Plus, заполните оба поля, нажмите «Сохранить», затем «Проверить Client ID». Для полного доступа к ключам VK может попросить подтвердить профиль бизнеса." + ) + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.55f), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.25f)) + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(6.dp) + ) { + Text("Важно", fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onErrorContainer) + Text( + "Не публикуйте Защищённый ключ, не отправляйте его в чат и не добавляйте в GitHub. Новое приложение VK ID может не иметь прав старой TURN-цепочки: статус проверки показывает распознавание legacy OAuth, а окончательный результат виден только при реальном подключении. При неудаче приложение продолжит через встроенный резерв.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer + ) + } + } + + Button( + onClick = onDismiss, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), + shape = RoundedCornerShape(16.dp) + ) { + Text("Понятно") + } + } + } + } + } +} + +@Composable +private fun HelpStep(number: Int, title: String, text: String) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.Top + ) { + Surface(shape = CircleShape, color = MaterialTheme.colorScheme.secondaryContainer) { + Box(modifier = Modifier.size(30.dp), contentAlignment = Alignment.Center) { + Text(number.toString(), fontWeight = FontWeight.Bold) + } + } + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(title, fontWeight = FontWeight.Bold) + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 18.sp + ) + } + } +} + +@Composable +private fun CopyValueCard(label: String, value: String, onCopy: (() -> Unit)?) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f) + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 4.dp, top = 8.dp, bottom = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(value, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium) + } + IconButton(onClick = { onCopy?.invoke() }, enabled = onCopy != null) { + Icon(Icons.Default.ContentCopy, contentDescription = "Копировать") + } + } + } +} + +internal fun parseVkClientIdCheckResults(raw: String): VkClientIdProbeCache = runCatching { + val json = JSONObject(raw) + if (json.optInt("_probe_version") != VK_CLIENT_ID_PROBE_VERSION) { + return@runCatching VkClientIdProbeCache(emptyMap(), 0L) + } + val results = buildMap { + val keys = json.keys() + while (keys.hasNext()) { + val key = keys.next() + if (key != "_probe_version" && key != VK_CLIENT_ID_PROBE_CHECKED_AT) { + runCatching { VkClientIdProbeStatus.valueOf(json.optString(key)) } + .getOrNull() + ?.let { put(key, it) } + } + } + } + VkClientIdProbeCache( + results = results, + checkedAt = json.optLong(VK_CLIENT_ID_PROBE_CHECKED_AT, 0L).coerceAtLeast(0L) + ) +}.getOrDefault(VkClientIdProbeCache(emptyMap(), 0L)) + +private fun encodeVkClientIdCheckResults( + results: Map, + checkedAt: Long +): String = + JSONObject().apply { + put("_probe_version", VK_CLIENT_ID_PROBE_VERSION) + put(VK_CLIENT_ID_PROBE_CHECKED_AT, checkedAt.coerceAtLeast(0L)) + results.forEach { (id, result) -> put(id, result.name) } + }.toString() + +internal val vkLegacyOAuthProbeEndpoints = listOf( + "https://oauth.vk.ru/authorize", + "https://oauth.vk.com/authorize" +) + +private fun checkVkClientId(appId: String): VkClientIdProbeStatus { + val cleanAppId = appId.trim() + if (!isValidVkClientId(cleanAppId)) return VkClientIdProbeStatus.LegacyRejected + var legacyRejected = false + for (endpoint in vkLegacyOAuthProbeEndpoints) { + var connection: java.net.HttpURLConnection? = null + try { + val url = java.net.URL( + "$endpoint?client_id=$cleanAppId&display=mobile&response_type=token" + ) + connection = url.openConnection() as java.net.HttpURLConnection + connection.requestMethod = "GET" + connection.connectTimeout = 5_000 + connection.readTimeout = 5_000 + val responseCode = connection.responseCode + if (isVkLegacyClientIdProbeSuccessful(responseCode, connection.contentType.orEmpty())) { + return VkClientIdProbeStatus.LegacyCompatible + } + if (isVkLegacyClientIdProbeRejected(responseCode)) { + legacyRejected = true + } + } catch (_: Exception) { + // Try the compatibility domain below. + } finally { + connection?.disconnect() + } + } + return if (legacyRejected) { + VkClientIdProbeStatus.LegacyRejected + } else { + VkClientIdProbeStatus.CheckFailed + } +} + +internal fun isVkLegacyClientIdProbeSuccessful(statusCode: Int, contentType: String): Boolean = + statusCode in 200..299 && contentType.startsWith("text/html", ignoreCase = true) + +internal fun isVkLegacyClientIdProbeRejected(statusCode: Int): Boolean = + statusCode in 400..499 && statusCode != 408 && statusCode != 429 + +@Suppress("DEPRECATION") +private fun appSigningSha1(context: Context): String = runCatching { + val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNING_CERTIFICATES) + } else { + context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES) + } + val signature = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + val signingInfo = packageInfo.signingInfo ?: return@runCatching "" + if (signingInfo.hasMultipleSigners()) { + signingInfo.apkContentsSigners.firstOrNull() + } else { + signingInfo.signingCertificateHistory.firstOrNull() + } + } else { + packageInfo.signatures?.firstOrNull() + } ?: return@runCatching "" + MessageDigest.getInstance("SHA-1") + .digest(signature.toByteArray()) + .joinToString(":") { byte -> "%02X".format(byte) } +}.getOrDefault("") diff --git a/app/src/test/java/com/wdtt/plus/AppUpdateTest.kt b/app/src/test/java/com/wdtt/plus/AppUpdateTest.kt index 3a4529f..c7c83d8 100644 --- a/app/src/test/java/com/wdtt/plus/AppUpdateTest.kt +++ b/app/src/test/java/com/wdtt/plus/AppUpdateTest.kt @@ -3,6 +3,7 @@ package com.wdtt.plus import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -90,6 +91,44 @@ class AppUpdateTest { ) } + @Test + fun updateAssetRequiresOfficialUrlSizeAndDigest() { + val safe = AppReleaseAsset( + name = "WDTT-Plus-v12-universal-release.apk", + downloadUrl = ( + "https://github.com/Ivan4537/WDTT-Plus/releases/download/" + + "v12/WDTT-Plus-v12-universal-release.apk" + ), + sizeBytes = 42L, + digest = "sha256:${"a".repeat(64)}", + ) + val release = AppReleaseInfo( + versionTag = "v12", + releaseUrl = "https://github.com/Ivan4537/WDTT-Plus/releases/tag/v12", + source = RemoteVersionSource.Release, + assets = listOf(safe), + ) + + assertEquals(safe, selectUpdateApkAsset(release)) + assertNull( + selectUpdateApkAsset( + release.copy(assets = listOf(safe.copy(digest = ""))), + ), + ) + assertFalse( + isTrustedUpdateDownloadUrl( + "https://github.com/other/project/releases/download/v12/app.apk", + initialRequest = true, + ), + ) + assertTrue( + isTrustedUpdateDownloadUrl( + "https://release-assets.githubusercontent.com/opaque", + initialRequest = false, + ), + ) + } + private fun releaseWithHashes(vararg hashes: String): AppReleaseInfo { return AppReleaseInfo( versionTag = "v7", diff --git a/app/src/test/java/com/wdtt/plus/BoundedInputTest.kt b/app/src/test/java/com/wdtt/plus/BoundedInputTest.kt new file mode 100644 index 0000000..05b7faa --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/BoundedInputTest.kt @@ -0,0 +1,20 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Test + +class BoundedInputTest { + @Test + fun `bounded reader stops before accepting an oversized response`() { + assertEquals( + "данные", + "данные".byteInputStream().readUtf8TextLimited(32), + ) + + runCatching { + "x".repeat(33).byteInputStream().readUtf8TextLimited(32) + }.onSuccess { + throw AssertionError("Oversized response must be rejected") + } + } +} diff --git a/app/src/test/java/com/wdtt/plus/ClientNetworkDiagnosticsTest.kt b/app/src/test/java/com/wdtt/plus/ClientNetworkDiagnosticsTest.kt new file mode 100644 index 0000000..86f02f3 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ClientNetworkDiagnosticsTest.kt @@ -0,0 +1,132 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ClientNetworkDiagnosticsTest { + @Test + fun vkDiagnosticsTreatModernVkCallsHostsAsPrimaryAndLegacyHostsAsReserve() { + assertTrue("api.vk.me" in primaryVkDiagnosticHosts) + assertTrue("calls.okcdn.ru" in primaryVkDiagnosticHosts) + assertTrue("vk.ru" in reserveVkDiagnosticHosts) + assertTrue("login.vk.ru" in reserveVkDiagnosticHosts) + assertTrue("api.vk.ru" in reserveVkDiagnosticHosts) + assertTrue("id.vk.ru" in reserveVkDiagnosticHosts) + assertTrue("static.vk.ru" in reserveVkDiagnosticHosts) + assertTrue("vk.com" in reserveVkDiagnosticHosts) + assertTrue(primaryVkDiagnosticHosts.intersect(reserveVkDiagnosticHosts).isEmpty()) + assertEquals("api.vk.me", clientDnsProbeHost) + } + + @Test + fun clientDnsPath_usesSystemFallbackWithoutReportingFailure() { + val result = assessClientDnsPath(emptySet(), systemPrimaryApiWorks = true) + + assertEquals("прямой DNS недоступен, используется системный DNS", result.status) + assertEquals(DeviceCheckSeverity.Info, result.severity) + assertEquals(null, result.action) + } + + @Test + fun clientDnsPath_acceptsSecondaryUdpRoute() { + val result = assessClientDnsPath(setOf("77.88.8.1 UDP"), systemPrimaryApiWorks = false) + + assertEquals("резервный UDP DNS доступен", result.status) + assertEquals(DeviceCheckSeverity.Info, result.severity) + assertEquals(null, result.action) + } + + @Test + fun clientDnsPath_prefersSecondaryUdpOverPrimaryTcp() { + val result = assessClientDnsPath( + setOf("77.88.8.8 TCP", "77.88.8.1 UDP"), + systemPrimaryApiWorks = true + ) + + assertEquals("резервный UDP DNS доступен", result.status) + assertEquals(DeviceCheckSeverity.Info, result.severity) + } + + @Test + fun clientDnsPath_acceptsTcpFallback() { + val result = assessClientDnsPath(setOf("77.88.8.8 TCP"), systemPrimaryApiWorks = false) + + assertEquals("UDP DNS недоступен, TCP отвечает", result.status) + assertEquals(DeviceCheckSeverity.Info, result.severity) + assertEquals(null, result.action) + } + + @Test + fun clientDnsPath_keepsPrimaryDirectRouteAheadOfSystemDns() { + val result = assessClientDnsPath(setOf("77.88.8.8 UDP"), systemPrimaryApiWorks = true) + + assertEquals("основной UDP DNS доступен", result.status) + assertEquals(DeviceCheckSeverity.Ok, result.severity) + assertEquals(null, result.action) + } + + @Test + fun clientDnsPath_reportsFailureOnlyWhenEveryRouteIsUnavailable() { + val result = assessClientDnsPath(emptySet(), systemPrimaryApiWorks = false) + + assertEquals("DNS до VK недоступен", result.status) + assertEquals(DeviceCheckSeverity.Error, result.severity) + assertEquals(DeviceCheckAction.NetworkSettings, result.action) + } + + @Test + fun dnsQuery_containsExpectedHeaderNameAndARecordType() { + val query = buildDnsQuery(clientDnsProbeHost, 0x1234) + + assertEquals(0x12, query[0].toInt() and 0xff) + assertEquals(0x34, query[1].toInt() and 0xff) + assertEquals(1, unsignedShort(query, 4)) + assertTrue(query.copyOfRange(12, query.size).containsSubsequence(byteArrayOf(3, 'a'.code.toByte(), 'p'.code.toByte(), 'i'.code.toByte()))) + assertEquals(1, unsignedShort(query, query.size - 4)) + assertEquals(1, unsignedShort(query, query.size - 2)) + } + + @Test + fun dnsResponse_parsesAnswerCountAndFlags() { + val response = byteArrayOf( + 0x12, 0x34, + 0x83.toByte(), 0x80.toByte(), + 0x00, 0x01, + 0x00, 0x02, + 0x00, 0x00, + 0x00, 0x00 + ) + + val status = parseDnsResponse(response, 0x1234) + + assertEquals(0, status.responseCode) + assertEquals(2, status.answerCount) + assertTrue(status.truncated) + } + + @Test(expected = IllegalArgumentException::class) + fun dnsResponse_rejectsDifferentTransaction() { + parseDnsResponse( + byteArrayOf( + 0x55, 0x66, + 0x81.toByte(), 0x80.toByte(), + 0x00, 0x01, + 0x00, 0x01, + 0x00, 0x00, + 0x00, 0x00 + ), + 0x1234 + ) + } + + private fun unsignedShort(bytes: ByteArray, offset: Int): Int = + ((bytes[offset].toInt() and 0xff) shl 8) or (bytes[offset + 1].toInt() and 0xff) + + private fun ByteArray.containsSubsequence(expected: ByteArray): Boolean { + if (expected.isEmpty() || expected.size > size) return false + return indices.any { start -> + start + expected.size <= size && expected.indices.all { index -> this[start + index] == expected[index] } + } + } +} diff --git a/app/src/test/java/com/wdtt/plus/ClientTransferCodecTest.kt b/app/src/test/java/com/wdtt/plus/ClientTransferCodecTest.kt index db4898d..764a340 100644 --- a/app/src/test/java/com/wdtt/plus/ClientTransferCodecTest.kt +++ b/app/src/test/java/com/wdtt/plus/ClientTransferCodecTest.kt @@ -27,6 +27,20 @@ class ClientTransferCodecTest { assertFalse(encoded.contains("host")) } + @Test + fun clientTransfer_roundTripsWithoutVkHashes() { + val source = ClientTransferPayload( + password = "ABCDEFGHJKLMNPQR", + label = "Без хеша", + vkHash = "", + expiresAt = 0, + deactivated = false, + createdAt = 12345 + ) + + assertEquals(source, ClientTransferCodec.decode(ClientTransferCodec.encode(source))) + } + @Test(expected = IllegalArgumentException::class) fun clientTransfer_rejectsUnsafePassword() { ClientTransferCodec.decode( diff --git a/app/src/test/java/com/wdtt/plus/DeviceIdentityTest.kt b/app/src/test/java/com/wdtt/plus/DeviceIdentityTest.kt new file mode 100644 index 0000000..50a9842 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/DeviceIdentityTest.kt @@ -0,0 +1,52 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class DeviceIdentityTest { + @Test + fun existingIdentityIsPreservedForActiveInstallations() { + val existing = "android-11111111-2222-3333-4444-555555555555" + + val resolved = DeviceIdentity.resolve( + existing = existing, + platformId = "abcdef0123456789", + generatedId = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", + ) + + assertEquals(existing, resolved) + } + + @Test + fun freshInstallationUsesStablePlatformIdentity() { + val resolved = DeviceIdentity.resolve( + existing = null, + platformId = "abcdef0123456789", + generatedId = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", + ) + + assertEquals("abcdef0123456789", resolved) + } + + @Test + fun missingPlatformIdentityUsesValidGeneratedFallback() { + val fallback = "android-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" + + val resolved = DeviceIdentity.resolve( + existing = "broken", + platformId = null, + generatedId = fallback, + ) + + assertEquals(fallback, resolved) + } + + @Test + fun knownSharedLegacyAndroidIdentityIsRejected() { + assertFalse(DeviceIdentity.valid("9774d56d682e549c")) + assertFalse(DeviceIdentity.valid("unknown")) + assertTrue(DeviceIdentity.valid("abcdef0123456789")) + } +} diff --git a/app/src/test/java/com/wdtt/plus/LogSeverityTest.kt b/app/src/test/java/com/wdtt/plus/LogSeverityTest.kt index 95afd1f..3a5d97d 100644 --- a/app/src/test/java/com/wdtt/plus/LogSeverityTest.kt +++ b/app/src/test/java/com/wdtt/plus/LogSeverityTest.kt @@ -3,9 +3,19 @@ package com.wdtt.plus import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Test class LogSeverityTest { + @Test + fun wrapHandshakeRetryMessage_doesNotBlameThePassword() { + assertEquals( + "[WRAP] Отдельные каналы не ответили, выполняется повтор", + WRAP_HANDSHAKE_RETRY_MESSAGE + ) + assertFalse(WRAP_HANDSHAKE_RETRY_MESSAGE.contains("парол", ignoreCase = true)) + } + @Test fun repeatedTurnWorkerFailures_useOneRecoverableWarningKey() { val first = classifyRecoverableWorkerRetry( @@ -40,4 +50,11 @@ class LogSeverityTest { assertFalse(warning.isError) } + + @Test + fun serverExpiredDenialIsRecognizedBeforeLocalizedProtocolMessage() { + assertTrue(isExpiredAccessAuthFailure("FATAL_AUTH: DENIED:expired")) + assertTrue(isExpiredAccessAuthFailure("FATAL_AUTH: срок действия пароля истёк")) + assertFalse(isExpiredAccessAuthFailure("FATAL_AUTH: неверный пароль подключения")) + } } diff --git a/app/src/test/java/com/wdtt/plus/RemoteActionCatalogTest.kt b/app/src/test/java/com/wdtt/plus/RemoteActionCatalogTest.kt new file mode 100644 index 0000000..c6c219a --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/RemoteActionCatalogTest.kt @@ -0,0 +1,175 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class RemoteActionCatalogTest { + @Test + fun parse_acceptsOnlyKnownPlacementsAndExactTargets() { + val catalog = RemoteActionCatalogGateway.parse( + """ + { + "version": 1, + "actions": { + "tunnel": { + "title": "Дополнительное действие", + "message": "Продолжить во внешнем сервисе", + "label": "Открыть", + "confirmation_title": "Подтверждение", + "confirmation_message": "Первый абзац.\n\nВторой абзац.", + "confirmation_label": "Продолжить", + "progress_label": "Открываю…", + "preparing_message": "Подготавливаю...", + "stopping_message": "Останавливаю...", + "opening_message": "Открываю...", + "success_message": "Открыто.", + "cancelled_message": "Отменено.", + "failure_message": "Не удалось.", + "compact_message": "Короткий текст.", + "compact_label": "Короткая кнопка", + "compact_link_text": "Короткий", + "compact_button_visible": false, + "cancel_label": "Остановить", + "form": { + "token": "opaque.form.token_1234567890", + "submit_url": "https://example.org/actions/execute", + "title": "Введите значение", + "message": "Выберите готовое значение или укажите своё.", + "choices": [ + {"label": "Первое", "value": "opaque-choice-1"}, + {"label": "Второе", "value": "opaque-choice-2"} + ], + "input_label": "Значение", + "input_suffix": "", + "initial_value": "7", + "minimum": 2, + "maximum": 19, + "max_characters": 2, + "supporting_text": "Допустимый диапазон", + "invalid_text": "Проверьте значение", + "submit_label": "Продолжить — {value}", + "busy_label": "Подготавливаем…", + "failure_message": "Не удалось продолжить.", + "fallback_label": "Открыть страницу" + }, + "url": "https://example.org/start?opaque=1", + "fallback": "https://example.org/fallback", + "handler": "org.example.client", + "alternate_handlers": [ + "org.example.client.web", + "org.example.client.x" + ] + }, + "unknown": { + "title": "Неизвестное место", + "message": "Не должно попасть в каталог", + "label": "Открыть", + "url": "https://example.org/ignored" + } + } + } + """.trimIndent() + ) + + val action = catalog.at("tunnel")!! + assertEquals("Дополнительное действие", action.title) + assertEquals("https://example.org/start?opaque=1", action.target.primaryUrl) + assertEquals("https://example.org/fallback", action.target.fallbackUrl) + assertEquals("org.example.client", action.target.preferredHandler) + assertEquals( + listOf("org.example.client.web", "org.example.client.x"), + action.target.alternateHandlers, + ) + assertEquals( + listOf( + "org.example.client", + "org.example.client.web", + "org.example.client.x", + ), + action.target.handlerPackages(), + ) + assertEquals("Подтверждение", action.confirmationTitle) + assertEquals("Первый абзац.\n\nВторой абзац.", action.confirmationMessage) + assertEquals("Продолжить", action.confirmationLabel) + assertEquals("Открываю…", action.progressLabel) + assertEquals("Подготавливаю...", action.preparingMessage) + assertEquals("Останавливаю...", action.stoppingMessage) + assertEquals("Открываю...", action.openingMessage) + assertEquals("Открыто.", action.successMessage) + assertEquals("Отменено.", action.cancelledMessage) + assertEquals("Не удалось.", action.failureMessage) + assertEquals("Короткий текст.", action.compactMessage) + assertEquals("Короткая кнопка", action.compactLabel) + assertEquals("Короткий", action.compactLinkText) + assertEquals(false, action.compactButtonVisible) + assertEquals("Остановить", action.cancelLabel) + assertEquals("Введите значение", action.form?.title) + assertEquals("opaque-choice-2", action.form?.choices?.get(1)?.value) + assertEquals(2L, action.form?.minimum) + assertEquals(19L, action.form?.maximum) + assertNull(catalog.at("unknown")) + } + + @Test + fun parse_rejectsUnsafeOrMalformedActions() { + val catalog = RemoteActionCatalogGateway.parse( + """ + { + "version": 1, + "actions": { + "tunnel": { + "title": "Опасная ссылка", + "message": "Неподдерживаемая схема", + "label": "Открыть", + "url": "custom://private-contract" + }, + "profile": { + "title": "Неверный обработчик", + "message": "Имя пакета не прошло проверку", + "label": "Открыть", + "url": "https://example.org/start", + "handler": "not a package" + }, + "about": { + "title": "Неверные резервные обработчики", + "message": "Имя пакета не прошло проверку", + "label": "Открыть", + "url": "https://example.org/start", + "alternate_handlers": ["also not a package"] + } + } + } + """.trimIndent() + ) + + assertTrue(catalog.actions.isEmpty()) + } + + @Test + fun parse_rejectsUnknownProtocolVersion() { + val catalog = RemoteActionCatalogGateway.parse( + """{"version":2,"actions":{}}""" + ) + + assertTrue(catalog.actions.isEmpty()) + } + + @Test + fun parseExecutionTarget_acceptsOnlyExactHttpsTargets() { + val target = RemoteActionCatalogGateway.parseExecutionTarget( + """ + { + "version": 1, + "url": "https://actions.example.org/opaque", + "fallback": "https://example.org/fallback", + "handler": "" + } + """.trimIndent() + ) + + assertEquals("https://actions.example.org/opaque", target.primaryUrl) + assertEquals("https://example.org/fallback", target.fallbackUrl) + } +} diff --git a/app/src/test/java/com/wdtt/plus/TransferCodecTest.kt b/app/src/test/java/com/wdtt/plus/TransferCodecTest.kt index 8e41344..c37349c 100644 --- a/app/src/test/java/com/wdtt/plus/TransferCodecTest.kt +++ b/app/src/test/java/com/wdtt/plus/TransferCodecTest.kt @@ -8,6 +8,24 @@ import org.junit.Test import org.json.JSONObject class TransferCodecTest { + @Test + fun connectionLinkCarriesOptionalProfileWorkerPolicy() { + val link = WdttTransferCodec.buildConnectionLink( + WdttLinkParts( + host = "vpn.example.org", + dtlsPort = 56000, + wgPort = 56001, + localPort = 9000, + password = "secret", + hashes = "1234567890abcdef", + maxWorkers = 9 + ) + ) + + assertEquals(9, WdttDeepLink.parse(link)?.maxWorkers) + assertEquals(0, WdttDeepLink.parse(link.replace("&max_workers=9", ""))?.maxWorkers) + } + @Test fun modernConnectionLink_roundTripsSpecialCharacters() { val original = WdttLinkParts( @@ -112,6 +130,14 @@ class TransferCodecTest { assertEquals("", validation.parts?.profileName) } + @Test + fun invalidConnectionLink_helpShowsModernAndLegacyFormats() { + val message = WdttDeepLink.validate("not-a-link").userMessage() + + assertTrue(message.contains("Новый: wdtt://connect?v=1")) + assertTrue(message.contains("Старый: wdtt://адрес:")) + } + @Test fun onlyRenamedProfileIsPreparedForTransfer() { assertEquals("", vpnProfileTransferName(0, listOf("", "", ""))) @@ -166,6 +192,44 @@ class TransferCodecTest { assertEquals("Мой сервер", WdttDeepLink.parse(link.orEmpty())?.profileName) } + @Test + fun serverClientLink_withoutVkHashesCanBeSharedAndImportedAsPartialAccess() { + val link = buildServerConnectionLink( + password = "ABCDEFGHJKLMNPQR", + hashes = "", + ports = "56000,56001,9000", + fallbackHost = "vpn.example.org", + publicHost = "", + profileName = "Доступ без хеша" + ) + + assertNotNull(link) + assertTrue(link.orEmpty().contains("hashes=")) + assertFalse(WdttDeepLink.validate(link.orEmpty()).canStartVpn) + val partial = WdttDeepLink.parse(link.orEmpty(), allowMissingHashes = true) + assertNotNull(partial) + assertEquals("", partial?.hashes) + assertEquals("Доступ без хеша", partial?.profileName) + assertFalse(partial?.hasNonStandardPorts() ?: true) + } + + @Test + fun importedLinkEnablesCustomPortsOnlyWhenAtLeastOnePortDiffers() { + val standard = WdttLinkParts( + host = "vpn.example.org", + dtlsPort = 56000, + wgPort = 56001, + localPort = 9000, + password = "ABCDEFGHJKLMNPQR", + hashes = "hash" + ) + + assertFalse(standard.hasNonStandardPorts()) + assertTrue(standard.copy(dtlsPort = 57000).hasNonStandardPorts()) + assertTrue(standard.copy(wgPort = 57001).hasNonStandardPorts()) + assertTrue(standard.copy(localPort = 9100).hasNonStandardPorts()) + } + @Test fun linkCanBeExtractedFromSharedText() { val value = "Подключение: wdtt://vpn.example.org:56000:56001:9000:secret:1234567890abcdef\nНе передавайте посторонним" @@ -185,6 +249,38 @@ class TransferCodecTest { assertFalse(WdttDeepLink.validate(link).canStartVpn) } + @Test + fun connectionLinkWithoutHashes_canBeStoredButCannotStartVpn() { + val link = WdttTransferCodec.buildConnectionLink( + WdttLinkParts("vpn.example.org", 56000, 56001, 9000, "secret", "") + ) + + assertFalse(WdttDeepLink.validate(link).canStartVpn) + assertNotNull(WdttDeepLink.parse(link, allowMissingHashes = true)) + assertTrue( + WdttDeepLink.validate(link, allowMissingHashes = true) + .userMessage() + .contains("Добавьте свой VK-хеш") + ) + } + + @Test + fun ordinaryLongWordsAreNeverParsedAsVkHashes() { + val link = WdttTransferCodec.buildConnectionLink( + WdttLinkParts( + "vpn.example.org", + 56000, + 56001, + 9000, + "secret", + "пользовательский,переподключаются", + ) + ) + + assertFalse(WdttDeepLink.validate(link).canStartVpn) + assertEquals(null, WdttDeepLink.parse(link, allowMissingHashes = true)) + } + @Test fun malformedModernLink_isNotParsed() { val validation = WdttDeepLink.validate("wdtt://connect?v=1&host=vpn.example.org") diff --git a/app/src/test/java/com/wdtt/plus/TrustedWifiLogTest.kt b/app/src/test/java/com/wdtt/plus/TrustedWifiLogTest.kt new file mode 100644 index 0000000..df9cea3 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TrustedWifiLogTest.kt @@ -0,0 +1,23 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Test + +class TrustedWifiLogTest { + @Test + fun `repeated trusted wifi event updates one counter`() { + TunnelManager.isLoggingEnabled = true + TunnelManager.clearLogs() + try { + TunnelManager.noteTrustedWifiEvent("resume_wait_network", "Ждём рабочую сеть.") + TunnelManager.noteTrustedWifiEvent("resume_wait_network", "Ждём рабочую сеть.") + + val entries = TunnelManager.logs.value.filter { it.key == "trusted_wifi_resume_wait_network" } + assertEquals(1, entries.size) + assertEquals(2, entries.single().count) + assertEquals(LogSeverity.Info, entries.single().severity) + } finally { + TunnelManager.clearLogs() + } + } +} diff --git a/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt b/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt index 0e23bec..e204f07 100644 --- a/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt +++ b/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt @@ -123,4 +123,68 @@ class TrustedWifiTest { ) ) } + + @Test + fun `trusted wifi resume retries keep cpu awake only during fast recovery window`() { + assertEquals( + TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true), + trustedWifiResumeRetryPlan(0) + ) + assertEquals( + TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true), + trustedWifiResumeRetryPlan(11) + ) + assertEquals( + TrustedWifiResumeRetryPlan(delayMs = 30_000L, keepCpuAwake = false), + trustedWifiResumeRetryPlan(12) + ) + } + + @Test + fun `lost trusted wifi is not reused as validated resume network`() { + val networks = TrustedWifiValidatedNetworkTracker() + networks.update(network = "home", validated = true, wifi = true) + assertTrue(networks.hasUsableNetwork()) + + networks.forgetWifi() + assertFalse(networks.hasUsableNetwork()) + + networks.update(network = "cellular", validated = true, wifi = false) + assertTrue(networks.hasUsableNetwork()) + + networks.lost("cellular") + assertFalse(networks.hasUsableNetwork()) + } + + @Test + fun `trusted wifi loss preserves an already validated cellular network`() { + val networks = TrustedWifiValidatedNetworkTracker() + networks.update(network = "home", validated = true, wifi = true) + networks.update(network = "cellular", validated = true, wifi = false) + + networks.forgetWifi() + + assertTrue(networks.hasUsableNetwork()) + } + + @Test + fun `internet capability without validation is not enough to resume`() { + val networks = TrustedWifiValidatedNetworkTracker() + networks.update(network = "cellular", validated = false, wifi = false) + assertFalse(networks.hasUsableNetwork()) + + networks.update(network = "cellular", validated = true, wifi = false) + assertTrue(networks.hasUsableNetwork()) + } + + @Test + fun `losing trusted wifi does not discard a newly validated untrusted wifi`() { + val networks = TrustedWifiValidatedNetworkTracker() + networks.update(network = "home", validated = true, wifi = true) + networks.update(network = "office", validated = true, wifi = true) + + networks.lost("home") + + assertTrue(networks.hasUsableNetwork()) + } } diff --git a/app/src/test/java/com/wdtt/plus/TunnelProfilePresentationTest.kt b/app/src/test/java/com/wdtt/plus/TunnelProfilePresentationTest.kt new file mode 100644 index 0000000..fdf2e63 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TunnelProfilePresentationTest.kt @@ -0,0 +1,168 @@ +package com.wdtt.plus + +import com.wdtt.plus.ui.hasTunnelConnectionSource +import com.wdtt.plus.ui.isSelectedCompactConnectionReady +import com.wdtt.plus.ui.resolveConnectionInputMethod +import com.wdtt.plus.ui.usesCompactTunnelInterface +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TunnelProfilePresentationTest { + @Test + fun `user role uses compact tunnel interface`() { + assertTrue(usesCompactTunnelInterface("user")) + assertFalse(usesCompactTunnelInterface("admin")) + } + + @Test + fun `empty profiles use role specific default method`() { + assertEquals("link", resolveConnectionInputMethod("", false, false, true)) + assertEquals("manual", resolveConnectionInputMethod("", false, false, false)) + assertEquals("manual", resolveConnectionInputMethod("", false, true, true)) + assertEquals("link", resolveConnectionInputMethod("link", false, true, false)) + } + + @Test + fun `legacy profiles without saved method keep their configured source`() { + assertEquals("link", resolveConnectionInputMethod("", true, false, false)) + assertEquals("link", resolveConnectionInputMethod("", true, true, true)) + assertEquals("manual", resolveConnectionInputMethod("", false, true, false)) + assertTrue( + isSelectedCompactConnectionReady( + selectedMethod = "link", + savedMethod = "", + storedLinkMode = true, + linkPresent = true, + linkValid = true, + manualValid = false, + ) + ) + assertTrue( + isSelectedCompactConnectionReady( + selectedMethod = "manual", + savedMethod = "", + storedLinkMode = false, + linkPresent = false, + linkValid = false, + manualValid = true, + ) + ) + } + + @Test + fun `manual and link profiles detect their own connection source`() { + assertTrue(hasTunnelConnectionSource(false, false, "vpn.example", "secret")) + assertFalse(hasTunnelConnectionSource(false, false, "vpn.example", "")) + assertTrue(hasTunnelConnectionSource(true, true, "", "")) + assertTrue(hasTunnelConnectionSource(true, false, "vpn.example", "secret")) + } + + @Test + fun `selected connection method must match configured method`() { + assertTrue( + isSelectedCompactConnectionReady( + selectedMethod = "manual", + savedMethod = "manual", + storedLinkMode = false, + linkPresent = false, + linkValid = false, + manualValid = true, + ) + ) + assertFalse( + isSelectedCompactConnectionReady( + selectedMethod = "link", + savedMethod = "manual", + storedLinkMode = false, + linkPresent = false, + linkValid = false, + manualValid = true, + ) + ) + assertTrue( + isSelectedCompactConnectionReady( + selectedMethod = "link", + savedMethod = "link", + storedLinkMode = false, + linkPresent = false, + linkValid = false, + manualValid = true, + ) + ) + assertFalse( + isSelectedCompactConnectionReady( + selectedMethod = "manual", + savedMethod = "link", + storedLinkMode = false, + linkPresent = false, + linkValid = false, + manualValid = true, + ) + ) + } + + @Test + fun `incomplete selected method is not ready`() { + assertFalse( + isSelectedCompactConnectionReady( + selectedMethod = "manual", + savedMethod = "manual", + storedLinkMode = false, + linkPresent = false, + linkValid = false, + manualValid = false, + ) + ) + assertFalse( + isSelectedCompactConnectionReady( + selectedMethod = "link", + savedMethod = "", + storedLinkMode = true, + linkPresent = true, + linkValid = false, + manualValid = true, + ) + ) + } + + @Test + fun `running tunnel keeps launch profile after selection changes`() { + assertEquals( + 0, + displayedTunnelProfile( + selectedProfile = 2, + activeTunnelProfile = 0, + running = true, + trustedWifiWaiting = false, + ) + ) + } + + @Test + fun `trusted wifi waiting keeps tunnel profile`() { + assertEquals( + 1, + displayedTunnelProfile( + selectedProfile = 2, + activeTunnelProfile = 1, + running = false, + trustedWifiWaiting = true, + ) + ) + } + + @Test + fun `disconnected interface follows selected profile`() { + assertEquals( + 2, + displayedTunnelProfile( + selectedProfile = 2, + activeTunnelProfile = 0, + running = false, + trustedWifiWaiting = false, + ) + ) + } +} diff --git a/app/src/test/java/com/wdtt/plus/TunnelProfileRuntimeUpdateTest.kt b/app/src/test/java/com/wdtt/plus/TunnelProfileRuntimeUpdateTest.kt new file mode 100644 index 0000000..4373893 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TunnelProfileRuntimeUpdateTest.kt @@ -0,0 +1,90 @@ +package com.wdtt.plus + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TunnelProfileRuntimeUpdateTest { + @Test + fun activeRunningProfileRequestsRuntimeUpdate() { + assertTrue( + shouldRequestTunnelProfileRuntimeUpdate( + updatedProfile = 1, + activeTunnelProfile = 1, + tunnelRunning = true, + trustedWifiWaiting = false, + ) + ) + } + + @Test + fun inactiveProfileDoesNotTouchRunningTunnel() { + assertFalse( + shouldRequestTunnelProfileRuntimeUpdate( + updatedProfile = 2, + activeTunnelProfile = 1, + tunnelRunning = true, + trustedWifiWaiting = false, + ) + ) + } + + @Test + fun stoppedProfileDoesNotStartVpn() { + assertFalse( + shouldRequestTunnelProfileRuntimeUpdate( + updatedProfile = 1, + activeTunnelProfile = 1, + tunnelRunning = false, + trustedWifiWaiting = false, + ) + ) + } + + @Test + fun trustedWifiWaitingProfileKeepsUpdatedConfigurationForResume() { + assertTrue( + shouldRequestTunnelProfileRuntimeUpdate( + updatedProfile = 1, + activeTunnelProfile = 1, + tunnelRunning = false, + trustedWifiWaiting = true, + ) + ) + } + + @Test + fun changedConnectionParametersRequireRuntimeReplacement() { + val current = params(peer = "old.example:56000") + val updated = current.copy(peer = "new.example:56000") + + assertTrue(tunnelProfileRuntimeConfigurationChanged(current, updated)) + } + + @Test + fun unchangedConnectionParametersDoNotRestartTransport() { + val current = params(peer = "same.example:56000") + + assertFalse(tunnelProfileRuntimeConfigurationChanged(current, current.copy())) + } + + @Test + fun anotherProfileCannotReplaceActiveRuntimeConfiguration() { + val current = params(peer = "old.example:56000", profileIndex = 0) + val updated = current.copy(peer = "new.example:56000", profileIndex = 1) + + assertFalse(tunnelProfileRuntimeConfigurationChanged(current, updated)) + } + + private fun params( + peer: String, + profileIndex: Int = 0, + ) = TunnelParams( + peer = peer, + vkHashes = "hash", + workersPerHash = 9, + port = 9000, + connectionPassword = "password", + profileIndex = profileIndex, + ) +} diff --git a/app/src/test/java/com/wdtt/plus/TunnelRecoveryPolicyTest.kt b/app/src/test/java/com/wdtt/plus/TunnelRecoveryPolicyTest.kt new file mode 100644 index 0000000..f68d822 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TunnelRecoveryPolicyTest.kt @@ -0,0 +1,34 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Test + +class TunnelRecoveryPolicyTest { + @Test + fun firstRecoveryIsTransportOnly() { + assertEquals( + NetworkRecoveryAction.SoftRestart, + stableNetworkRecoveryAction(completedAttempts = 0), + ) + } + + @Test + fun failedTransportRecoveryRecreatesVpnOnce() { + assertEquals( + NetworkRecoveryAction.RecreateVpn, + stableNetworkRecoveryAction(completedAttempts = 1), + ) + } + + @Test + fun failedVpnRecreationStopsFailOpen() { + assertEquals( + NetworkRecoveryAction.StopVpn, + stableNetworkRecoveryAction(completedAttempts = 2), + ) + assertEquals( + NetworkRecoveryAction.StopVpn, + stableNetworkRecoveryAction(completedAttempts = 3), + ) + } +} diff --git a/app/src/test/java/com/wdtt/plus/TunnelStartConfigTest.kt b/app/src/test/java/com/wdtt/plus/TunnelStartConfigTest.kt new file mode 100644 index 0000000..177a271 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TunnelStartConfigTest.kt @@ -0,0 +1,47 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Test + +class TunnelStartConfigTest { + @Test + fun `tile and widgets stop both active and trusted wifi waiting tunnel`() { + assertEquals( + TunnelToggleAction.STOP, + tunnelToggleAction( + running = true, + trustedWifiWaiting = false, + vpnPermissionRequired = false, + ) + ) + assertEquals( + TunnelToggleAction.STOP, + tunnelToggleAction( + running = false, + trustedWifiWaiting = true, + vpnPermissionRequired = false, + ) + ) + } + + @Test + fun `tile and widgets request permission before start`() { + assertEquals( + TunnelToggleAction.REQUEST_VPN_PERMISSION, + tunnelToggleAction( + running = false, + trustedWifiWaiting = false, + vpnPermissionRequired = true, + ) + ) + assertEquals( + TunnelToggleAction.START, + tunnelToggleAction( + running = false, + trustedWifiWaiting = false, + vpnPermissionRequired = false, + ) + ) + } + +} diff --git a/app/src/test/java/com/wdtt/plus/TunnelStartRequestGateTest.kt b/app/src/test/java/com/wdtt/plus/TunnelStartRequestGateTest.kt new file mode 100644 index 0000000..9970f90 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TunnelStartRequestGateTest.kt @@ -0,0 +1,27 @@ +package com.wdtt.plus + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TunnelStartRequestGateTest { + @Test + fun `stop invalidates a delayed start`() { + val gate = TunnelStartRequestGate() + val request = gate.next() + + gate.invalidate() + + assertFalse(gate.isCurrent(request)) + } + + @Test + fun `only the latest profile request may finish`() { + val gate = TunnelStartRequestGate() + val first = gate.next() + val second = gate.next() + + assertFalse(gate.isCurrent(first)) + assertTrue(gate.isCurrent(second)) + } +} diff --git a/app/src/test/java/com/wdtt/plus/TunnelStopCoordinatorTest.kt b/app/src/test/java/com/wdtt/plus/TunnelStopCoordinatorTest.kt new file mode 100644 index 0000000..c2e50f9 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TunnelStopCoordinatorTest.kt @@ -0,0 +1,15 @@ +package com.wdtt.plus + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TunnelStopCoordinatorTest { + @Test + fun `only completed stop outcomes allow a destructive follow-up action`() { + assertTrue(TunnelStopResult.ALREADY_STOPPED.succeeded) + assertTrue(TunnelStopResult.STOPPED.succeeded) + assertFalse(TunnelStopResult.TIMED_OUT.succeeded) + assertFalse(TunnelStopResult.FAILED.succeeded) + } +} diff --git a/app/src/test/java/com/wdtt/plus/TunnelWorkerPolicyTest.kt b/app/src/test/java/com/wdtt/plus/TunnelWorkerPolicyTest.kt new file mode 100644 index 0000000..8e9bc33 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TunnelWorkerPolicyTest.kt @@ -0,0 +1,20 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Test + +class TunnelWorkerPolicyTest { + @Test + fun profilePolicyCapsOnlyTheProfileThatCarriesIt() { + assertEquals(9, normalizeTunnelWorkerCount(1, profileMaxWorkers = 9)) + assertEquals(9, normalizeTunnelWorkerCount(27, profileMaxWorkers = 9)) + assertEquals(18, normalizeTunnelWorkerCount(27, profileMaxWorkers = 18)) + } + + @Test + fun profileWithoutPolicyRetainsFullPowerRange() { + assertEquals(18, normalizeTunnelWorkerCount(16)) + assertEquals(108, normalizeTunnelWorkerCount(108)) + assertEquals(108, normalizeTunnelWorkerCount(500)) + } +} diff --git a/app/src/test/java/com/wdtt/plus/VkClientCredentialsTest.kt b/app/src/test/java/com/wdtt/plus/VkClientCredentialsTest.kt new file mode 100644 index 0000000..81d9f38 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/VkClientCredentialsTest.kt @@ -0,0 +1,42 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class VkClientCredentialsTest { + @Test + fun `client id normalization keeps digits only`() { + assertEquals("123456", normalizeVkClientId(" 12-ab34 56 ")) + assertTrue(isValidVkClientId("123456")) + assertFalse(isValidVkClientId("123-456")) + } + + @Test + fun `disabled custom mode never blocks built in credentials`() { + assertNull(customVkCredentialsError(CustomVkClientCredentials(enabled = false))) + } + + @Test + fun `enabled custom mode requires both values`() { + assertEquals( + "Укажите числовой Client ID приложения VK.", + customVkCredentialsError(CustomVkClientCredentials(enabled = true)) + ) + assertEquals( + "Укажите защищённый ключ (Client secret) приложения VK.", + customVkCredentialsError(CustomVkClientCredentials(enabled = true, clientId = "123456")) + ) + assertNull( + customVkCredentialsError( + CustomVkClientCredentials( + enabled = true, + clientId = "123456", + clientSecret = "test-only-secret" + ) + ) + ) + } +} diff --git a/app/src/test/java/com/wdtt/plus/VkJoinLinkTest.kt b/app/src/test/java/com/wdtt/plus/VkJoinLinkTest.kt new file mode 100644 index 0000000..a393977 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/VkJoinLinkTest.kt @@ -0,0 +1,55 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class VkJoinLinkTest { + @Test + fun extractsHashFromCurrentVkRuLink() { + assertEquals( + "current_hash_1234567890", + VkJoinLink.extractHash( + "https://vk.ru/call/join/current_hash_1234567890?from=share#fragment" + ) + ) + } + + @Test + fun keepsVkComLinksAsCompatibilityInput() { + assertEquals( + "legacy_hash_1234567890", + VkJoinLink.extractHash( + "https://vk.com/call/join/legacy_hash_1234567890?from=share" + ) + ) + } + + @Test + fun keepsRawHashInputSupported() { + assertEquals( + "raw_hash_1234567890", + VkJoinLink.extractHash("raw_hash_1234567890") + ) + } + + @Test + fun acceptsOnlyOpaqueAsciiHashValues() { + assertTrue(VkJoinLink.isValidHash("3XariaxnHDP9eTiWVFukTMO6ZjCw7c0QQS_J3gYiiaM")) + assertTrue(VkJoinLink.isValidHash("short")) + assertFalse(VkJoinLink.isValidHash("пользовательский")) + assertFalse(VkJoinLink.isValidHash("переподключаются")) + assertEquals("", VkJoinLink.extractValidHash("https://vk.ru/call/join/пользовательский")) + } + + @Test + fun validatesCharactersWithoutGuessingVkHashLength() { + assertTrue(VkJoinLink.isValidInput("a")) + assertTrue(VkJoinLink.isValidInput("https://vk.ru/call/join/a?from=share")) + assertFalse(VkJoinLink.isValidInput("хеш")) + assertFalse(VkJoinLink.isValidInput("bad/path")) + assertFalse(VkJoinLink.isValidInput("https://vk.ru/not-a-call/a")) + assertEquals("a,b_C-2", VkJoinLink.normalizeHashes("a, b_C-2")) + } +} diff --git a/app/src/test/java/com/wdtt/plus/WdttDocumentTest.kt b/app/src/test/java/com/wdtt/plus/WdttDocumentTest.kt new file mode 100644 index 0000000..10ab8c9 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/WdttDocumentTest.kt @@ -0,0 +1,32 @@ +package com.wdtt.plus + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class WdttDocumentTest { + @Test + fun `profile file name always has one wdtt extension`() { + assertEquals("WDTT-Plus-profile.wdtt", WdttDocument.fileName("WDTT-Plus-profile")) + assertEquals("WDTT-Plus-profile.wdtt", WdttDocument.fileName("WDTT-Plus-profile.wdtt")) + } + + @Test + fun `picker accepts current mime and compatible legacy document types`() { + assertArrayEquals( + arrayOf( + "application/vnd.wdtt.plus", + "application/vnd.wdtt.plus.transfer", + "application/vnd.wdtt.plus.client", + "application/json", + "application/octet-stream", + "text/plain", + ), + WdttDocument.acceptedMimeTypes(), + ) + assertTrue(WdttDocument.isAcceptedMimeType("application/vnd.wdtt.plus")) + assertTrue(WdttDocument.isAcceptedMimeType("application/octet-stream")) + assertTrue(WdttDocument.isAcceptedMimeType("text/plain; charset=utf-8")) + } +} diff --git a/app/src/test/java/com/wdtt/plus/WireGuardRuntimeConfigTest.kt b/app/src/test/java/com/wdtt/plus/WireGuardRuntimeConfigTest.kt new file mode 100644 index 0000000..1a795d6 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/WireGuardRuntimeConfigTest.kt @@ -0,0 +1,72 @@ +package com.wdtt.plus + +import com.wireguard.config.Config +import com.wireguard.crypto.Key +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.ByteArrayInputStream + +class WireGuardRuntimeConfigTest { + private val privateKey = Key.fromBytes(ByteArray(32) { index -> (index + 1).toByte() }) + .toBase64() + private val publicKey = Key.fromBytes(ByteArray(32) { index -> (index + 33).toByte() }) + .toBase64() + + @Test + fun unchangedConfigurationKeepsRunningVpnInterface() { + val current = config(endpointPort = 9000) + val updated = config(endpointPort = 9000) + + assertTrue( + shouldReuseRunningWireGuard( + tunnelUp = true, + currentConfigFingerprint = wireGuardConfigFingerprint(current), + updatedConfig = updated, + ) + ) + } + + @Test + fun changedConfigurationReplacesVpnInterface() { + assertFalse( + shouldReuseRunningWireGuard( + tunnelUp = true, + currentConfigFingerprint = wireGuardConfigFingerprint( + config(endpointPort = 9000) + ), + updatedConfig = config(endpointPort = 9001), + ) + ) + } + + @Test + fun stoppedVpnInterfaceIsNeverReused() { + val config = config(endpointPort = 9000) + + assertFalse( + shouldReuseRunningWireGuard( + tunnelUp = false, + currentConfigFingerprint = wireGuardConfigFingerprint(config), + updatedConfig = config, + ) + ) + } + + private fun config(endpointPort: Int): Config { + val text = """ + [Interface] + PrivateKey = $privateKey + Address = 10.0.0.2/32 + DNS = 1.1.1.1 + MTU = 1280 + + [Peer] + PublicKey = $publicKey + AllowedIPs = 0.0.0.0/0 + Endpoint = 127.0.0.1:$endpointPort + PersistentKeepalive = 25 + """.trimIndent() + return Config.parse(ByteArrayInputStream(text.toByteArray())) + } +} diff --git a/app/src/test/java/com/wdtt/plus/ui/ExceptionsTabBehaviorTest.kt b/app/src/test/java/com/wdtt/plus/ui/ExceptionsTabBehaviorTest.kt new file mode 100644 index 0000000..0302698 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/ExceptionsTabBehaviorTest.kt @@ -0,0 +1,96 @@ +package com.wdtt.plus.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ExceptionsTabBehaviorTest { + @Test + fun `header stays collapsed while app list can still scroll to its first item`() { + assertEquals( + -240f, + collapsingHeaderOffsetAfterScroll( + currentOffsetPx = -240f, + headerHeightPx = 240f, + deltaPx = 80f, + allowExpand = false, + ), + ) + } + + @Test + fun `header expands after app list reaches its first item`() { + assertEquals( + -160f, + collapsingHeaderOffsetAfterScroll( + currentOffsetPx = -240f, + headerHeightPx = 240f, + deltaPx = 80f, + allowExpand = true, + ), + ) + } + + @Test + fun `header gesture clamps expansion and collapse to measured height`() { + assertEquals( + 0f, + collapsingHeaderOffsetAfterScroll(-40f, 240f, 100f, allowExpand = true), + ) + assertEquals( + -240f, + collapsingHeaderOffsetAfterScroll(-200f, 240f, -100f, allowExpand = true), + ) + } + + @Test + fun `quick exclusions recognize current whitelist app packages`() { + val packages = listOf( + "ru.oneme.app", + "ru.gosuslugi.goskey", + "com.octopod.russianpost.client.android", + "ru.nspk.mirpay", + "ru.nspk.sbpay", + "logo.com.mbanking", + "ru.rzd.pass", + "ru.tutu.tutu_emp", + "ru.vkusvill", + "com.icemobile.lenta.prod", + "ru.reksoft.okey", + "ru.myauchan.droid", + "www.metro.com", + "ru.tander.magnit", + "ru.pyaterochka.app.browser", + "ru.perekrestok.app", + "club.chizhik", + "com.logistic.sdek", + "ru.dodopizza.app", + "ru.burgerking", + "com.apegroup.mcdonaldsrussia", + "com.carshering", + "youdrive.today", + "ru.ivi.client", + "ru.more.play", + "ru.zen.android", + "gpm.tnt_premier", + "ru.mts.mtstv", + "ru.radioplayer", + ) + + packages.forEach { packageName -> + assertTrue( + "Expected $packageName to be a quick exclusion", + matchesQuickExclusionApp(name = "Неизвестное название", packageName = packageName), + ) + } + } + + @Test + fun `quick exclusions match store label aliases without selecting unrelated apps`() { + assertTrue(matchesQuickExclusionApp("МАКС: общение, звонки, сервисы", "store.variant")) + assertTrue(matchesQuickExclusionApp("Вкусно — и точка", "store.variant")) + assertTrue(matchesQuickExclusionApp("Сателлит Online", "store.variant")) + assertFalse(matchesQuickExclusionApp("Калькулятор", "com.example.calculator")) + } +} diff --git a/app/src/test/java/com/wdtt/plus/ui/OutboundFormsStoreTest.kt b/app/src/test/java/com/wdtt/plus/ui/OutboundFormsStoreTest.kt new file mode 100644 index 0000000..b58746a --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/OutboundFormsStoreTest.kt @@ -0,0 +1,35 @@ +package com.wdtt.plus.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OutboundFormsStoreTest { + @Test + fun keys_areScopedToVpnProfile() { + assertEquals( + "profile_0_external_proxy_host", + OutboundFormsStore.key(0, "external_proxy_host") + ) + assertEquals( + "profile_2_external_proxy_host", + OutboundFormsStore.key(2, "external_proxy_host") + ) + assertEquals( + "profile_2_external_proxy_host", + OutboundFormsStore.key(99, "external_proxy_host") + ) + } + + @Test + fun secretKeys_haveSeparateEncryptedStorageName() { + assertEquals( + "profile_1_imported_wg_config_encrypted", + OutboundFormsStore.encryptedKey(1, "imported_wg_config") + ) + assertTrue(OutboundFormsStore.isSecretPlainKey("profile_1_wg_exit_password")) + assertTrue(OutboundFormsStore.isSecretPlainKey("local_proxy_password")) + assertFalse(OutboundFormsStore.isSecretPlainKey("profile_1_external_proxy_host")) + } +} diff --git a/app/src/test/java/com/wdtt/plus/ui/OutboundProfileComparisonTest.kt b/app/src/test/java/com/wdtt/plus/ui/OutboundProfileComparisonTest.kt new file mode 100644 index 0000000..1371ff6 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/OutboundProfileComparisonTest.kt @@ -0,0 +1,249 @@ +package com.wdtt.plus.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OutboundProfileComparisonTest { + @Test + fun unusedGeneratedDefaults_doNotLookLikeServerChanges() { + val server = snapshot( + localProxyPort = "1080", + localProxyLogin = "old-generated-login", + localProxyPassword = "old-generated-password", + externalProxyKindName = "", + externalProxyPort = "", + wireGuardExitSshPort = "", + wireGuardExitUser = "", + wireGuardExitPort = "", + wireGuardExitDns = "" + ) + val local = forms( + localProxyLogin = "new-generated-login", + localProxyPassword = "new-generated-password" + ) + + assertFalse(outboundProfilesDiffer(server, local)) + } + + @Test + fun configuredValues_areComparedAfterStorageNormalization() { + val server = snapshot( + mode = "wireguard_vps", + wireGuardPresent = true, + wireGuardExitHost = "exit.example.org", + wireGuardExitSshPort = "22", + wireGuardExitUser = "root", + wireGuardExitPassword = "secret", + wireGuardExitPort = "51820", + wireGuardExitDns = "1.1.1.1,8.8.8.8" + ) + val local = forms( + wireGuardExitHost = " exit.example.org ", + wireGuardExitSshPort = "port 22", + wireGuardExitUser = "root", + wireGuardExitPassword = "secret", + wireGuardExitPort = "51820 ", + wireGuardExitDns = "9.9.9.9" + ) + + // DNS WireGuard-выхода намеренно не сравнивается: DNS клиентов задаётся + // в основных настройках WDTT и не применяется этим режимом. + assertFalse(outboundProfilesDiffer(server, local)) + } + + @Test + fun configuredProxyChange_isReported() { + val server = snapshot( + externalProxyPresent = true, + externalProxyKindName = "Socks5", + externalProxyHost = "old.example.org", + externalProxyPort = "1080" + ) + val local = forms(externalProxyHost = "new.example.org") + + assertTrue(outboundProfilesDiffer(server, local)) + } + + @Test + fun orphanedWarpInterface_isAttributedOnlyToWarpAndCanBeDisabledThere() { + val server = snapshot( + mode = "direct", + wireGuardPresent = true, + wireGuardActive = true, + warpPresent = true + ) + + assertEquals( + OutboundModeIndicator(OutboundModeVisualState.Error, "не отключён"), + outboundModeIndicator(server, OutboundDialog.FreeWarp) + ) + assertEquals( + OutboundModeVisualState.Off, + outboundModeIndicator(server, OutboundDialog.WireGuardVps).state + ) + assertEquals( + OutboundModeVisualState.Off, + outboundModeIndicator(server, OutboundDialog.ImportedWireGuard).state + ) + assertTrue(canDisableOutboundDialog(server, OutboundDialog.FreeWarp)) + assertFalse(canDisableOutboundDialog(server, OutboundDialog.WireGuardVps)) + assertFalse(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard)) + assertTrue(canReturnDirect(server)) + } + + @Test + fun ownerMarker_winsOverUnrelatedWarpRegistration() { + val server = snapshot( + mode = "direct", + wireGuardPresent = true, + wireGuardActive = true, + warpPresent = true, + wireGuardOwnerMode = "imported_wg" + ) + + assertEquals( + OutboundModeVisualState.Error, + outboundModeIndicator(server, OutboundDialog.ImportedWireGuard).state + ) + assertEquals( + OutboundModeVisualState.Warning, + outboundModeIndicator(server, OutboundDialog.FreeWarp).state + ) + assertTrue(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard)) + assertFalse(canDisableOutboundDialog(server, OutboundDialog.FreeWarp)) + } + + @Test + fun partialExternalProxy_isNotReportedAsActiveAndCanBeCleaned() { + val server = snapshot( + mode = "external_proxy", + externalProxyPresent = true, + externalProxyServiceActive = true, + externalProxyRouteActive = false + ) + + assertEquals( + OutboundModeIndicator(OutboundModeVisualState.Error, "запущен частично"), + outboundModeIndicator(server, OutboundDialog.ExternalProxy) + ) + assertTrue(canDisableOutboundDialog(server, OutboundDialog.ExternalProxy)) + assertTrue(canReturnDirect(server)) + } + + @Test + fun recordedInactiveWireGuardMode_canStillBeDisabledFromItsDialog() { + val server = snapshot( + mode = "imported_wg", + wireGuardPresent = true, + wireGuardActive = false + ) + + assertTrue(canDisableOutboundDialog(server, OutboundDialog.ImportedWireGuard)) + assertTrue(canReturnDirect(server)) + } + + @Test + fun proxyCredentials_rejectAmbiguousValuesAndEscapeConfig() { + assertEquals( + "Логин внешнего прокси не должен содержать двоеточие.", + externalProxyCredentialsIssue("user:name", "password") + ) + assertTrue(localProxyCredentialsIssue("user", "short") != null) + assertEquals("""a\\b\"c""", escapeRedsocksQuotedValue("""a\b"c""")) + } + + private fun forms( + localProxyPort: String = "1080", + localProxyLogin: String = "generated-login", + localProxyPassword: String = "generated-password", + externalProxyKindName: String = "Socks5", + externalProxyHost: String = "", + externalProxyPort: String = "1080", + externalProxyLogin: String = "", + externalProxyPassword: String = "", + wireGuardExitHost: String = "", + wireGuardExitSshPort: String = "22", + wireGuardExitUser: String = "root", + wireGuardExitPassword: String = "", + wireGuardExitPort: String = "51820", + wireGuardExitDns: String = "1.1.1.1,8.8.8.8", + importedWireGuardConfig: String = "" + ) = OutboundProfileForms( + localProxyPort = localProxyPort, + localProxyLogin = localProxyLogin, + localProxyPassword = localProxyPassword, + externalProxyKindName = externalProxyKindName, + externalProxyHost = externalProxyHost, + externalProxyPort = externalProxyPort, + externalProxyLogin = externalProxyLogin, + externalProxyPassword = externalProxyPassword, + wireGuardExitHost = wireGuardExitHost, + wireGuardExitSshPort = wireGuardExitSshPort, + wireGuardExitUser = wireGuardExitUser, + wireGuardExitPassword = wireGuardExitPassword, + wireGuardExitPort = wireGuardExitPort, + wireGuardExitDns = wireGuardExitDns, + importedWireGuardConfig = importedWireGuardConfig + ) + + private fun snapshot( + mode: String = "direct", + localProxyPresent: Boolean = false, + localProxyPort: String = "", + localProxyLogin: String = "", + localProxyPassword: String = "", + externalProxyPresent: Boolean = false, + externalProxyKindName: String = "", + externalProxyHost: String = "", + externalProxyPort: String = "", + externalProxyLogin: String = "", + externalProxyPassword: String = "", + wireGuardPresent: Boolean = false, + wireGuardActive: Boolean = false, + wireGuardExitHost: String = "", + wireGuardExitSshPort: String = "", + wireGuardExitUser: String = "", + wireGuardExitPassword: String = "", + wireGuardExitPort: String = "", + wireGuardExitDns: String = "", + importedWireGuardConfig: String = "", + warpPresent: Boolean = false, + externalProxyServiceActive: Boolean = false, + externalProxyRouteActive: Boolean = false, + wireGuardOwnerMode: String = "" + ) = OutboundServerSnapshot( + mode = mode, + detail = "", + updatedAt = "", + hasProfile = true, + localProxyPresent = localProxyPresent, + localProxyActive = false, + localProxyPort = localProxyPort, + localProxyLogin = localProxyLogin, + localProxyPassword = localProxyPassword, + externalProxyPresent = externalProxyPresent, + externalProxyActive = false, + externalProxyKindName = externalProxyKindName, + externalProxyHost = externalProxyHost, + externalProxyPort = externalProxyPort, + externalProxyLogin = externalProxyLogin, + externalProxyPassword = externalProxyPassword, + wireGuardPresent = wireGuardPresent, + wireGuardActive = wireGuardActive, + wireGuardExitHost = wireGuardExitHost, + wireGuardExitSshPort = wireGuardExitSshPort, + wireGuardExitUser = wireGuardExitUser, + wireGuardExitPassword = wireGuardExitPassword, + wireGuardExitPort = wireGuardExitPort, + wireGuardExitDns = wireGuardExitDns, + warpPresent = warpPresent, + warpMtu = "", + importedWireGuardConfig = importedWireGuardConfig, + checkedAtMillis = 0L, + externalProxyServiceActive = externalProxyServiceActive, + externalProxyRouteActive = externalProxyRouteActive, + wireGuardOwnerMode = wireGuardOwnerMode + ) +} 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 eb046d1..6e34ed2 100644 --- a/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt @@ -51,6 +51,8 @@ class OutboundWireGuardTest { fun freeWarpScript_hasSafeUpdateChecksAndValidShellSyntax() { val script = buildFreeWarpInstallScript(1392) + assertTrue(WGCF_VERSION == "2.2.32") + assertTrue(THREEPROXY_VERSION == "0.9.7") assertTrue("WARP_MTU=1392" in script) assertTrue("checksums.txt" in script) assertTrue("sha256sum" in script) @@ -60,9 +62,60 @@ class OutboundWireGuardTest { assertTrue("WARP_ENDPOINT_CANDIDATES" in script) assertTrue("engage.cloudflareclient.com:2408" in script) assertTrue("rollback after WARP check error" in script) + assertTrue("trap wdtt_wg_up_cleanup 0" in script) + assertTrue("rollback after WireGuard service start error" in script) + assertTrue("WDTT_ERROR=wireguard_exit_service_inactive" in script) + assertTrue("ip link delete \"${'$'}WDTT_WG_IFACE\"" in script) assertShellSyntax(script) } + @Test + fun directExitScript_forceCleansPartiallyStartedWireGuard() { + val script = disableOutboundExitScript() + + assertTrue("wdtt_clear_external_out" in script) + assertTrue("ip link delete \"${'$'}WDTT_WG_IFACE\"" in script) + assertTrue("WDTT_ERROR=direct_cleanup_failed" in script) + assertTrue("wdtt_write_mode \"direct\"" in script) + assertShellSyntax(script) + } + + @Test + fun outboundCleanupScripts_areScopedAndHaveValidShellSyntax() { + val localStop = stopLocalProxyScript() + val localRemove = removeLocalProxyScript() + val external = deleteExternalProxyScript() + val imported = deleteImportedWireGuardExitScript() + val currentVps = deleteWireGuardVpsCurrentScript() + val foreignVps = deleteWireGuardVpsForeignScript() + + assertTrue("systemctl disable --now wdtt-3proxy" in localStop) + assertTrue("local_proxy_service_still_active" in localStop) + assertTrue("LOCAL_PROXY_PASSWORD_B64" in localRemove) + assertTrue("local_proxy_remove_failed" in localRemove) + assertTrue("wdtt_clear_proxy_out" in external) + assertTrue("EXTERNAL_PROXY_PASSWORD_B64" in external) + assertTrue("external_proxy_remove_failed" in external) + assertTrue("OWNS_ACTIVE" in imported) + assertTrue("wdtt_clear_wireguard_out" in imported) + assertTrue("IMPORTED_WG_CONFIG_B64" in imported) + assertTrue("wireguard_vps_current_remove_failed" in currentVps) + assertTrue("WDTT_EXIT_FOREIGN" in foreignVps) + assertTrue("foreign_wireguard_not_owned" in foreignVps) + assertShellSyntax(localStop) + assertShellSyntax(localRemove) + assertShellSyntax(external) + assertShellSyntax(imported) + assertShellSyntax(currentVps) + assertShellSyntax(foreignVps) + } + + @Test + fun protocolErrorMarker_isNotCopiedRawToUserLog() { + assertFalse(shouldWriteRemoteErrorToUserLog("WDTT_ERROR=local_proxy_check_failed")) + assertTrue(shouldWriteRemoteErrorToUserLog("FAIL: служба не запустилась")) + } + @Test fun serverDiagnosticsScript_hasPortableChecksAndValidShellSyntax() { val script = serverDiagnosticsScript() @@ -79,12 +132,25 @@ class OutboundWireGuardTest { assertTrue("systemctl" in script) assertTrue("iptables" in script) assertTrue("nft" in script) - assertTrue("VK / TURN-зависимости" in script) + assertTrue("VK/OK с VPS (справочно)" in script) + assertTrue("не влияет на основной VK-вход" in script) + assertTrue("login.vk.ru" in script) assertTrue("api.vk.me" in script) + assertTrue("api.vk.ru" in script) assertTrue("calls.okcdn.ru" in script) + assertTrue("Получение VK-токенов и решение капчи выполняются на телефоне" in script) + assertFalse("обязательным узлам VK в зоне .ru" in script) assertTrue("api.telegram.org" in script) assertTrue("Бесплатный WARP" in script) assertTrue("engage.cloudflareclient.com" in script) + assertTrue("wdtt_diag_wg_exit_probe" in script) + assertTrue("Cloudflare подтвердил warp=" in script) + assertTrue("WG_POLICY_RULE_ACTIVE" in script) + assertTrue("WG_DEFAULT_ROUTE_ACTIVE" in script) + assertTrue("WG_NAT_ACTIVE" in script) + assertTrue("WireGuard-выход запущен не полностью" in script) + assertTrue("FIREWALL_SEVERITY=\"ERROR\"" in script) + assertTrue("NAT прямого выхода отсутствует" in script) assertTrue("WDTT_EXPECTED_DTLS_PORT" in script) assertTrue("wdtt_diag_udp_probe" in script) assertTrue("/dev/net/tun" in script) @@ -93,6 +159,42 @@ class OutboundWireGuardTest { assertShellSyntax(script, shell = "sh") } + @Test + fun externalProxyTransparentCheck_doesNotCaptureRootXrayTraffic() { + val script = outboundShellPrelude() + + assertTrue("WDTT_PROXY_TEST_SOURCE=\"${'$'}test_source\"" in script) + assertTrue("iptables -t nat -I OUTPUT -s \"${'$'}test_source\" -p tcp -j WDTT_PROXY_TEST" in script) + assertTrue("curl --interface \"${'$'}test_source\"" in script) + assertFalse("iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST" in script) + assertShellSyntax(script) + } + + @Test + fun outboundSnapshot_preservesExplicitlySavedEmptyFields() { + val script = outboundSnapshotScript() + + assertTrue("wdtt_profile_has_key" in script) + assertTrue("if wdtt_profile_has_key LOCAL_PROXY_LOGIN_B64" in script) + assertTrue("if wdtt_profile_has_key EXTERNAL_PROXY_HOST_B64" in script) + assertTrue("if wdtt_profile_has_key WG_VPS_DNS_B64" in script) + assertTrue("! wdtt_profile_has_key IMPORTED_WG_CONFIG_B64" in script) + assertTrue("WDTT_LOCAL_PROXY_SERVICE_ENABLED" in script) + assertTrue("WDTT_EXTERNAL_PROXY_SERVICE_ENABLED" in script) + assertTrue("WDTT_WG_SERVICE_ENABLED" in script) + assertShellSyntax(script) + } + + @Test + fun detailedOutboundStatus_reportsRoutesAndAutostart() { + val script = outboundStatusScript() + + assertTrue("Автозапуск внешнего TCP-прокси" in script) + assertTrue("Правило маршрутизации подсети WDTT" in script) + assertTrue("NAT WireGuard-выхода" in script) + assertShellSyntax(script) + } + @Test(expected = IllegalArgumentException::class) fun freeWarpScript_rejectsUnsafeMtu() { buildFreeWarpInstallScript(1600) diff --git a/app/src/test/java/com/wdtt/plus/ui/ServerMigrationTest.kt b/app/src/test/java/com/wdtt/plus/ui/ServerMigrationTest.kt index 5c2d8eb..d9d6ce2 100644 --- a/app/src/test/java/com/wdtt/plus/ui/ServerMigrationTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/ServerMigrationTest.kt @@ -2,8 +2,11 @@ package com.wdtt.plus.ui import org.json.JSONArray import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test +import java.util.Base64 class ServerMigrationTest { @Test @@ -11,6 +14,64 @@ class ServerMigrationTest { validatePasswordsDbStructure(database("client-a", "Телефон")) } + @Test + fun backupValidation_acceptsTrafficImportHistory() { + val db = database("client-a", "Телефон") + + validatePasswordsDbStructure(db) + } + + @Test(expected = IllegalArgumentException::class) + fun backupValidation_rejectsMalformedTrafficImportHistory() { + val db = database("client-a", "Телефон") + db.getJSONObject("passwords").getJSONObject("client-a") + .put("traffic_imports", JSONArray()) + + validatePasswordsDbStructure(db) + } + + @Test + fun preserveValidation_recoversEmptyMainPasswordFromCurrentSecrets() { + val db = database("client-a", "Телефон").put("main_password", "") + + val needsRecovery = validatePasswordsDbForPreserving(db, "new-owner-password") + + assertTrue(needsRecovery) + assertTrue(db.optString("main_password").isEmpty()) + assertTrue(db.getJSONObject("passwords").has("client-a")) + } + + @Test + fun preserveValidation_recoversMissingMainPasswordFromCurrentSecrets() { + val db = database("client-a", "Телефон").apply { remove("main_password") } + + assertTrue(validatePasswordsDbForPreserving(db, "new-owner-password")) + assertTrue(!db.has("main_password")) + } + + @Test + fun preserveValidation_keepsValidMainPassword() { + val db = database("client-a", "Телефон") + + assertTrue(!validatePasswordsDbForPreserving(db, "new-owner-password")) + assertTrue(db.optString("main_password") == "owner-password") + } + + @Test(expected = IllegalArgumentException::class) + fun preserveValidation_rejectsRecoveryWithoutCurrentMainPassword() { + val db = database("client-a", "Телефон").put("main_password", "") + + validatePasswordsDbForPreserving(db, "") + } + + @Test(expected = IllegalArgumentException::class) + fun preserveValidation_stillRejectsMalformedClientDataDuringRecovery() { + val db = database("client-a", "Телефон").put("main_password", "") + db.getJSONObject("passwords").getJSONObject("client-a").put("expires_at", -1L) + + validatePasswordsDbForPreserving(db, "new-owner-password") + } + @Test(expected = IllegalArgumentException::class) fun backupValidation_rejectsInvalidOwnerProfile() { val db = database("client-a", "Телефон") @@ -28,6 +89,19 @@ class ServerMigrationTest { validateImportedServerState(source.toString(), null, after.toString(), replace = true) } + @Test(expected = IllegalArgumentException::class) + fun replaceImport_detectsChangedTrafficImportHistory() { + val source = database("client-a", "Телефон") + val after = JSONObject(source.toString()) + after.getJSONObject("passwords") + .getJSONObject("client-a") + .getJSONObject("traffic_imports") + .getJSONObject("move-1") + .put("down_bytes", 999L) + + validateImportedServerState(source.toString(), null, after.toString(), replace = true) + } + @Test fun mergeImport_preservesTargetAndAddsMissingClient() { val before = database("target-client", "Существующий") @@ -79,10 +153,120 @@ class ServerMigrationTest { assertTrue(target.getJSONObject("devices").getJSONObject("used-device").getString("ip") == "10.66.66.3") } + @Test + fun replaceAdaptsOwnerAndClientPortsToTarget() { + val source = database("client-a", "Телефон") + + val prepared = JSONObject( + prepareServerDatabaseForTarget( + sourceJson = source.toString(), + currentDbJson = null, + merge = false, + portsSpec = "56100,56101,9100", + dnsValue = "9.9.9.9", + publicHost = "new.example.org" + ) + ) + + assertEquals( + "56100,56101,9100", + prepared.getJSONObject("passwords").getJSONObject("client-a").getString("ports") + ) + assertEquals("56100,56101,9100", prepared.getJSONObject("admin_profile").getString("ports")) + assertEquals(9100, prepared.getJSONObject("admin_profile").getInt("listen_port")) + assertEquals("new.example.org", prepared.getString("public_ip")) + } + + @Test + fun mergeIntoEmptyServerKeepsWholeSourceDatabase() { + val source = database("client-a", "Телефон") + .put("admin_down_bytes", 12_345L) + .put("admin_up_bytes", 54_321L) + + val prepared = JSONObject( + prepareServerDatabaseForTarget( + sourceJson = source.toString(), + currentDbJson = null, + merge = true, + portsSpec = "56100,56101,9100", + dnsValue = "9.9.9.9", + publicHost = "new.example.org" + ) + ) + + assertEquals(12_345L, prepared.getLong("admin_down_bytes")) + assertEquals(54_321L, prepared.getLong("admin_up_bytes")) + assertTrue(prepared.getJSONObject("admin_profile").has("workers_per_hash")) + assertTrue(prepared.getJSONObject("passwords").has("client-a")) + } + + @Test + fun versionTwoBackupRoundTripVerifiesIntegrity() { + val source = database("client-a", "Телефон") + val keys = List(4) { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }.joinToString("\n") + val encoded = backupToJson( + parseBackup( + passwordsJson = source.toString(), + wgKeysDat = keys, + createdAt = "27.07.2026 12:00", + sourceHost = "old.example.org" + ) + ) + + val decoded = parseBackupFile(encoded) + + assertEquals(2, decoded.formatVersion) + assertTrue(decoded.integrityVerified) + assertTrue(decoded.hasWgKeys) + assertEquals(source.toString(), decoded.passwordsJson) + } + + @Test(expected = IllegalArgumentException::class) + fun versionTwoBackupRejectsChangedDatabase() { + val source = database("client-a", "Телефон") + val encoded = JSONObject( + backupToJson( + parseBackup( + passwordsJson = source.toString(), + wgKeysDat = null, + createdAt = "27.07.2026 12:00", + sourceHost = "old.example.org" + ) + ) + ) + val changed = JSONObject(source.toString()).put("dns", "8.8.8.8").toString() + encoded.put( + "passwords_json_b64", + Base64.getEncoder().encodeToString(changed.toByteArray()) + ) + + parseBackupFile(encoded.toString()) + } + + @Test + fun versionOneBackupRemainsCompatible() { + val source = database("client-a", "Телефон") + val legacy = JSONObject() + .put("format", "wdtt-server-backup") + .put("version", 1) + .put("created_at", "05.07.2026 10:00") + .put("source_host", "old.example.org") + .put( + "passwords_json_b64", + Base64.getEncoder().encodeToString(source.toString().toByteArray()) + ) + + val decoded = parseBackupFile(legacy.toString()) + + assertEquals(1, decoded.formatVersion) + assertFalse(decoded.integrityVerified) + assertEquals(source.toString(), decoded.passwordsJson) + } + private fun database(password: String, label: String): JSONObject { val entry = JSONObject() .put("device_id", "") - .put("expires_at", 0L) + .put("expires_at", 2_000_000_000L) .put("down_bytes", 1024L) .put("up_bytes", 2048L) .put("label", label) @@ -94,6 +278,13 @@ class ServerMigrationTest { .put("down_bytes", 1024L) .put("up_bytes", 2048L) )) + .put("traffic_imports", JSONObject().put( + "move-1", + JSONObject() + .put("down_bytes", 100L) + .put("up_bytes", 200L) + .put("applied_at", 1_700_000_000L) + )) .put("bind_history", JSONArray()) return JSONObject() .put("main_password", "owner-password") diff --git a/app/src/test/java/com/wdtt/plus/ui/VkClientIdProbeTest.kt b/app/src/test/java/com/wdtt/plus/ui/VkClientIdProbeTest.kt new file mode 100644 index 0000000..f83a45c --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/VkClientIdProbeTest.kt @@ -0,0 +1,102 @@ +package com.wdtt.plus.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class VkClientIdProbeTest { + @Test + fun legacyProbePrefersVkRuAndKeepsVkComAsCompatibilityFallback() { + assertEquals("https://oauth.vk.ru/authorize", vkLegacyOAuthProbeEndpoints.first()) + assertEquals("https://oauth.vk.com/authorize", vkLegacyOAuthProbeEndpoints.last()) + } + + @Test + fun acceptsLegacyOauthLoginPage() { + assertTrue(isVkLegacyClientIdProbeSuccessful(200, "text/html; charset=utf-8")) + } + + @Test + fun rejectsJsonErrorsAndHttpFailures() { + assertFalse(isVkLegacyClientIdProbeSuccessful(401, "application/json; charset=utf-8")) + assertFalse(isVkLegacyClientIdProbeSuccessful(200, "application/json")) + assertFalse(isVkLegacyClientIdProbeSuccessful(503, "text/html")) + assertTrue(isVkLegacyClientIdProbeRejected(401)) + assertFalse(isVkLegacyClientIdProbeRejected(429)) + assertFalse(isVkLegacyClientIdProbeRejected(503)) + } + + @Test + fun cachedProbeResultsKeepStatusAndTimestampSeparate() { + val cache = parseVkClientIdCheckResults( + """{"_probe_version":3,"_checked_at":123456,"6287487":"LegacyCompatible","8202606":"LegacyRejected"}""" + ) + + assertEquals(123456L, cache.checkedAt) + assertEquals( + mapOf( + "6287487" to VkClientIdProbeStatus.LegacyCompatible, + "8202606" to VkClientIdProbeStatus.LegacyRejected + ), + cache.results + ) + } + + @Test + fun probeCooldownBlocksRapidRepeatedChecks() { + assertEquals(10_000L, vkClientIdProbeCooldownRemainingMillis(now = 20_000L, lastStartedAt = 20_000L)) + assertEquals(1L, vkClientIdProbeCooldownRemainingMillis(now = 29_999L, lastStartedAt = 20_000L)) + assertEquals(0L, vkClientIdProbeCooldownRemainingMillis(now = 30_000L, lastStartedAt = 20_000L)) + } + + @Test + fun availabilitySummaryExplainsAllProbeCombinations() { + val ids = listOf("6287487", "8202606") + + assertEquals( + "Все встроенные Client ID доступны для резервного способа", + vkClientIdAvailabilityMessage( + ids, + mapOf( + "6287487" to VkClientIdProbeStatus.LegacyCompatible, + "8202606" to VkClientIdProbeStatus.LegacyCompatible + ) + ) + ) + assertEquals( + "Доступны: 6287487. Не принимаются: 8202606.", + vkClientIdAvailabilityMessage( + ids, + mapOf( + "6287487" to VkClientIdProbeStatus.LegacyCompatible, + "8202606" to VkClientIdProbeStatus.LegacyRejected + ) + ) + ) + assertEquals( + "Не удалось проверить: 6287487, 8202606.", + vkClientIdAvailabilityMessage( + ids, + mapOf( + "6287487" to VkClientIdProbeStatus.CheckFailed, + "8202606" to VkClientIdProbeStatus.CheckFailed + ) + ) + ) + } + + @Test + fun automaticProbeUsesOnlyCredentialsForSelectedMode() { + assertEquals( + listOf("6287487", "8202606"), + vkClientIdsForAutomaticProbe(false, "123456", "secret") + ) + assertEquals( + listOf("123456"), + vkClientIdsForAutomaticProbe(true, "123456", "secret") + ) + assertTrue(vkClientIdsForAutomaticProbe(true, "123456", "").isEmpty()) + assertTrue(vkClientIdsForAutomaticProbe(true, "invalid", "secret").isEmpty()) + } +} diff --git a/app/src/test/java/com/wdtt/plus/ui/VkHashBulkPasteTest.kt b/app/src/test/java/com/wdtt/plus/ui/VkHashBulkPasteTest.kt new file mode 100644 index 0000000..c44dd8f --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ui/VkHashBulkPasteTest.kt @@ -0,0 +1,74 @@ +package com.wdtt.plus.ui + +import org.junit.Assert.assertEquals +import org.junit.Test + +class VkHashBulkPasteTest { + @Test + fun parseBulkVkHashesAcceptsCommaSeparatedHashes() { + assertEquals( + listOf("hash000000000001", "hash000000000002", "hash000000000003", "hash000000000004"), + parseBulkVkHashes("hash000000000001,hash000000000002,hash000000000003,hash000000000004") + ) + } + + @Test + fun parseBulkVkHashesAcceptsEncodedSpacesAndSeparators() { + assertEquals( + listOf("hash000000000001", "hash000000000002", "hash000000000003", "hash000000000004"), + parseBulkVkHashes("hash000000000001%20hash000000000002%2Chash000000000003%0Ahash000000000004") + ) + } + + @Test + fun parseBulkVkHashesExtractsJoinLinksAndDropsDuplicates() { + assertEquals( + listOf("hash000000000001", "hash000000000002"), + parseBulkVkHashes( + "https://vk.com/call/join/hash000000000001 " + + "https://vk.ru/call/join/hash000000000002 " + + "hash000000000001" + ) + ) + } + + @Test + fun parseBulkVkHashesRejectsOrdinaryLongWords() { + assertEquals( + emptyList(), + parseBulkVkHashes("пользовательский переподключаются") + ) + } + + @Test + fun mergeBulkVkHashesFillsOnlyEmptySlotsWithoutOverwritingExisting() { + val result = mergeBulkVkHashes( + existingSlots = listOf("", "oldHash0000000002", "oldHash0000000003", ""), + incomingHashes = listOf("newHash0000000001", "oldHash0000000002", "newHash0000000004"), + mode = BulkVkHashPasteMode.FillEmpty + ) + + assertEquals( + listOf("newHash0000000001", "oldHash0000000002", "oldHash0000000003", "newHash0000000004"), + result.slots + ) + assertEquals(2, result.insertedCount) + assertEquals(1, result.skippedCount) + } + + @Test + fun mergeBulkVkHashesReplacesAllSlotsWhenRequested() { + val result = mergeBulkVkHashes( + existingSlots = listOf("", "oldHash0000000002", "oldHash0000000003", ""), + incomingHashes = listOf("newHash0000000001", "newHash0000000002", "newHash0000000003", "newHash0000000004"), + mode = BulkVkHashPasteMode.ReplaceAll + ) + + assertEquals( + listOf("newHash0000000001", "newHash0000000002", "newHash0000000003", "newHash0000000004"), + result.slots + ) + assertEquals(4, result.insertedCount) + assertEquals(0, result.skippedCount) + } +} diff --git a/bot.go b/bot.go index 276dce6..6e55a69 100644 --- a/bot.go +++ b/bot.go @@ -12,8 +12,12 @@ import ( "strconv" "strings" "time" +) - "golang.zx2c4.com/wireguard/device" +const ( + botThreeProxyVersion = "0.9.7" + botThreeProxySourceURL = "https://github.com/3proxy/3proxy/archive/refs/tags/0.9.7.tar.gz" + botThreeProxySourceSHA256 = "efe862ef8b7c0ddf7b1c45d6b5d72f0b7cd0a3c54447419c7f1bd2239a06fc30" ) func defaultPortsSpec() string { @@ -141,7 +145,7 @@ func normalizePasswordLabel(input string) string { } func createBotClient( - wgDev *device.Device, + wgDev wgDevice, requestedPassword string, days int, expiresAt int64, @@ -226,7 +230,7 @@ func createBotClient( return password, entry, nil } -func changeBotClientPassword(wgDev *device.Device, oldPassword, requested string) (string, error) { +func changeBotClientPassword(wgDev wgDevice, oldPassword, requested string) (string, error) { newPassword, err := normalizeClientPassword(requested) if err != nil { return "", err @@ -246,7 +250,7 @@ func changeBotClientPassword(wgDev *device.Device, oldPassword, requested string if _, exists := db.Passwords[newPassword]; exists { return "", errors.New("клиент с таким паролем уже существует") } - if !entry.IsDeactivated && !isPasswordExpired(entry) { + if !entry.IsDeactivated && !isPasswordPurgeable(entry) { if err := serverWrapKeys.AddPassword(newPassword); err != nil { return "", fmt.Errorf("не удалось добавить новый WRAP-ключ: %w", err) } @@ -430,8 +434,14 @@ func botScriptErrorText(err error, output string) string { return "Не удалось собрать 3proxy: на сервере нет компилятора gcc/cc, и пакетный менеджер не смог его поставить." case "3proxy_source_no_openssl_headers": return "Не удалось собрать 3proxy: на сервере нет OpenSSL-заголовков. Нужен пакет libssl-dev, openssl-devel, libopenssl-devel или openssl-dev в зависимости от Linux-дистрибутива." + case "3proxy_source_no_pcre2_headers": + return "Не удалось собрать актуальный 3proxy: на сервере нет заголовков PCRE2. Нужен пакет libpcre2-dev или pcre2-devel." + case "3proxy_source_no_sha256sum": + return "Не удалось безопасно проверить архив 3proxy: на сервере нет sha256sum." case "3proxy_source_download_failed": - return "Не удалось скачать исходники 3proxy с GitHub. Проверьте, открывается ли github.com с сервера и не блокирует ли сеть исходящие HTTPS-подключения." + return "Не удалось скачать закреплённый выпуск 3proxy с GitHub. Проверьте, открывается ли github.com с сервера и не блокирует ли сеть исходящие HTTPS-подключения." + case "3proxy_source_checksum_failed": + return "Контрольная сумма архива 3proxy не совпала с закреплённым выпуском. Архив не был распакован или запущен." case "3proxy_source_unpack_failed": return "Архив 3proxy скачался, но сервер не смог его распаковать. Возможен битый архив, нехватка места или проблема с tar/gzip." case "3proxy_source_build_failed": @@ -441,7 +451,7 @@ func botScriptErrorText(err error, output string) string { case "3proxy_source_install_failed": return "3proxy собрался, но сервер не дал записать файл в /usr/local/bin. Проверьте root-права пользователя и sudo." case "3proxy_install_failed": - return "Не удалось установить 3proxy: пакет не найден в репозиториях сервера, а сборка из исходников не дала готовый файл. Повторите установку: теперь бот покажет конкретный шаг, на котором она сорвалась." + return "Не удалось установить закреплённый выпуск 3proxy из проверенных исходников. Повторите установку: бот покажет конкретный шаг, на котором она сорвалась." case "systemd_required": return "Для прокси на этом сервере нужна systemd-служба. На сервере не найден systemctl, поэтому бот не может безопасно запустить 3proxy как сервис." case "curl_not_installed": @@ -450,10 +460,16 @@ func botScriptErrorText(err error, output string) string { return "Внешний прокси не ответил. Проверьте тип, адрес, порт, логин и пароль." case "external_proxy_service_inactive": return "Служба перенаправления через внешний прокси не запустилась. Бот откатил правила и вернул прямой выход, чтобы интернет через VPN не остался сломанным." + case "external_proxy_route_install_failed": + return "Служба внешнего прокси запустилась, но постоянное правило маршрутизации WDTT не применилось. Режим отключён." + case "external_proxy_test_rule_failed": + return "Сервер не разрешил создать временное правило для проверки пути WDTT через внешний прокси. Режим не считается проверенным." case "external_proxy_apply_failed": return botTextWithRemoteTail("Внешний прокси отвечает напрямую, но путь WDTT через redsocks не заработал. Бот откатил правила и вернул прямой выход, чтобы VPN-интернет не пропал.", output) case "iptables_required": return "На сервере не найдены правила межсетевого экрана iptables. Без них нельзя направить подключения WDTT через прокси." + case "direct_cleanup_failed": + return "Сервер не подтвердил полную остановку прежнего WireGuard/прокси-выхода. Выполните диагностику перед включением другого режима." case "local_proxy_check_failed": return "Проверка не устанавливает прокси: она подключается к уже запущенному SOCKS5 на 127.0.0.1 с сохранёнными логином и паролем. Подключение не удалось. Создайте или обновите прокси." case "local_proxy_config_not_found": @@ -464,6 +480,8 @@ func botScriptErrorText(err error, output string) string { return "Служба wdtt-3proxy не запущена. Создайте или обновите прокси на сервере." case "local_proxy_service_still_active": return "Команда остановки выполнена, но служба wdtt-3proxy всё ещё запущена. Проверьте права пользователя SSH или остановите службу вручную." + case "local_proxy_firewall_failed": + return "Прокси запустился, но сервер не смог открыть его порты в firewall. Служба остановлена." case "redsocks_not_installed": return "Не удалось установить компонент перенаправления через внешний прокси. Проверьте доступ сервера к интернету и пакетному менеджеру." case "wdtt_iface_not_found": @@ -500,7 +518,10 @@ func isFriendlyBotScriptError(err error) bool { "3proxy_source_no_make", "3proxy_source_no_compiler", "3proxy_source_no_openssl_headers", + "3proxy_source_no_pcre2_headers", + "3proxy_source_no_sha256sum", "3proxy_source_download_failed", + "3proxy_source_checksum_failed", "3proxy_source_unpack_failed", "3proxy_source_build_failed", "3proxy_source_binary_missing", @@ -510,13 +531,17 @@ func isFriendlyBotScriptError(err error) bool { "curl_not_installed", "external_proxy_check_failed", "external_proxy_service_inactive", + "external_proxy_route_install_failed", + "external_proxy_test_rule_failed", "external_proxy_apply_failed", "iptables_required", + "direct_cleanup_failed", "local_proxy_check_failed", "local_proxy_config_not_found", "local_proxy_credentials_missing", "local_proxy_service_inactive", "local_proxy_service_still_active", + "local_proxy_firewall_failed", "redsocks_not_installed", "wdtt_iface_not_found", "wdtt_test_source_missing", @@ -612,16 +637,19 @@ wdtt_clear_external_out() { systemctl disable --now wdtt-warp-watchdog.timer 2>/dev/null || true systemctl disable --now wdtt-wg-exit.service 2>/dev/null || true if command -v iptables >/dev/null 2>&1; then - iptables -t nat -D PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null || true + while iptables -t nat -D PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null; do :; done iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true - iptables -t nat -D POSTROUTING -s "$WDTT_SUBNET" -o "$WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null || true + while iptables -t nat -D POSTROUTING -s "$WDTT_SUBNET" -o "$WDTT_WG_IFACE" -m comment --comment WDTT_EXIT -j MASQUERADE 2>/dev/null; do :; done fi - ip rule del from "$WDTT_SUBNET" table "$WDTT_TABLE" priority 100 2>/dev/null || true + while ip rule del from "$WDTT_SUBNET" table "$WDTT_TABLE" priority 100 2>/dev/null; do :; done ip route flush table "$WDTT_TABLE" 2>/dev/null || true systemctl disable --now wdtt-redsocks 2>/dev/null || systemctl stop wdtt-redsocks 2>/dev/null || true wdtt_kill_redsocks_listener - wg-quick down "$WDTT_WG_IFACE" 2>/dev/null || true + if ! wg-quick down "$WDTT_WG_IFACE" 2>/dev/null; then + ip link delete "$WDTT_WG_IFACE" 2>/dev/null || true + fi + rm -f /etc/wdtt-plus/wg-exit/owner } wdtt_kill_redsocks_listener() { rm -f /run/wdtt-redsocks.pid 2>/dev/null || true @@ -646,24 +674,32 @@ wdtt_proxy_reserved_returns() { [ -n "$proxy_ip" ] && iptables -t nat -A "$chain" -d "$proxy_ip" -j RETURN 2>/dev/null || true } wdtt_cleanup_proxy_test() { + cleanup_test_source="${WDTT_PROXY_TEST_SOURCE:-}" + [ -n "$cleanup_test_source" ] && iptables -t nat -D OUTPUT -s "$cleanup_test_source" -p tcp -j WDTT_PROXY_TEST 2>/dev/null || true + # Удаляем также правило старых версий, если предыдущая проверка была прервана. iptables -t nat -D OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST 2>/dev/null || true iptables -t nat -F WDTT_PROXY_TEST 2>/dev/null || true iptables -t nat -X WDTT_PROXY_TEST 2>/dev/null || true + WDTT_PROXY_TEST_SOURCE="" } wdtt_test_redsocks_path() { proxy_ip="$1" systemctl is-active --quiet wdtt-redsocks || { echo WDTT_ERROR=external_proxy_service_inactive; return 1; } command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; return 1; } + test_source="$(wdtt_test_source)" + [ -n "$test_source" ] || { echo WDTT_ERROR=wdtt_iface_not_found; return 1; } wdtt_cleanup_proxy_test + WDTT_PROXY_TEST_SOURCE="$test_source" iptables -t nat -N WDTT_PROXY_TEST 2>/dev/null || true iptables -t nat -F WDTT_PROXY_TEST wdtt_proxy_reserved_returns WDTT_PROXY_TEST "$proxy_ip" iptables -t nat -A WDTT_PROXY_TEST -p tcp -j REDIRECT --to-ports 12345 - if ! iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST 2>/dev/null; then + if ! iptables -t nat -I OUTPUT -s "$test_source" -p tcp -j WDTT_PROXY_TEST 2>/dev/null; then wdtt_cleanup_proxy_test - return 0 + echo WDTT_ERROR=external_proxy_test_rule_failed + return 1 fi - test_ip="$(curl -4fsS --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/tmp/wdtt-redsocks-test.err || true)" + test_ip="$(curl --interface "$test_source" -4fsS --connect-timeout 5 --max-time 18 https://api.ipify.org 2>/tmp/wdtt-redsocks-test.err || true)" wdtt_cleanup_proxy_test [ -n "$test_ip" ] || { echo WDTT_ERROR=external_proxy_apply_failed; tail -n 20 /var/log/wdtt-redsocks.log 2>/dev/null || true; cat /tmp/wdtt-redsocks-test.err 2>/dev/null || true; return 1; } echo "Проверка пути через внешний прокси успешна. IP через прокси: $test_ip" @@ -711,17 +747,35 @@ echo "Подсеть клиентов WDTT: $WDTT_SUBNET" echo "Интерфейс клиентов: $WDTT_IFACE" echo "Внешний IP самого сервера: $SERVER_IP" if systemctl is-active wdtt-3proxy >/dev/null 2>&1; then echo "Прокси на этом сервере: служба запущена"; else echo "Прокси на этом сервере: служба остановлена"; fi -EXTERNAL_ACTIVE=0 -if systemctl is-active wdtt-redsocks >/dev/null 2>&1; then EXTERNAL_ACTIVE=1; echo "Внешний прокси для WDTT: включён"; else echo "Внешний прокси для WDTT: выключен"; fi -WG_ACTIVE=0 +if systemctl is-enabled wdtt-3proxy >/dev/null 2>&1; then echo "Автозапуск прокси на этом сервере: включён"; else echo "Автозапуск прокси на этом сервере: выключен"; fi +EXTERNAL_SERVICE=0 +if systemctl is-active wdtt-redsocks >/dev/null 2>&1; then EXTERNAL_SERVICE=1; echo "Служба внешнего прокси: запущена"; else echo "Служба внешнего прокси: остановлена"; fi +if systemctl is-enabled wdtt-redsocks >/dev/null 2>&1; then echo "Автозапуск внешнего прокси: включён"; else echo "Автозапуск внешнего прокси: выключен"; fi +EXTERNAL_ROUTE=0 +if command -v iptables >/dev/null 2>&1 && + iptables -t nat -C PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null; then + EXTERNAL_ROUTE=1 + echo "Маршрут TCP-трафика WDTT через внешний прокси: применён" +else + echo "Маршрут TCP-трафика WDTT через внешний прокси: отсутствует" +fi +WG_INTERFACE=0 if command -v wg >/dev/null 2>&1 && wg show "$WDTT_WG_IFACE" >/dev/null 2>&1; then - WG_ACTIVE=1 + WG_INTERFACE=1 echo "WireGuard $WDTT_WG_IFACE:" wg show "$WDTT_WG_IFACE" | sed -E 's/(private key: ).*/\1(скрыт)/' else echo "WireGuard $WDTT_WG_IFACE: не запущен" fi -if [ "$EXTERNAL_ACTIVE" = 1 ] && [ "$WG_ACTIVE" = 1 ]; then +if systemctl is-active wdtt-wg-exit.service >/dev/null 2>&1; then echo "Служба WireGuard-выхода: запущена"; else echo "Служба WireGuard-выхода: остановлена"; fi +if systemctl is-enabled wdtt-wg-exit.service >/dev/null 2>&1; then echo "Автозапуск WireGuard-выхода: включён"; else echo "Автозапуск WireGuard-выхода: выключен"; fi +WG_ROUTE=0 +ip rule show 2>/dev/null | grep -Eq "from [^ ]+ lookup $WDTT_TABLE([[:space:]]|$)|from [^ ]+ lookup wdtt-exit([[:space:]]|$)" && WG_ROUTE=1 +ip route show table "$WDTT_TABLE" 2>/dev/null | grep -Eq "^default([[:space:]].*)? dev $WDTT_WG_IFACE([[:space:]]|$)" && WG_ROUTE=1 +if command -v iptables >/dev/null 2>&1; then + iptables -t nat -S POSTROUTING 2>/dev/null | grep -q -- "-o $WDTT_WG_IFACE .*--comment WDTT_EXIT .*MASQUERADE" && WG_ROUTE=1 +fi +if [ "$EXTERNAL_ROUTE" = 1 ] && { [ "$WG_INTERFACE" = 1 ] || [ "$WG_ROUTE" = 1 ]; }; then echo "Внимание: одновременно активны внешний TCP-прокси и WireGuard-выход. Верните прямой выход или выполните диагностику перед новым переключением." fi if [ "$MODE" = "warp_free" ]; then @@ -789,6 +843,17 @@ tail -n 20 /var/log/wdtt-redsocks.log 2>/dev/null || echo "Лог redsocks пу func outboundDisableScript() string { return outboundBotPrelude() + ` wdtt_clear_external_out +CLEANUP_LEFT=0 +(command -v wg >/dev/null 2>&1 && wg show "$WDTT_WG_IFACE" >/dev/null 2>&1) && CLEANUP_LEFT=1 +systemctl is-active --quiet wdtt-wg-exit.service 2>/dev/null && CLEANUP_LEFT=1 +systemctl is-active --quiet wdtt-redsocks.service 2>/dev/null && CLEANUP_LEFT=1 +ip rule show 2>/dev/null | grep -Eq "from [^ ]+ lookup $WDTT_TABLE([[:space:]]|$)|from [^ ]+ lookup wdtt-exit([[:space:]]|$)" && CLEANUP_LEFT=1 +ip route show table "$WDTT_TABLE" 2>/dev/null | grep -Eq "^default([[:space:]].*)? dev $WDTT_WG_IFACE([[:space:]]|$)" && CLEANUP_LEFT=1 +if command -v iptables >/dev/null 2>&1; then + iptables -t nat -S PREROUTING 2>/dev/null | grep -q -- "-i $WDTT_IFACE .* -j WDTT_PROXY_OUT" && CLEANUP_LEFT=1 + iptables -t nat -S POSTROUTING 2>/dev/null | grep -q -- "-o $WDTT_WG_IFACE .*--comment WDTT_EXIT .*MASQUERADE" && CLEANUP_LEFT=1 +fi +[ "$CLEANUP_LEFT" = 0 ] || { echo WDTT_ERROR=direct_cleanup_failed; exit 3; } wdtt_write_mode "direct" "прямой выход через текущий сервер" echo "Внешний прокси или WireGuard-выход отключён. WDTT-пользователи снова идут напрямую через текущий сервер." ` @@ -900,6 +965,9 @@ HTTP_PORT=%d ADMIN_PORT=%d PROXY_LOGIN=%s PROXY_PASSWORD=%s +THREEPROXY_VERSION=%s +THREEPROXY_SOURCE_URL=%s +THREEPROXY_SOURCE_SHA256=%s install_pkg() { if command -v apt-get >/dev/null 2>&1; then apt-get update -y >/dev/null 2>&1 || true @@ -920,17 +988,17 @@ install_pkg() { } install_3proxy_build_deps() { if command -v apt-get >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc libc6-dev libssl-dev + install_pkg curl ca-certificates tar gzip make gcc coreutils libc6-dev libssl-dev libpcre2-dev elif command -v dnf >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc glibc-devel openssl-devel + install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel openssl-devel pcre2-devel elif command -v yum >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc glibc-devel openssl-devel + install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel openssl-devel pcre2-devel elif command -v zypper >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc glibc-devel libopenssl-devel + install_pkg curl ca-certificates tar gzip make gcc coreutils glibc-devel libopenssl-devel pcre2-devel elif command -v apk >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc musl-dev linux-headers openssl-dev + install_pkg curl ca-certificates tar gzip make gcc coreutils musl-dev linux-headers openssl-dev pcre2-dev elif command -v pacman >/dev/null 2>&1; then - install_pkg curl ca-certificates tar gzip make gcc glibc openssl + install_pkg curl ca-certificates tar gzip make gcc coreutils glibc openssl pcre2 else return 1 fi @@ -944,24 +1012,30 @@ install_3proxy_from_source() { command -v tar >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_tar; exit 2; } command -v gzip >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_gzip; exit 2; } command -v make >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_make; exit 2; } + command -v sha256sum >/dev/null 2>&1 || { echo WDTT_ERROR=3proxy_source_no_sha256sum; exit 2; } (command -v gcc >/dev/null 2>&1 || command -v cc >/dev/null 2>&1) || { echo WDTT_ERROR=3proxy_source_no_compiler; exit 2; } [ -f /usr/include/openssl/evp.h ] || [ -f /usr/local/include/openssl/evp.h ] || { echo WDTT_ERROR=3proxy_source_no_openssl_headers; exit 2; } + [ -f /usr/include/pcre2.h ] || [ -f /usr/local/include/pcre2.h ] || { echo WDTT_ERROR=3proxy_source_no_pcre2_headers; exit 2; } cd "$TMP_DIR" - curl -fsSL -o 3proxy.tar.gz https://github.com/3proxy/3proxy/archive/refs/heads/master.tar.gz || { echo WDTT_ERROR=3proxy_source_download_failed; exit 2; } + curl -fsSL --retry 2 --connect-timeout 12 --max-time 180 -o 3proxy.tar.gz "$THREEPROXY_SOURCE_URL" || { echo WDTT_ERROR=3proxy_source_download_failed; exit 2; } + ACTUAL_SOURCE_SHA256="$(sha256sum 3proxy.tar.gz | awk '{print $1}')" + [ "$ACTUAL_SOURCE_SHA256" = "$THREEPROXY_SOURCE_SHA256" ] || { echo WDTT_ERROR=3proxy_source_checksum_failed; exit 2; } tar -xzf 3proxy.tar.gz || { echo WDTT_ERROR=3proxy_source_unpack_failed; exit 2; } - cd 3proxy-* + cd "3proxy-$THREEPROXY_VERSION" ln -sf Makefile.Linux Makefile make >/tmp/wdtt-3proxy-build.log 2>&1 || { echo WDTT_ERROR=3proxy_source_build_failed; tail -n 20 /tmp/wdtt-3proxy-build.log; exit 2; } BUILT_BIN="$(find . -type f -name 3proxy -perm -111 | head -n1)" [ -n "$BUILT_BIN" ] || { echo WDTT_ERROR=3proxy_source_binary_missing; exit 2; } install -m 755 "$BUILT_BIN" /usr/local/bin/3proxy || { echo WDTT_ERROR=3proxy_source_install_failed; exit 2; } + printf '%%s\n' "$THREEPROXY_VERSION" >/etc/wdtt/3proxy-version + chmod 600 /etc/wdtt/3proxy-version } command -v systemctl >/dev/null 2>&1 || { echo WDTT_ERROR=systemd_required; exit 2; } install_pkg curl ca-certificates || true -install_pkg 3proxy || true THREEPROXY_BIN="$(command -v 3proxy || true)" -if [ -z "$THREEPROXY_BIN" ]; then - install_3proxy_from_source || true +INSTALLED_THREEPROXY_VERSION="$(cat /etc/wdtt/3proxy-version 2>/dev/null || true)" +if [ -z "$THREEPROXY_BIN" ] || [ "$INSTALLED_THREEPROXY_VERSION" != "$THREEPROXY_VERSION" ]; then + install_3proxy_from_source THREEPROXY_BIN="$(command -v 3proxy || true)" fi [ -n "$THREEPROXY_BIN" ] || { echo WDTT_ERROR=3proxy_install_failed; exit 2; } @@ -979,6 +1053,26 @@ proxy -p$HTTP_PORT -i0.0.0.0 -e0.0.0.0 admin -p$ADMIN_PORT -i0.0.0.0 EOF chmod 600 /etc/wdtt/3proxy.cfg +mkdir -p /usr/local/lib/wdtt +cat >/usr/local/lib/wdtt/local-proxy-firewall </dev/null 2>&1; then + iptables -S INPUT 2>/dev/null | grep 'WDTT_LOCAL_PROXY' | sed 's/^-A /iptables -D /' | + while read -r cmd; do \$cmd 2>/dev/null || true; done + fi +} +if [ "\$action" = down ]; then cleanup; exit 0; fi +[ "\$action" = up ] || exit 2 +command -v iptables >/dev/null 2>&1 || exit 0 +cleanup +iptables -I INPUT -p tcp --dport $PROXY_PORT -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT +iptables -I INPUT -p tcp --dport $HTTP_PORT -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT +iptables -I INPUT -p tcp --dport $ADMIN_PORT -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT +EOF +chmod 700 /usr/local/lib/wdtt/local-proxy-firewall cat >/etc/systemd/system/wdtt-3proxy.service </dev/null -systemctl is-active --quiet wdtt-3proxy || { echo WDTT_ERROR=local_proxy_service_inactive; exit 3; } -if command -v iptables >/dev/null 2>&1; then - iptables -C INPUT -p tcp --dport "$PROXY_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "$PROXY_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT - iptables -C INPUT -p tcp --dport "$HTTP_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "$HTTP_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT - iptables -C INPUT -p tcp --dport "$ADMIN_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "$ADMIN_PORT" -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT +if ! systemctl enable wdtt-3proxy >/dev/null || + ! systemctl restart wdtt-3proxy >/dev/null || + ! systemctl is-active --quiet wdtt-3proxy; then + systemctl stop wdtt-3proxy 2>/dev/null || true + echo WDTT_ERROR=local_proxy_service_inactive + exit 3 fi +/usr/local/lib/wdtt/local-proxy-firewall up || { echo WDTT_ERROR=local_proxy_firewall_failed; systemctl stop wdtt-3proxy 2>/dev/null || true; exit 3; } +TEST_IP="$(curl --proxy-user "$PROXY_LOGIN:$PROXY_PASSWORD" --socks5-hostname "127.0.0.1:$PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" +[ -n "$TEST_IP" ] || { systemctl stop wdtt-3proxy 2>/dev/null || true; echo WDTT_ERROR=local_proxy_check_failed; exit 3; } SERVER_IP="$(curl -4fsS --max-time 8 https://api.ipify.org 2>/dev/null || hostname -I | awk '{print $1}')" cat >/etc/wdtt/local-proxy.json </etc/wdtt/local-proxy.json </dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; exit 2; if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files wdtt-3proxy.service >/dev/null 2>&1; then systemctl is-active --quiet wdtt-3proxy || { echo WDTT_ERROR=local_proxy_service_inactive; exit 3; } fi -IP="$(curl --socks5-hostname "$PROXY_LOGIN:$PROXY_PASSWORD@127.0.0.1:$PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" +IP="$(curl --proxy-user "$PROXY_LOGIN:$PROXY_PASSWORD" --socks5-hostname "127.0.0.1:$PROXY_PORT" -4fsS --max-time 12 https://api.ipify.org 2>/dev/null || true)" [ -n "$IP" ] || { echo WDTT_ERROR=local_proxy_check_failed; exit 3; } echo "Проверка успешна: SOCKS5 на 127.0.0.1:$PROXY_PORT отвечает с сохранёнными логином и паролем. Выходной IP: $IP" ` @@ -1054,7 +1153,7 @@ echo "Прокси на этом сервере остановлен. Настр } return ` systemctl disable --now wdtt-3proxy 2>/dev/null || true -rm -f /etc/systemd/system/wdtt-3proxy.service /etc/wdtt/3proxy.cfg /etc/wdtt/local-proxy.json +rm -f /etc/systemd/system/wdtt-3proxy.service /etc/wdtt/3proxy.cfg /etc/wdtt/local-proxy.json /usr/local/lib/wdtt/local-proxy-firewall systemctl daemon-reload 2>/dev/null || true if command -v iptables >/dev/null 2>&1; then iptables -S INPUT 2>/dev/null | grep WDTT_LOCAL_PROXY | sed 's/^-A /iptables -D /' | while read -r cmd; do $cmd 2>/dev/null || true; done @@ -1106,9 +1205,29 @@ func parseExternalProxyInput(input string) (kind, host string, port int, login, err = errors.New("если прокси с авторизацией, укажите и логин, и пароль; если без авторизации — используйте `- -`") return } + if len(login) > 80 || len(password) > 120 { + err = errors.New("логин должен быть не длиннее 80 символов, пароль — не длиннее 120") + return + } + if strings.Contains(login, ":") { + err = errors.New("логин внешнего прокси не должен содержать двоеточие") + return + } + if strings.ContainsAny(login+password, `\"`) { + err = errors.New("в логине и пароле через бот нельзя использовать кавычку или обратную косую черту; задайте такие данные из приложения") + return + } + if strings.IndexFunc(login+password, func(r rune) bool { return r < 32 || r == 127 }) >= 0 { + err = errors.New("логин или пароль содержит недопустимые управляющие символы") + return + } return } +func escapeRedsocksValue(value string) string { + return strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(value) +} + func proxyKindLabel(kind string) string { switch strings.ToLower(kind) { case "socks5": @@ -1125,18 +1244,20 @@ func externalProxyCheckScript(kind, host string, port int, login, password strin if kind == "socks5" { scheme = "socks5h" } - auth := "" - if login != "" { - auth = login + ":" + password + "@" - } - proxyURI := fmt.Sprintf("%s://%s%s:%d", scheme, auth, host, port) + proxyURI := fmt.Sprintf("%s://%s:%d", scheme, host, port) return fmt.Sprintf(` command -v curl >/dev/null 2>&1 || { echo WDTT_ERROR=curl_not_installed; exit 2; } PROXY_URI=%s -IP="$(curl --proxy "$PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)" +PROXY_LOGIN=%s +PROXY_PASSWORD=%s +if [ -n "$PROXY_LOGIN" ]; then + IP="$(curl --proxy "$PROXY_URI" --proxy-user "$PROXY_LOGIN:$PROXY_PASSWORD" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)" +else + IP="$(curl --proxy "$PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)" +fi [ -n "$IP" ] || { echo WDTT_ERROR=external_proxy_check_failed; exit 3; } echo "Проверка успешна: %s отвечает, сервер смог открыть проверочный сайт через него. IP через прокси: $IP" -`, botShellQuote(proxyURI), proxyKindLabel(kind)) +`, botShellQuote(proxyURI), botShellQuote(login), botShellQuote(password), proxyKindLabel(kind)) } func externalProxyEnableScript(kind, host string, port int, login, password string) string { @@ -1151,6 +1272,8 @@ PROXY_HOST=%s PROXY_PORT=%d PROXY_LOGIN=%s PROXY_PASSWORD=%s +PROXY_LOGIN_CONFIG=%s +PROXY_PASSWORD_CONFIG=%s wdtt_install_redsocks_tools || true REDSOCKS_BIN="$(command -v redsocks || true)" [ -n "$REDSOCKS_BIN" ] || { echo WDTT_ERROR=redsocks_not_installed; exit 2; } @@ -1175,22 +1298,48 @@ redsocks { type = $REDSOCKS_TYPE; EOF if [ -n "$PROXY_LOGIN" ]; then - printf ' login = "%%s";\n' "$PROXY_LOGIN" >>/etc/wdtt/redsocks.conf - printf ' password = "%%s";\n' "$PROXY_PASSWORD" >>/etc/wdtt/redsocks.conf + printf ' login = "%%s";\n' "$PROXY_LOGIN_CONFIG" >>/etc/wdtt/redsocks.conf + printf ' password = "%%s";\n' "$PROXY_PASSWORD_CONFIG" >>/etc/wdtt/redsocks.conf fi cat >>/etc/wdtt/redsocks.conf </usr/local/lib/wdtt/redsocks-routes </dev/null; do :; done + iptables -t nat -F WDTT_PROXY_OUT 2>/dev/null || true + iptables -t nat -X WDTT_PROXY_OUT 2>/dev/null || true +} +if [ "\$action" = down ]; then cleanup; exit 0; fi +[ "\$action" = up ] || exit 2 +cleanup +iptables -t nat -N WDTT_PROXY_OUT +for net in 0.0.0.0/8 10.0.0.0/8 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 224.0.0.0/4 240.0.0.0/4; do + iptables -t nat -A WDTT_PROXY_OUT -d "\$net" -j RETURN +done +[ -n "\$PROXY_IP" ] && iptables -t nat -A WDTT_PROXY_OUT -d "\$PROXY_IP" -j RETURN +iptables -t nat -A WDTT_PROXY_OUT -p tcp -j REDIRECT --to-ports 12345 +iptables -t nat -A PREROUTING -i "\$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT +EOF +chmod 700 /usr/local/lib/wdtt/redsocks-routes cat >/etc/systemd/system/wdtt-redsocks.service </dev/null -systemctl is-active --quiet wdtt-redsocks || { echo WDTT_ERROR=external_proxy_service_inactive; journalctl -u wdtt-redsocks -n 30 --no-pager 2>/dev/null || true; exit 3; } -iptables -t nat -N WDTT_PROXY_OUT 2>/dev/null || true -iptables -t nat -F WDTT_PROXY_OUT -wdtt_proxy_reserved_returns WDTT_PROXY_OUT "$PROXY_IP" -iptables -t nat -A WDTT_PROXY_OUT -p tcp -j REDIRECT --to-ports 12345 -iptables -t nat -C PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT 2>/dev/null || iptables -t nat -A PREROUTING -i "$WDTT_IFACE" -p tcp -j WDTT_PROXY_OUT +if ! systemctl enable wdtt-redsocks >/dev/null || + ! systemctl restart wdtt-redsocks >/dev/null || + ! systemctl is-active --quiet wdtt-redsocks; then + journalctl -u wdtt-redsocks -n 30 --no-pager 2>/dev/null || true + wdtt_clear_external_out + wdtt_write_mode "direct" "rollback after external proxy service error" + echo WDTT_ERROR=external_proxy_service_inactive + exit 3 +fi +/usr/local/lib/wdtt/redsocks-routes up || { echo WDTT_ERROR=external_proxy_route_install_failed; wdtt_clear_external_out; exit 3; } if ! wdtt_test_redsocks_path "$PROXY_IP"; then wdtt_clear_external_out wdtt_write_mode "direct" "rollback after external proxy error" @@ -1213,7 +1365,7 @@ fi wdtt_write_mode "external_proxy" "$PROXY_KIND://$PROXY_HOST:$PROXY_PORT" echo "Внешний прокси включён для обычных TCP-подключений WDTT-пользователей. Голосовой UDP-трафик через него не перенаправляется." echo "Прокси: $PROXY_KIND://$PROXY_HOST:$PROXY_PORT" -`, outboundBotPrelude(), botShellQuote(kind), botShellQuote(redsocksType), botShellQuote(host), port, botShellQuote(login), botShellQuote(password)) +`, outboundBotPrelude(), botShellQuote(kind), botShellQuote(redsocksType), botShellQuote(host), port, botShellQuote(login), botShellQuote(password), botShellQuote(escapeRedsocksValue(login)), botShellQuote(escapeRedsocksValue(password))) } func sendFreeWarpMenu(token string, adminID int64, messageID int) int { @@ -2108,7 +2260,7 @@ func showEditExpiryMenu(token string, adminID int64, messageID int, pass string) ) } -func startNewPasswordFlow(token string, adminID int64, wgDev *device.Device, waitingForDays *bool, messageID int) int { +func startNewPasswordFlow(token string, adminID int64, wgDev wgDevice, waitingForDays *bool, messageID int) int { dbMutex.Lock() if cleanupExpiredPasswordsLocked(wgDev) > 0 { saveDB() @@ -2125,7 +2277,7 @@ func startNewPasswordFlow(token string, adminID int64, wgDev *device.Device, wai return showNewPasswordDaysMenu(token, adminID, messageID) } -func botLoop(token string, adminIDstr string, wgDev *device.Device) { +func botLoop(token string, adminIDstr string, wgDev wgDevice) { if token == "" || adminIDstr == "" { return } @@ -2578,9 +2730,9 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { entry, exists := db.Passwords[pass] if exists && entry != nil { if days == 0 { - entry.ExpiresAt = 0 + setPasswordExpiryPreservingRetention(entry, 0) } else { - entry.ExpiresAt = time.Now().Add(time.Duration(days) * 24 * time.Hour).Unix() + setPasswordExpiryPreservingRetention(entry, time.Now().Add(time.Duration(days)*24*time.Hour).Unix()) } saveDB() } @@ -2787,7 +2939,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { } else if data == "out_local_install" { login := "wdtt" + strings.ToLower(generatePassword()[:8]) password := generatePassword() - promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "🧦 Создаю или обновляю SOCKS5/HTTP-прокси на этом сервере. Если пакета 3proxy нет, попробую собрать его из исходников...", nil) + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "🧦 Создаю или обновляю SOCKS5/HTTP-прокси на этом сервере из проверенного выпуска 3proxy...", nil) out, err := runBotScript(localProxyInstallScript(login, password, 1080), 5*time.Minute) promptMessageID = sendBotScriptResult(token, adminID, promptMessageID, "Прокси на сервере готов", out, err, "out_local") } else if data == "out_local_check" { @@ -3449,9 +3601,9 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { continue } if days == 0 { - entry.ExpiresAt = 0 + setPasswordExpiryPreservingRetention(entry, 0) } else { - entry.ExpiresAt = time.Now().Add(time.Duration(days) * 24 * time.Hour).Unix() + setPasswordExpiryPreservingRetention(entry, time.Now().Add(time.Duration(days)*24*time.Hour).Unix()) } saveDB() dbMutex.Unlock() @@ -3581,7 +3733,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { } } -func sendPasswordList(token string, adminID int64, wgDev *device.Device, messageID int) int { +func sendPasswordList(token string, adminID int64, wgDev wgDevice, messageID int) int { dbMutex.Lock() defer dbMutex.Unlock() diff --git a/bot_external_proxy_test.go b/bot_external_proxy_test.go new file mode 100644 index 0000000..fc20a54 --- /dev/null +++ b/bot_external_proxy_test.go @@ -0,0 +1,110 @@ +package main + +import ( + "os" + "os/exec" + "strings" + "testing" +) + +func TestExternalProxyTransparentCheckDoesNotCaptureRootXrayTraffic(t *testing.T) { + script := outboundBotPrelude() + + for _, expected := range []string{ + `WDTT_PROXY_TEST_SOURCE="$test_source"`, + `iptables -t nat -I OUTPUT -s "$test_source" -p tcp -j WDTT_PROXY_TEST`, + `curl --interface "$test_source"`, + } { + if !strings.Contains(script, expected) { + t.Fatalf("outbound script does not contain %q", expected) + } + } + + legacyInsertion := `iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST` + if strings.Contains(script, legacyInsertion) { + t.Fatalf("outbound script still captures every root TCP connection") + } +} + +func TestOutboundBotScriptsHaveValidBashSyntax(t *testing.T) { + scripts := map[string]string{ + "local proxy install": localProxyInstallScript("wdttuser", "safePassword123", 1080), + "local proxy check": localProxyCheckScript(), + "external proxy": externalProxyEnableScript("socks5", "proxy.example.com", 1080, "user", "password"), + "direct exit": outboundDisableScript(), + "status": outboundStatusScript(), + } + for name, script := range scripts { + t.Run(name, func(t *testing.T) { + assertBashSyntax(t, script) + }) + } +} + +func TestLocalProxyUsesPinnedVerifiedReleaseAndPersistentFirewall(t *testing.T) { + script := localProxyInstallScript("wdttuser", "safePassword123", 1080) + + for _, expected := range []string{ + `THREEPROXY_VERSION='0.9.7'`, + botThreeProxySourceSHA256, + "sha256sum 3proxy.tar.gz", + "local-proxy-firewall", + "ExecStartPost=/usr/local/lib/wdtt/local-proxy-firewall up", + `--proxy-user "$PROXY_LOGIN:$PROXY_PASSWORD"`, + } { + if !strings.Contains(script, expected) { + t.Fatalf("local proxy script does not contain %q", expected) + } + } + if strings.Contains(script, "master.tar.gz") { + t.Fatal("local proxy script still downloads mutable master.tar.gz") + } + if strings.Contains(script, `echo "SOCKS5: socks5://$PROXY_LOGIN:$PROXY_PASSWORD@`) { + t.Fatal("local proxy result exposes the generated password") + } +} + +func TestExternalProxyUsesPersistentRoutesAndSeparateCredentials(t *testing.T) { + script := externalProxyEnableScript("socks5", "proxy.example.com", 1080, "user", "password") + + for _, expected := range []string{ + "redsocks-routes", + "ExecStartPost=/usr/local/lib/wdtt/redsocks-routes up", + "ExecStopPost=/usr/local/lib/wdtt/redsocks-routes down", + "WDTT_ERROR=external_proxy_route_install_failed", + } { + if !strings.Contains(script, expected) { + t.Fatalf("external proxy script does not contain %q", expected) + } + } +} + +func TestExternalProxyInputRejectsAmbiguousCredentials(t *testing.T) { + if _, _, _, _, _, err := parseExternalProxyInput("socks5 proxy.example.com 1080 user:name password"); err == nil { + t.Fatal("login with colon must be rejected") + } + if _, _, _, _, _, err := parseExternalProxyInput(`socks5 proxy.example.com 1080 user pass\"word`); err == nil { + t.Fatal("credentials requiring config escaping must be entered from the app") + } +} + +func assertBashSyntax(t *testing.T, script string) { + t.Helper() + file, err := os.CreateTemp("", "wdtt-outbound-*.sh") + if err != nil { + t.Fatal(err) + } + name := file.Name() + defer os.Remove(name) + if _, err := file.WriteString(script); err != nil { + file.Close() + t.Fatal(err) + } + if err := file.Close(); err != nil { + t.Fatal(err) + } + output, err := exec.Command("bash", "-n", name).CombinedOutput() + if err != nil { + t.Fatalf("bash -n failed: %v\n%s", err, output) + } +} diff --git a/docs/icons.md b/docs/icons.md deleted file mode 100644 index acd5951..0000000 --- a/docs/icons.md +++ /dev/null @@ -1,17 +0,0 @@ -# WDTT Plus icon pack - -Основная иконка — готовый PNG-арт, не VectorDrawable. - -## Файлы - -- `docs/icon-sources/wdtt_plus_icon.png` — исходник. -- `app/src/main/res/mipmap-*/ic_launcher.png` — legacy launcher. -- `app/src/main/res/mipmap-*/ic_launcher_round.png` — legacy round. -- `app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml` — adaptive icon. -- `app/src/main/res/drawable/ic_launcher_foreground.png` — PNG foreground. -- `app/src/main/res/drawable/ic_launcher_background.png` — dark background. -- `app/src/main/res/drawable/ic_launcher_monochrome.xml` — Android 13 themed icon. -- `app/src/main/res/drawable/ic_notification_icon.xml` — status bar notification icon. -- `app/src/main/res/drawable/ic_tile_logo.xml` — Quick Settings tile icon. - -Полную 3D-иконку не перерисовывать через XML/SVG. VectorDrawable используется только для monochrome/notification/tile. diff --git a/docs/outbound-routing.md b/docs/outbound-routing.md deleted file mode 100644 index db80337..0000000 --- a/docs/outbound-routing.md +++ /dev/null @@ -1,78 +0,0 @@ -# Выходной IP и прокси - -Модуль на вкладке **«Деплой»** управляет выходом только для WDTT-пользователей. Он не должен менять глобальный `default route` основного сервера: SSH, системные обновления, Docker, Telegram-бот и сам транспорт WDTT продолжают идти обычным маршрутом сервера. - -## Общий принцип - -WDTT-сервер поднимает клиентскую сеть `10.66.66.0/24` на интерфейсе `wdtt0`. Внешние режимы применяются только к этой подсети: - -- внешний SOCKS5/HTTP использует `redsocks` и цепочку `WDTT_PROXY_OUT` в `iptables` только для `-i wdtt0`; -- WireGuard exit использует интерфейс `wg-wdtt-exit`, отдельную routing table `100` и `ip rule from 10.66.66.0/24 table 100`; -- возврат в direct очищает только правила WDTT Plus и не трогает остальные правила сервера. - -Одновременно активен один внешний выход: `direct`, `external_proxy`, `wireguard_vps` или `imported_wg`. - -## 1. Прокси на этом VPS - -Кнопка **«Прокси на этом VPS»** ставит `3proxy`, создаёт `wdtt-3proxy.service` и включает SOCKS5/HTTP-прокси с логином и паролем. Это прокси для администратора или внешних клиентов, оно не меняет маршрут WDTT-пользователей само по себе. - -Важно: - -- open proxy не создаётся, авторизация обязательна; -- SOCKS5-порт задаётся в окне, HTTP-порт создаётся как `SOCKS5 + 1`; -- пароль не пишется в обычный Android-лог, в результате показывается URI с замаскированным паролем. - -Проверка выполняется через: - -```bash -curl --socks5-hostname LOGIN:PASSWORD@127.0.0.1:PORT https://api.ipify.org -``` - -## 2. Внешний SOCKS5/HTTP-прокси - -Кнопка **«Внешний SOCKS5/HTTP»** ставит `redsocks`, поднимает редиректор на `0.0.0.0:12345` и перенаправляет TCP-трафик WDTT-пользователей через внешний прокси. - -Ограничения: - -- режим рассчитан в основном на TCP; -- UDP может не поддерживаться; -- качество, страна и репутация IP зависят от внешнего прокси; -- private/local ranges исключены из перенаправления. - -Если ICMP-пинги проходят, а сайты не открываются, проверьте диагностику: для трафика из `PREROUTING` редиректор не должен слушать только `127.0.0.1:12345`. - -Этот режим не меняет default route VPS. - -## 3. Зарубежный VPS через WireGuard - -Кнопка **«WG exit VPS»** подключается по SSH к foreign VPS, ставит WireGuard, создаёт туннель `wg-wdtt-exit` между текущим WDTT-сервером и foreign VPS, включает NAT на foreign VPS и policy routing на текущем сервере. - -Это рекомендуемый полноценный режим для смены выходного IP WDTT-пользователей, потому что WireGuard переносит не только TCP. - -## 4. Импорт WireGuard config - -Кнопка **«Импорт WG config»** принимает готовый `.conf` файлом или текстом. Конфиг проверяется на обязательные поля: - -- `[Interface] PrivateKey` -- `[Interface] Address` -- `[Peer] PublicKey` -- `[Peer] Endpoint` -- `[Peer] AllowedIPs` - -`PreUp`, `PostUp`, `PreDown`, `PostDown` запрещены при импорте, чтобы чужой конфиг не мог поменять маршруты всего VPS. WDTT Plus добавляет `Table = off`, поднимает `wg-wdtt-exit` и маршрутизирует через него только WDTT-подсеть. - -`AllowedIPs = 0.0.0.0/0` нормально для exit-node: благодаря `Table = off` и отдельному `ip rule` это не становится default route всего сервера. - -## Диагностика и rollback - -Кнопки **«Статус»** и **«Диагностика»** показывают: - -- текущий outbound mode; -- WDTT client subnet; -- внешний IP самого сервера; -- состояние `3proxy`, `redsocks`, `wg-wdtt-exit`; -- `ip rule`; -- routing table `100`; -- WDTT-цепочки `iptables`. - -Кнопка **«Вернуть direct»** останавливает `redsocks`, опускает `wg-wdtt-exit`, чистит policy routing и возвращает прямой выход через текущий VPS. diff --git a/go_client/creds.go b/go_client/creds.go index 87422de..d085679 100644 --- a/go_client/creds.go +++ b/go_client/creds.go @@ -9,7 +9,6 @@ import ( "io" "log" "math/rand" - "net" neturl "net/url" "strings" "sync" @@ -29,11 +28,25 @@ type VKCredentials struct { ClientSecret string } +type legacyVKCredentialProvider string + +const ( + legacyVKProviderCustom legacyVKCredentialProvider = "legacy-custom" + legacyVKProviderBuiltIn legacyVKCredentialProvider = "legacy-built-in" +) + +type legacyVKCredentialCandidate struct { + Credentials VKCredentials + Provider legacyVKCredentialProvider +} + var vkCredentialsList = []VKCredentials{ {ClientID: "6287487", ClientSecret: "MuAxFaKDYDOICzGnEOhp"}, {ClientID: "8202606", ClientSecret: "lMRsTiMCyPnp5vfoldmn"}, } +var customVKCredentials *VKCredentials + // Full list of known credentials to match against when setting active client IDs var knownVKCredentials = map[string]VKCredentials{ "6287487": {ClientID: "6287487", ClientSecret: "MuAxFaKDYDOICzGnEOhp"}, @@ -56,6 +69,44 @@ func SetActiveClientIds(ids string) { } } +func SetCustomVKCredentials(clientID, clientSecret string) error { + clientID = strings.TrimSpace(clientID) + if clientID == "" || len(clientID) > 20 { + return errors.New("client ID must contain 1 to 20 digits") + } + for _, char := range clientID { + if char < '0' || char > '9' { + return errors.New("client ID must contain digits only") + } + } + if strings.TrimSpace(clientSecret) == "" { + return errors.New("client secret is empty") + } + credentials := VKCredentials{ + ClientID: clientID, + ClientSecret: clientSecret, + } + customVKCredentials = &credentials + return nil +} + +func legacyVKCredentialCandidates() []legacyVKCredentialCandidate { + result := make([]legacyVKCredentialCandidate, 0, len(vkCredentialsList)+1) + if customVKCredentials != nil { + result = append(result, legacyVKCredentialCandidate{ + Credentials: *customVKCredentials, + Provider: legacyVKProviderCustom, + }) + } + for _, credentials := range vkCredentialsList { + result = append(result, legacyVKCredentialCandidate{ + Credentials: credentials, + Provider: legacyVKProviderBuiltIn, + }) + } + return result +} + func GetActiveClientIdsString() string { var ids []string for _, cred := range vkCredentialsList { @@ -82,6 +133,14 @@ type TurnCredentials struct { Link string } +type fetchedTurnCredentials struct { + Username string + Password string + ServerAddrs []string + Lifetime time.Duration + Provider string +} + type StreamCredentialsCache struct { creds TurnCredentials mutex sync.RWMutex @@ -96,6 +155,20 @@ const ( errorWindow = 10 * time.Second ) +func credentialCacheLifetime(reported time.Duration) time.Duration { + if reported <= 0 { + return credentialLifetime - cacheSafetyMargin + } + if reported > 24*time.Hour { + reported = 24 * time.Hour + } + margin := cacheSafetyMargin + if reported <= 2*cacheSafetyMargin { + margin = reported / 5 + } + return reported - margin +} + var streamsPerCache = 10 func getCacheID(streamID int) int { @@ -325,19 +398,21 @@ func getVkCredsCached(ctx context.Context, link string, streamID int) (string, s return cache.creds.Username, cache.creds.Password, cloneStringSlice(cache.creds.ServerAddrs), nil } - user, pass, addrs, err := fetchVkCredsSerialized(ctx, link, streamID) + fetched, err := fetchVkCredsSerialized(ctx, link, streamID) if err != nil { return "", "", nil, err } + cacheLifetime := credentialCacheLifetime(fetched.Lifetime) cache.creds = TurnCredentials{ - Username: user, - Password: pass, - ServerAddrs: addrs, - ExpiresAt: time.Now().Add(credentialLifetime - cacheSafetyMargin), + Username: fetched.Username, + Password: fetched.Password, + ServerAddrs: fetched.ServerAddrs, + ExpiresAt: time.Now().Add(cacheLifetime), Link: link, } - return user, pass, cloneStringSlice(addrs), nil + log.Printf("[STREAM %d] [VK Provider] %s: TURN-данные сохранены на %v", streamID, fetched.Provider, cacheLifetime.Truncate(time.Second)) + return fetched.Username, fetched.Password, cloneStringSlice(fetched.ServerAddrs), nil } // ─── Serialized (throttled) fetcher ─── @@ -347,7 +422,7 @@ var ( globalLastVkFetchTime time.Time ) -func fetchVkCredsSerialized(ctx context.Context, link string, streamID int) (string, string, []string, error) { +func fetchVkCredsSerialized(ctx context.Context, link string, streamID int) (fetchedTurnCredentials, error) { vkRequestMu.Lock() defer vkRequestMu.Unlock() @@ -360,7 +435,7 @@ func fetchVkCredsSerialized(ctx context.Context, link string, streamID int) (str log.Printf("[STREAM %d] [VK Auth] Throttling: waiting %v to prevent rate limit...", streamID, wait.Truncate(time.Millisecond)) select { case <-ctx.Done(): - return "", "", nil, ctx.Err() + return fetchedTurnCredentials{}, ctx.Err() case <-time.After(wait): } } @@ -374,67 +449,89 @@ func fetchVkCredsSerialized(ctx context.Context, link string, streamID int) (str // ─── Main credential fetcher (rotates through stable credential sets) ─── -func fetchVkCreds(ctx context.Context, link string, streamID int) (string, string, []string, error) { +func fetchVkCreds(ctx context.Context, link string, streamID int) (fetchedTurnCredentials, error) { if vkCallsPreflightEnabled.Load() { if pause := vkCallsFloodPauseRemaining(time.Now()); pause > 0 { - log.Printf("[STREAM %d] [VKCalls] preflight временно пропущен после ограничения VK (%v); продолжаем captcha-цепочку", streamID, pause.Truncate(time.Second)) + log.Printf("[STREAM %d] [VKCalls] preflight временно пропущен после ограничения VK (%v); продолжаем резервную legacy-цепочку", streamID, pause.Truncate(time.Second)) } else { log.Printf("[STREAM %d] [VKCalls] preflight", streamID) - if user, pass, addrs, err := getVKCredsViaVKCalls(ctx, link, streamID); err == nil { - return user, pass, addrs, nil + if user, pass, addrs, lifetime, err := getVKCredsViaVKCalls(ctx, link, streamID); err == nil { + log.Printf("[STREAM %d] [VK Provider] modern-vkcalls: успешно", streamID) + return fetchedTurnCredentials{ + Username: user, + Password: pass, + ServerAddrs: addrs, + Lifetime: lifetime, + Provider: "modern-vkcalls", + }, nil } else if isVKCallsFloodError(err) { startVKCallsFloodPause(time.Now()) - log.Printf("[STREAM %d] [VKCalls] VK временно ограничил анонимный вход; продолжаем captcha-цепочку", streamID) + log.Printf("[STREAM %d] [VKCalls] VK временно ограничил анонимный вход; продолжаем резервную legacy-цепочку", streamID) } else { - log.Printf("[STREAM %d] [VKCalls] preflight не сработал: %v; продолжаем captcha-цепочку", streamID, err) + log.Printf("[STREAM %d] [VKCalls] preflight не сработал: %v; продолжаем резервную legacy-цепочку", streamID, err) } } } if time.Now().Unix() < globalCaptchaLockout.Load() { - return "", "", nil, fmt.Errorf("CAPTCHA_WAIT_REQUIRED: global lockout active") + return fetchedTurnCredentials{}, fmt.Errorf("CAPTCHA_WAIT_REQUIRED: global lockout active") } + candidates := legacyVKCredentialCandidates() + if len(candidates) == 0 { + return fetchedTurnCredentials{}, errors.New("no legacy VK credentials configured") + } + attemptLimit := vkCredentialAttemptLimit + if len(candidates) > attemptLimit { + attemptLimit = len(candidates) + } var lastErr error jar := tlsclient.NewCookieJar() - for attempt := 0; attempt < vkCredentialAttemptLimit; attempt++ { - creds := vkCredentialsList[attempt%len(vkCredentialsList)] - log.Printf("[STREAM %d] [VK Auth] Trying credentials: client_id=%s (attempt %d/%d)", streamID, creds.ClientID, attempt+1, vkCredentialAttemptLimit) + for attempt := 0; attempt < attemptLimit; attempt++ { + candidate := candidates[attempt%len(candidates)] + creds := candidate.Credentials + provider := string(candidate.Provider) + log.Printf("[STREAM %d] [VK Provider] %s: пробуем client_id=%s (попытка %d/%d)", streamID, provider, creds.ClientID, attempt+1, attemptLimit) user, pass, addrs, err := getTokenChain(ctx, link, streamID, creds, jar) if err == nil { - log.Printf("[STREAM %d] [VK Auth] Success with client_id=%s", streamID, creds.ClientID) - return user, pass, addrs, nil + log.Printf("[STREAM %d] [VK Provider] %s: успешно", streamID, provider) + return fetchedTurnCredentials{ + Username: user, + Password: pass, + ServerAddrs: addrs, + Provider: provider, + }, nil } lastErr = err - log.Printf("[STREAM %d] [VK Auth] Failed with client_id=%s: %v", streamID, creds.ClientID, err) + log.Printf("[STREAM %d] [VK Provider] %s: client_id=%s не сработал: %v", streamID, provider, creds.ClientID, err) if strings.Contains(err.Error(), "CAPTCHA_WAIT_REQUIRED") || strings.Contains(err.Error(), "FATAL_CAPTCHA") { - return "", "", nil, err + return fetchedTurnCredentials{}, err } if strings.Contains(err.Error(), "INVALID_JOIN_LINK") || strings.Contains(err.Error(), "ANON_BLOCKED") || strings.Contains(err.Error(), "CALL_FULL") { - return "", "", nil, err + return fetchedTurnCredentials{}, err } if strings.Contains(err.Error(), "error_code:29") || strings.Contains(err.Error(), "error_code: 29") || strings.Contains(err.Error(), "Rate limit") { log.Printf("[STREAM %d] [VK Auth] Rate limit detected, trying next credentials...", streamID) } - if attempt%len(vkCredentialsList) == len(vkCredentialsList)-1 && attempt+1 < vkCredentialAttemptLimit { + if attempt%len(candidates) == len(candidates)-1 && attempt+1 < attemptLimit { wait := time.Duration(900+rand.Intn(900)) * time.Millisecond - log.Printf("[STREAM %d] [VK Auth] Both VK credentials failed, retrying stable pair after %v...", streamID, wait) + log.Printf("[STREAM %d] [VK Auth] Все legacy-провайдеры временно не сработали, повтор через %v...", streamID, wait) select { case <-ctx.Done(): - return "", "", nil, ctx.Err() + return fetchedTurnCredentials{}, ctx.Err() case <-time.After(wait): } } } - return "", "", nil, fmt.Errorf("all VK credentials failed: %w", lastErr) + return fetchedTurnCredentials{}, fmt.Errorf("all VK credential providers failed: %w", lastErr) } // ─── Token chain: anon_token → getCallPreview → getAnonymousToken → OK session → joinConversation → TURN creds ─── @@ -485,7 +582,7 @@ func getTokenChain(ctx context.Context, link string, streamID int, creds VKCrede httpResp, err := client.Do(req) if err != nil { - return nil, err + return nil, fmt.Errorf("VK HTTPS %s: %w", domain, err) } defer func() { if closeErr := httpResp.Body.Close(); closeErr != nil { @@ -680,9 +777,9 @@ func getTokenChain(ctx context.Context, link string, streamID int, creds VKCrede if !ok { continue } - clean := strings.Split(urlStr, "?")[0] - address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:") - addresses = append(addresses, address) + if normalized := normalizeTURNURL(urlStr); normalized != "" { + addresses = append(addresses, normalized) + } } if len(addresses) == 0 { @@ -875,51 +972,3 @@ func requestWebViewCaptcha(ctx context.Context, streamID int, captchaErr *VkCapt func GetCreds(ctx context.Context, link string, streamID int) (string, string, []string, error) { return getVkCredsCached(ctx, link, streamID) } - -// ─── DNS dialer setup ─── - -func setupGlobalResolver() { - dialer := &net.Dialer{ - Timeout: 3 * time.Second, - KeepAlive: 30 * time.Second, - } - yandexDNSServers := []string{"77.88.8.8:53", "77.88.8.1:53"} - - net.DefaultResolver = &net.Resolver{ - PreferGo: true, - Dial: func(ctx context.Context, network, address string) (net.Conn, error) { - var lastErr error - for _, dns := range yandexDNSServers { - conn, err := dialer.DialContext(ctx, "udp", dns) - if err == nil { - return conn, nil - } - lastErr = err - conn, err = dialer.DialContext(ctx, "tcp", dns) - if err == nil { - return conn, nil - } - lastErr = err - } - - address = strings.TrimSpace(address) - if address != "" && !isYandexDNSAddress(address) { - conn, err := dialer.DialContext(ctx, network, address) - if err == nil { - return conn, nil - } - lastErr = err - } - return nil, lastErr - }, - } -} - -func isYandexDNSAddress(address string) bool { - host, _, err := net.SplitHostPort(address) - if err != nil { - host = address - } - host = strings.Trim(host, "[]") - return host == "77.88.8.8" || host == "77.88.8.1" -} diff --git a/go_client/creds_custom_test.go b/go_client/creds_custom_test.go new file mode 100644 index 0000000..865d609 --- /dev/null +++ b/go_client/creds_custom_test.go @@ -0,0 +1,80 @@ +package main + +import ( + "testing" + "time" +) + +func TestSetCustomVKCredentialsAddsIndependentLegacyProvider(t *testing.T) { + originalCredentials := append([]VKCredentials(nil), vkCredentialsList...) + originalCustomCredentials := customVKCredentials + defer func() { + vkCredentialsList = originalCredentials + customVKCredentials = originalCustomCredentials + }() + vkCredentialsList = []VKCredentials{ + {ClientID: "6287487", ClientSecret: "built-in-one"}, + {ClientID: "8202606", ClientSecret: "built-in-two"}, + } + customVKCredentials = nil + + if err := SetCustomVKCredentials("12345678", "test-only-secret"); err != nil { + t.Fatalf("SetCustomVKCredentials returned error: %v", err) + } + candidates := legacyVKCredentialCandidates() + if len(candidates) != 3 { + t.Fatalf("candidate count = %d, want 3", len(candidates)) + } + if candidates[0].Provider != legacyVKProviderCustom || candidates[0].Credentials.ClientID != "12345678" { + t.Fatalf("first candidate = %#v, want custom credentials", candidates[0]) + } + if candidates[1].Provider != legacyVKProviderBuiltIn || candidates[1].Credentials.ClientID != "6287487" { + t.Fatalf("second candidate = %#v, want first built-in credentials", candidates[1]) + } + if candidates[2].Provider != legacyVKProviderBuiltIn || candidates[2].Credentials.ClientID != "8202606" { + t.Fatalf("third candidate = %#v, want second built-in credentials", candidates[2]) + } + if vkCallsClientID != "8093730" { + t.Fatalf("fixed VK Calls client ID = %q", vkCallsClientID) + } +} + +func TestSetCustomVKCredentialsRejectsIncompleteValues(t *testing.T) { + tests := []struct { + name string + id string + secret string + }{ + {name: "empty id", secret: "test-only-secret"}, + {name: "non numeric id", id: "123abc", secret: "test-only-secret"}, + {name: "empty secret", id: "12345678"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if err := SetCustomVKCredentials(test.id, test.secret); err == nil { + t.Fatal("expected validation error") + } + }) + } +} + +func TestCredentialCacheLifetime(t *testing.T) { + tests := []struct { + name string + reported time.Duration + want time.Duration + }{ + {name: "legacy fallback", want: 9 * time.Minute}, + {name: "server lifetime", reported: 10 * time.Minute, want: 9 * time.Minute}, + {name: "short lifetime", reported: 100 * time.Second, want: 80 * time.Second}, + {name: "short safe margin", reported: 20 * time.Second, want: 16 * time.Second}, + {name: "bounded", reported: 48 * time.Hour, want: 23*time.Hour + 59*time.Minute}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := credentialCacheLifetime(test.reported); got != test.want { + t.Fatalf("cache lifetime = %v, want %v", got, test.want) + } + }) + } +} diff --git a/go_client/creds_test.go b/go_client/creds_test.go index 915d704..ea277ea 100644 --- a/go_client/creds_test.go +++ b/go_client/creds_test.go @@ -1,6 +1,9 @@ package main -import "testing" +import ( + "errors" + "testing" +) func TestClassifyTerminalVKJoinError(t *testing.T) { tests := []struct { @@ -53,3 +56,26 @@ func TestClassifyTerminalVKJoinErrorIgnoresTransient(t *testing.T) { t.Fatalf("unexpected terminal error: %v", got) } } + +func TestClassifyHashCheckErrorKeepsTerminalAndTransientStatusesSeparate(t *testing.T) { + tests := []struct { + errText string + status string + }{ + {errText: "INVALID_JOIN_LINK: VK API error_code:9008", status: "dead"}, + {errText: "ANON_BLOCKED: anonymous join is disabled", status: "blocked"}, + {errText: "CALL_FULL: call is full", status: "full"}, + {errText: "vchat.joinConversationByLink: participant.check.flood", status: "limited"}, + {errText: "vchat.joinConversationByLink: VK HTTPS api.vk.me: timeout", status: "network"}, + {errText: "vchat.joinConversationByLink: unexpected response", status: "error"}, + } + + for _, test := range tests { + t.Run(test.status+"_"+test.errText[:4], func(t *testing.T) { + status, _ := classifyHashCheckError(errors.New(test.errText)) + if status != test.status { + t.Fatalf("status = %q, want %q", status, test.status) + } + }) + } +} diff --git a/go_client/creds_vkcalls.go b/go_client/creds_vkcalls.go index ca88678..6ddeb44 100644 --- a/go_client/creds_vkcalls.go +++ b/go_client/creds_vkcalls.go @@ -9,6 +9,7 @@ import ( "io" "log" neturl "net/url" + "strconv" "strings" "sync/atomic" "time" @@ -27,10 +28,27 @@ const ( ) var ( - errVKCallsFlood = errors.New("VKCalls participant check flood") - vkCallsFloodUntil atomic.Int64 + errVKCallsFlood = errors.New("VKCalls participant check flood") + vkCallsFloodUntil atomic.Int64 + vkCallsAPIBaseURLs = [...]string{ + "https://api.vk.me", + "https://api.vk.ru", + } ) +func vkCallsJoinURL(link string) string { + return neturl.QueryEscape("https://vk.ru/call/join/" + link) +} + +func vkCallsAPIRequestURLs(path string) []string { + cleanPath := "/" + strings.TrimLeft(path, "/") + result := make([]string, 0, len(vkCallsAPIBaseURLs)) + for _, baseURL := range vkCallsAPIBaseURLs { + result = append(result, strings.TrimRight(baseURL, "/")+cleanPath) + } + return result +} + func isVKCallsFloodError(err error) bool { return errors.Is(err, errVKCallsFlood) } @@ -52,11 +70,11 @@ func stableVKCallsUUID(scope string) string { return uuid.NewSHA1(uuid.NameSpaceOID, []byte(seed)).String() } -func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (string, string, []string, error) { +func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (string, string, []string, time.Duration, error) { deviceID := stableVKCallsUUID("vk") okDeviceID := stableVKCallsUUID("ok") name := generateName() - joinURL := neturl.QueryEscape("https://vk.com/call/join/" + link) + joinURL := vkCallsJoinURL(link) client, err := tlsclient.NewHttpClient( tlsclient.NewNoopLogger(), @@ -65,10 +83,15 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin tlsclient.WithCookieJar(tlsclient.NewCookieJar()), ) if err != nil { - return "", "", nil, fmt.Errorf("setup: %w", err) + return "", "", nil, 0, fmt.Errorf("setup: %w", err) } doRequest := func(step, requestURL string) (map[string]interface{}, error) { + parsedURL, parseErr := neturl.Parse(requestURL) + host := "" + if parseErr == nil { + host = parsedURL.Hostname() + } req, err := fhttp.NewRequestWithContext(ctx, "POST", requestURL, bytes.NewReader(nil)) if err != nil { return nil, fmt.Errorf("%s create request: %w", step, err) @@ -80,6 +103,9 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin resp, err := client.Do(req) if err != nil { + if host != "" { + return nil, fmt.Errorf("%s VK HTTPS %s: %w", step, host, err) + } return nil, fmt.Errorf("%s request: %w", step, err) } defer resp.Body.Close() @@ -93,55 +119,73 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin } return result, nil } + doVKAPIRequest := func(step, path string) (map[string]interface{}, error) { + var lastErr error + requestURLs := vkCallsAPIRequestURLs(path) + for index, requestURL := range requestURLs { + result, requestErr := doRequest(step, requestURL) + if requestErr == nil { + return result, nil + } + lastErr = requestErr + if index+1 < len(requestURLs) { + log.Printf("[VKCalls] %s через основной API-домен не выполнен, пробуем совместимый резерв: %v", step, requestErr) + } + } + return nil, lastErr + } - step1URL := fmt.Sprintf( - "https://api.vk.me/method/auth.getAnonymToken?v=%s&client_id=%s&link=%s&device_id=%s&anonymName=%s&lang=ru", + step1Path := fmt.Sprintf( + "/method/auth.getAnonymToken?v=%s&client_id=%s&link=%s&device_id=%s&anonymName=%s&lang=ru", vkCallsAPIVersion, vkCallsClientID, joinURL, deviceID, neturl.QueryEscape(name), ) - step1, err := doRequest("auth.getAnonymToken", step1URL) + step1, err := doVKAPIRequest("auth.getAnonymToken", step1Path) if err != nil { - return "", "", nil, err + return "", "", nil, 0, err + } + if err := parseVKCallsAPIError(step1); err != nil { + return "", "", nil, 0, fmt.Errorf("auth.getAnonymToken: %w", err) } anonymToken, err := extractVKCallsString(step1, "response", "token") if err != nil { - return "", "", nil, fmt.Errorf("auth.getAnonymToken: %w", err) + return "", "", nil, 0, fmt.Errorf("auth.getAnonymToken: %w", err) } - step2URL := fmt.Sprintf( - "https://api.vk.me/method/messages.getCallPreview?v=%s&anonymous_token=%s&device_id=%s&extended=1&fields=first_name,last_name,photo_200&lang=ru&link=%s", + step2Path := fmt.Sprintf( + "/method/messages.getCallPreview?v=%s&anonymous_token=%s&device_id=%s&extended=1&fields=first_name,last_name,photo_200&lang=ru&link=%s", vkCallsAPIVersion, neturl.QueryEscape(anonymToken), deviceID, joinURL, ) - step2, err := doRequest("messages.getCallPreview", step2URL) + step2, err := doVKAPIRequest("messages.getCallPreview", step2Path) if err != nil { - return "", "", nil, err + return "", "", nil, 0, err } if err := parseVKCallsAPIError(step2); err != nil { - return "", "", nil, fmt.Errorf("messages.getCallPreview: %w", err) + return "", "", nil, 0, fmt.Errorf("messages.getCallPreview: %w", err) } userID, err := extractVKCallsNumber(step2, "response", "user_id") if err != nil { - return "", "", nil, fmt.Errorf("messages.getCallPreview user_id: %w", err) + return "", "", nil, 0, fmt.Errorf("messages.getCallPreview user_id: %w", err) } secret, err := extractVKCallsString(step2, "response", "secret") if err != nil { - return "", "", nil, fmt.Errorf("messages.getCallPreview secret: %w", err) + return "", "", nil, 0, fmt.Errorf("messages.getCallPreview secret: %w", err) } - step3URL := fmt.Sprintf( - "https://api.vk.me/method/messages.getAnonymCallToken?v=%s&anonymous_token=%s&device_id=%s&link=%s&name=%s&user_id=%.0f&secret=%s&lang=ru", + step3Path := fmt.Sprintf( + "/method/messages.getAnonymCallToken?v=%s&anonymous_token=%s&device_id=%s&link=%s&name=%s&user_id=%.0f&secret=%s&lang=ru", vkCallsAPIVersion, neturl.QueryEscape(anonymToken), deviceID, joinURL, neturl.QueryEscape(name), userID, neturl.QueryEscape(secret), ) - step3, err := doRequest("messages.getAnonymCallToken", step3URL) + step3, err := doVKAPIRequest("messages.getAnonymCallToken", step3Path) if err != nil { - return "", "", nil, err + return "", "", nil, 0, err } if err := parseVKCallsAPIError(step3); err != nil { - return "", "", nil, fmt.Errorf("messages.getAnonymCallToken: %w", err) + return "", "", nil, 0, fmt.Errorf("messages.getAnonymCallToken: %w", err) } okAnonymToken, err := extractVKCallsString(step3, "response", "token") if err != nil { - return "", "", nil, fmt.Errorf("messages.getAnonymCallToken token: %w", err) + return "", "", nil, 0, fmt.Errorf("messages.getAnonymCallToken token: %w", err) } sessionData := neturl.QueryEscape(fmt.Sprintf(`{"version":2,"device_id":"%s","client_version":"1.0.1"}`, okDeviceID)) @@ -149,11 +193,14 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin "&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA" step4, err := doRequest("auth.anonymLogin", step4URL) if err != nil { - return "", "", nil, err + return "", "", nil, 0, err + } + if err := parseVKCallsOKError(step4); err != nil { + return "", "", nil, 0, fmt.Errorf("auth.anonymLogin: %w", err) } sessionKey, err := extractVKCallsString(step4, "session_key") if err != nil { - return "", "", nil, fmt.Errorf("auth.anonymLogin session_key: %w", err) + return "", "", nil, 0, fmt.Errorf("auth.anonymLogin session_key: %w", err) } step5URL := fmt.Sprintf( @@ -162,25 +209,29 @@ func getVKCredsViaVKCalls(ctx context.Context, link string, streamID int) (strin ) step5, err := doRequest("vchat.joinConversationByLink", step5URL) if err != nil { - return "", "", nil, err + return "", "", nil, 0, err + } + if terminal := classifyTerminalVKJoinError(step5); terminal != nil { + return "", "", nil, 0, terminal } if err := parseVKCallsOKError(step5); err != nil { - return "", "", nil, fmt.Errorf("vchat.joinConversationByLink: %w", err) + return "", "", nil, 0, fmt.Errorf("vchat.joinConversationByLink: %w", err) } user, err := extractVKCallsString(step5, "turn_server", "username") if err != nil { - return "", "", nil, err + return "", "", nil, 0, err } pass, err := extractVKCallsString(step5, "turn_server", "credential") if err != nil { - return "", "", nil, err + return "", "", nil, 0, err } addrs := parseVKCallsTURNAddresses(step5) if len(addrs) == 0 { - return "", "", nil, fmt.Errorf("turn_server.urls empty") + return "", "", nil, 0, fmt.Errorf("turn_server.urls empty") } - log.Printf("[STREAM %d] [VKCalls] TURN credentials получены, адресов=%d", streamID, len(addrs)) - return user, pass, addrs, nil + lifetime := parseVKCallsTURNLifetime(step5, user, time.Now()) + log.Printf("[STREAM %d] [VKCalls] TURN credentials получены, адресов=%d, lifetime=%v", streamID, len(addrs), lifetime.Truncate(time.Second)) + return user, pass, addrs, lifetime, nil } func extractVKCallsString(resp map[string]interface{}, keys ...string) (string, error) { @@ -230,15 +281,52 @@ func parseVKCallsTURNAddresses(resp map[string]interface{}) []string { if !ok { continue } - value = strings.Split(value, "?")[0] - value = strings.TrimPrefix(strings.TrimPrefix(value, "turn:"), "turns:") - if value != "" { - result = append(result, value) + if normalized := normalizeTURNURL(value); normalized != "" { + result = append(result, normalized) } } return result } +func parseVKCallsTURNLifetime(resp map[string]interface{}, username string, now time.Time) time.Duration { + if turnServer, ok := resp["turn_server"].(map[string]interface{}); ok { + for _, key := range []string{"lifetime", "ttl"} { + if seconds := vkCallsPositiveSeconds(turnServer[key]); seconds > 0 { + return time.Duration(seconds) * time.Second + } + } + } + + // TURN REST обычно кодирует срок действия в начале username. + if separator := strings.IndexByte(username, ':'); separator > 0 { + if expiresAt, err := strconv.ParseInt(username[:separator], 10, 64); err == nil { + lifetime := time.Unix(expiresAt, 0).Sub(now) + if lifetime > 0 { + return lifetime + } + } + } + return 0 +} + +func vkCallsPositiveSeconds(value interface{}) int64 { + switch number := value.(type) { + case float64: + if number > 0 { + return int64(number) + } + case json.Number: + if parsed, err := number.Int64(); err == nil && parsed > 0 { + return parsed + } + case string: + if parsed, err := time.ParseDuration(strings.TrimSpace(number) + "s"); err == nil && parsed > 0 { + return int64(parsed / time.Second) + } + } + return 0 +} + func parseVKCallsAPIError(resp map[string]interface{}) error { errObject, ok := resp["error"].(map[string]interface{}) if !ok { @@ -249,6 +337,13 @@ func parseVKCallsAPIError(resp map[string]interface{}) error { if int(code) == 14 { return parseVkCaptchaError(errObject) } + lowerMessage := strings.ToLower(message) + if int(code) == 29 || strings.Contains(lowerMessage, "flood") || strings.Contains(lowerMessage, "rate limit") { + return fmt.Errorf("%w: VK API %.0f: %s", errVKCallsFlood, code, message) + } + if terminal := classifyTerminalVKJoinError(errObject); terminal != nil { + return terminal + } if code != 0 || message != "" { return fmt.Errorf("VK API error %.0f: %s", code, message) } diff --git a/go_client/creds_vkcalls_test.go b/go_client/creds_vkcalls_test.go index a844ba1..5cd2ea3 100644 --- a/go_client/creds_vkcalls_test.go +++ b/go_client/creds_vkcalls_test.go @@ -2,11 +2,34 @@ package main import ( "errors" + "net/url" "reflect" "testing" "time" ) +func TestVKCallsUsesVkRuJoinLink(t *testing.T) { + encoded := vkCallsJoinURL("join-code") + decoded, err := url.QueryUnescape(encoded) + if err != nil { + t.Fatalf("decode join URL: %v", err) + } + if decoded != "https://vk.ru/call/join/join-code" { + t.Fatalf("join URL = %q", decoded) + } +} + +func TestVKCallsUsesVkMeAPIWithCompatibilityFallback(t *testing.T) { + got := vkCallsAPIRequestURLs("/method/test?v=5.276") + want := []string{ + "https://api.vk.me/method/test?v=5.276", + "https://api.vk.ru/method/test?v=5.276", + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("API URLs = %#v, want %#v", got, want) + } +} + func TestStableVKCallsUUID(t *testing.T) { setVKCallsPreflight(true, "device-a") first := stableVKCallsUUID("vk") @@ -30,7 +53,7 @@ func TestParseVKCallsTURNAddresses(t *testing.T) { }, }, } - want := []string{"1.2.3.4:3478", "turn.example:443"} + want := []string{"turn:1.2.3.4:3478?transport=udp", "turns:turn.example:443?transport=tcp"} if got := parseVKCallsTURNAddresses(resp); !reflect.DeepEqual(got, want) { t.Fatalf("addresses = %#v, want %#v", got, want) } @@ -64,6 +87,62 @@ func TestParseVKCallsFloodError(t *testing.T) { } } +func TestParseVKCallsAPIFloodError(t *testing.T) { + err := parseVKCallsAPIError(map[string]interface{}{ + "error": map[string]interface{}{ + "error_code": float64(29), + "error_msg": "Rate limit reached", + }, + }) + if !isVKCallsFloodError(err) { + t.Fatalf("expected VKCalls flood error, got %v", err) + } +} + +func TestParseVKCallsTURNLifetime(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + tests := []struct { + name string + response map[string]interface{} + username string + want time.Duration + }{ + { + name: "lifetime", + response: map[string]interface{}{ + "turn_server": map[string]interface{}{"lifetime": float64(600)}, + }, + want: 10 * time.Minute, + }, + { + name: "ttl", + response: map[string]interface{}{ + "turn_server": map[string]interface{}{"ttl": "300"}, + }, + want: 5 * time.Minute, + }, + { + name: "username expiry", + response: map[string]interface{}{"turn_server": map[string]interface{}{}}, + username: "1700000600:participant", + want: 10 * time.Minute, + }, + { + name: "unknown", + response: map[string]interface{}{}, + username: "participant", + want: 0, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := parseVKCallsTURNLifetime(test.response, test.username, now); got != test.want { + t.Fatalf("lifetime = %v, want %v", got, test.want) + } + }) + } +} + func TestVKCallsFloodPause(t *testing.T) { now := time.Unix(1_700_000_000, 0) startVKCallsFloodPause(now) diff --git a/go_client/dns_resolver.go b/go_client/dns_resolver.go new file mode 100644 index 0000000..57d08fd --- /dev/null +++ b/go_client/dns_resolver.go @@ -0,0 +1,161 @@ +package main + +import ( + "context" + "fmt" + "log" + "net" + "strings" + "time" +) + +const dnsProbeHost = "login.vk.ru" + +type dnsRoute struct { + Label string + Network string + Address string + System bool +} + +type dnsRouteProbe struct { + Route dnsRoute + Err error +} + +type directDNSProbe func(context.Context, dnsRoute, time.Duration) error +type systemDNSProbe func(context.Context, *net.Resolver, time.Duration) error + +func setupGlobalResolver() { + systemResolver := net.DefaultResolver + route, probes := chooseDNSRoute(context.Background(), systemResolver) + if route.System { + logDNSSystemRoute(probes) + return + } + if route.Address == "" { + logDNSUnavailable(probes) + return + } + + log.Printf("[DNS] Прямой DNS %s отвечает для %s; используем его", route.Label, dnsProbeHost) + net.DefaultResolver = fixedDNSResolver(route) +} + +func chooseDNSRoute(ctx context.Context, systemResolver *net.Resolver) (dnsRoute, []dnsRouteProbe) { + return chooseDNSRouteWithProbes(ctx, systemResolver, probeDNSRoute, probeSystemDNS) +} + +func chooseDNSRouteWithProbes( + ctx context.Context, + systemResolver *net.Resolver, + probeDirect directDNSProbe, + probeSystem systemDNSProbe, +) (dnsRoute, []dnsRouteProbe) { + candidates := []dnsRoute{ + {Label: "77.88.8.8 UDP", Network: "udp", Address: "77.88.8.8:53"}, + {Label: "77.88.8.1 UDP", Network: "udp", Address: "77.88.8.1:53"}, + {Label: "77.88.8.8 TCP", Network: "tcp", Address: "77.88.8.8:53"}, + {Label: "77.88.8.1 TCP", Network: "tcp", Address: "77.88.8.1:53"}, + } + + probes := make([]dnsRouteProbe, 0, len(candidates)+1) + for _, route := range candidates { + timeout := 1200 * time.Millisecond + if route.Network == "tcp" { + timeout = 1500 * time.Millisecond + } + err := probeDirect(ctx, route, timeout) + probes = append(probes, dnsRouteProbe{Route: route, Err: err}) + if err == nil { + return route, probes + } + } + + systemRoute := dnsRoute{Label: "системный DNS устройства", System: true} + err := probeSystem(ctx, systemResolver, 1800*time.Millisecond) + probes = append(probes, dnsRouteProbe{Route: systemRoute, Err: err}) + if err == nil { + return systemRoute, probes + } + return dnsRoute{}, probes +} + +func probeDNSRoute(ctx context.Context, route dnsRoute, timeout time.Duration) error { + probeCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + resolver := fixedDNSResolver(route) + return lookupHostWithResolver(probeCtx, resolver, dnsProbeHost) +} + +func probeSystemDNS(ctx context.Context, resolver *net.Resolver, timeout time.Duration) error { + if resolver == nil { + resolver = &net.Resolver{} + } + probeCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return lookupHostWithResolver(probeCtx, resolver, dnsProbeHost) +} + +func fixedDNSResolver(route dnsRoute) *net.Resolver { + dialer := &net.Dialer{ + Timeout: 1200 * time.Millisecond, + KeepAlive: 30 * time.Second, + } + if route.Network == "tcp" { + dialer.Timeout = 1500 * time.Millisecond + } + return &net.Resolver{ + PreferGo: true, + Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { + return dialer.DialContext(ctx, route.Network, route.Address) + }, + } +} + +func lookupHostWithResolver(ctx context.Context, resolver *net.Resolver, host string) error { + addrs, err := resolver.LookupIPAddr(ctx, host) + if err != nil { + return err + } + if len(addrs) == 0 { + return fmt.Errorf("пустой DNS-ответ") + } + return nil +} + +func logDNSSystemRoute(probes []dnsRouteProbe) { + failedDirect := summarizeDNSFailures(probes, false) + if failedDirect == "" { + log.Printf("[DNS] Системный DNS устройства отвечает для %s; используем его", dnsProbeHost) + return + } + log.Printf("[DNS] Прямой DNS клиента недоступен (%s); системный DNS устройства отвечает — используем его", failedDirect) +} + +func logDNSUnavailable(probes []dnsRouteProbe) { + log.Printf("[DNS] DNS до VK недоступен: прямой DNS клиента и системный DNS устройства не ответили (%s)", summarizeDNSFailures(probes, true)) +} + +func summarizeDNSFailures(probes []dnsRouteProbe, includeSystem bool) string { + parts := make([]string, 0, len(probes)) + for _, probe := range probes { + if probe.Err == nil || (!includeSystem && probe.Route.System) { + continue + } + parts = append(parts, probe.Route.Label+": "+shortDNSError(probe.Err)) + } + return strings.Join(parts, "; ") +} + +func shortDNSError(err error) string { + if err == nil { + return "OK" + } + text := strings.ReplaceAll(err.Error(), "\n", " ") + text = strings.ReplaceAll(text, "\r", " ") + if len(text) > 120 { + return text[:120] + "…" + } + return text +} diff --git a/go_client/dns_resolver_test.go b/go_client/dns_resolver_test.go new file mode 100644 index 0000000..44cb67f --- /dev/null +++ b/go_client/dns_resolver_test.go @@ -0,0 +1,91 @@ +package main + +import ( + "context" + "errors" + "io" + "net" + "testing" + "time" +) + +func TestChooseDNSRouteFallsBackToSystemAfterDirectTimeouts(t *testing.T) { + directAttempts := make([]string, 0, 4) + systemAttempts := 0 + + route, probes := chooseDNSRouteWithProbes( + context.Background(), + &net.Resolver{}, + func(_ context.Context, route dnsRoute, _ time.Duration) error { + directAttempts = append(directAttempts, route.Label) + return context.DeadlineExceeded + }, + func(_ context.Context, _ *net.Resolver, _ time.Duration) error { + systemAttempts++ + return nil + }, + ) + + wantAttempts := []string{ + "77.88.8.8 UDP", + "77.88.8.1 UDP", + "77.88.8.8 TCP", + "77.88.8.1 TCP", + } + if len(directAttempts) != len(wantAttempts) { + t.Fatalf("direct attempts = %v, want %v", directAttempts, wantAttempts) + } + for i := range wantAttempts { + if directAttempts[i] != wantAttempts[i] { + t.Fatalf("direct attempts = %v, want %v", directAttempts, wantAttempts) + } + } + if !route.System || route.Label != "системный DNS устройства" { + t.Fatalf("route = %+v, want system resolver", route) + } + if systemAttempts != 1 { + t.Fatalf("system attempts = %d, want 1", systemAttempts) + } + if len(probes) != len(wantAttempts)+1 { + t.Fatalf("probes = %d, want %d", len(probes), len(wantAttempts)+1) + } +} + +func TestLookupHostRequiresDNSResponseFromConnectedSocket(t *testing.T) { + resolver := &net.Resolver{ + PreferGo: true, + Dial: func(context.Context, string, string) (net.Conn, error) { + client, server := net.Pipe() + go func() { + defer server.Close() + _, _ = io.Copy(io.Discard, server) + }() + return client, nil + }, + } + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond) + defer cancel() + + if err := lookupHostWithResolver(ctx, resolver, dnsProbeHost); err == nil { + t.Fatal("connected DNS socket without a response was treated as working") + } +} + +func TestSummarizeDNSFailuresSkipsSystemWhenRequested(t *testing.T) { + probes := []dnsRouteProbe{ + {Route: dnsRoute{Label: "77.88.8.8 UDP"}, Err: errors.New("timeout")}, + {Route: dnsRoute{Label: "системный DNS устройства", System: true}, Err: nil}, + } + got := summarizeDNSFailures(probes, false) + if got != "77.88.8.8 UDP: timeout" { + t.Fatalf("summary = %q", got) + } +} + +func TestShortDNSErrorLimitsLongText(t *testing.T) { + long := "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + got := shortDNSError(errors.New(long)) + if len(got) > 123 { + t.Fatalf("short error too long: %d", len(got)) + } +} diff --git a/go_client/group.go b/go_client/group.go index b9479db..12f083d 100644 --- a/go_client/group.go +++ b/go_client/group.go @@ -12,10 +12,114 @@ import ( ) const ( - workersPerGroup = 9 - defaultCycleSecs = 36000 + workersPerGroup = 9 + defaultCycleSecs = 36000 + defaultWorkerRetryMin = 5 * time.Second + defaultWorkerRetryMax = 15 * time.Second + wrapHandshakeRetryMin = 1 * time.Second + wrapHandshakeRetryMax = 3 * time.Second ) +func workerRetryDelayBounds(err error) (time.Duration, time.Duration) { + if err != nil && strings.Contains(strings.ToUpper(err.Error()), "WRAP_AUTH_TIMEOUT") { + return wrapHandshakeRetryMin, wrapHandshakeRetryMax + } + return defaultWorkerRetryMin, defaultWorkerRetryMax +} + +func workerRetryDelay(err error) time.Duration { + minDelay, maxDelay := workerRetryDelayBounds(err) + steps := int((maxDelay-minDelay)/time.Second) + 1 + return minDelay + time.Duration(rand.Intn(steps))*time.Second +} + +type workerPolicyRetryGate struct { + mu sync.Mutex + blockedUntil time.Time + round int +} + +func workerPolicyRetryDelay(round int) time.Duration { + if round < 1 { + round = 1 + } + delay := time.Duration(3+round*2) * time.Second + if delay > 15*time.Second { + return 15 * time.Second + } + return delay +} + +// wait объединяет одновременные отказы всех воркеров в одно окно повтора. +// Небольшой разброс не даёт девяти DTLS-handshake стартовать в одну миллисекунду. +func (g *workerPolicyRetryGate) wait(ctx context.Context, workerID int) (bool, int, error) { + g.mu.Lock() + now := time.Now() + startedRound := !now.Before(g.blockedUntil) + if startedRound { + g.round++ + g.blockedUntil = now.Add(workerPolicyRetryDelay(g.round)) + } + round := g.round + retryAt := g.blockedUntil.Add(time.Duration(workerID%workersPerGroup) * 250 * time.Millisecond) + g.mu.Unlock() + + wait := time.Until(retryAt) + if wait <= 0 { + return startedRound, round, nil + } + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-timer.C: + return startedRound, round, nil + case <-ctx.Done(): + return startedRound, round, ctx.Err() + } +} + +func (g *workerPolicyRetryGate) reset() { + g.mu.Lock() + g.blockedUntil = time.Time{} + g.round = 0 + g.mu.Unlock() +} + +type configFirstStartGate struct { + enabled bool + ready chan struct{} + once sync.Once +} + +func newConfigFirstStartGate(enabled bool) *configFirstStartGate { + gate := &configFirstStartGate{enabled: enabled} + if enabled { + gate.ready = make(chan struct{}) + } + return gate +} + +func (g *configFirstStartGate) wait(ctx context.Context, workerIndex int) error { + if g == nil || !g.enabled || workerIndex == 0 { + return nil + } + select { + case <-g.ready: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (g *configFirstStartGate) release() { + if g == nil || !g.enabled { + return + } + g.once.Do(func() { + close(g.ready) + }) +} + // WorkerGroup: // Запускает 9 потоков с одними кредами. Ротации нет — работает до смерти воркеров. func WorkerGroup( @@ -30,8 +134,11 @@ func WorkerGroup( getConfig bool, configCh chan<- string, workerIDs []int, + requestedWorkers int, + configFirstStart bool, + hashFallback bool, pauseFlag *int32, - deviceID, password, deviceInfo string, + deviceID, password, deviceInfo, transportSession string, stats *Stats, waitReady <-chan struct{}, signalReady chan<- struct{}, @@ -50,6 +157,9 @@ func WorkerGroup( if !getConfig { configSent = 1 } + configStartGate := newConfigFirstStartGate( + configFirstStart && getConfig && requestedWorkers == workersPerGroup, + ) var signalReadyOnce sync.Once signalNext := func(delay time.Duration, reason string) { @@ -79,15 +189,35 @@ func WorkerGroup( time.Sleep(1 * time.Second) } - hash := tp.Hashes[hashIndex%len(tp.Hashes)] - shortHash := hash - if len(shortHash) > 8 { - shortHash = shortHash[:8] + hashCandidates := []string{tp.Hashes[hashIndex%len(tp.Hashes)]} + if hashFallback && len(tp.Hashes) > 1 { + hashCandidates = make([]string, 0, len(tp.Hashes)) + for offset := 0; offset < len(tp.Hashes); offset++ { + hashCandidates = append( + hashCandidates, + tp.Hashes[(hashIndex+offset)%len(tp.Hashes)], + ) + } } - log.Printf("[ГРУППА #%d] Запрос кредов (хеш: %s...)", groupID, shortHash) + selectedHash := 0 + hash := hashCandidates[selectedHash] + log.Printf("[ГРУППА #%d] Запрос реквизитов подключения", groupID) credStreamID := groupID * 100 user, pass, turnURLs, err := GetCreds(ctx, hash, credStreamID) + for err != nil && + selectedHash+1 < len(hashCandidates) && + isHashFallbackCredentialError(err) { + selectedHash++ + hash = hashCandidates[selectedHash] + log.Printf( + "[ГРУППА #%d] Текущий VK-хеш недоступен; пробуем резерв %d из %d", + groupID, + selectedHash+1, + len(hashCandidates), + ) + user, pass, turnURLs, err = GetCreds(ctx, hash, credStreamID) + } if err != nil && getConfig { log.Printf("[ГРУППА #%d] Стартовые креды не получены: %v; завершаем запуск для чистого повтора", groupID, err) cancel() @@ -119,6 +249,7 @@ func WorkerGroup( var credsMu sync.RWMutex var refreshMu sync.Mutex var lastCredRefresh atomic.Int64 + var policyRetryGate workerPolicyRetryGate refreshCreds := func(reason string) bool { refreshMu.Lock() @@ -131,12 +262,43 @@ func WorkerGroup( return true } - getStreamCache(credStreamID).invalidate(credStreamID) - u, p, urls, refreshErr := GetCreds(ctx, hash, credStreamID) + rotateForTurnFailure := hashFallback && + len(hashCandidates) > 1 && + strings.HasPrefix(strings.ToUpper(strings.TrimSpace(reason)), "TURN") + order := hashRefreshOrder(selectedHash, len(hashCandidates), rotateForTurnFailure) + var ( + u string + p string + urls []string + refreshErr error + nextHashIndex = selectedHash + ) + for attempt, candidateIndex := range order { + candidateHash := hashCandidates[candidateIndex] + if attempt > 0 || candidateIndex != selectedHash { + log.Printf( + "[ГРУППА #%d] Пробуем резервный VK-хеш %d из %d после ошибки TURN", + groupID, + candidateIndex+1, + len(hashCandidates), + ) + } + getStreamCache(credStreamID).invalidate(credStreamID) + u, p, urls, refreshErr = GetCreds(ctx, candidateHash, credStreamID) + if refreshErr == nil { + nextHashIndex = candidateIndex + break + } + if !isHashFallbackCredentialError(refreshErr) { + break + } + } if refreshErr != nil { log.Printf("[TURN] Не удалось обновить креды после %s: %v", reason, refreshErr) return false } + selectedHash = nextHashIndex + hash = hashCandidates[selectedHash] credsMu.Lock() creds = &Credentials{User: u, Pass: p, TurnURLs: urls, CacheStreamID: credStreamID} @@ -155,9 +317,13 @@ func WorkerGroup( // Stagger: 500мс между воркерами workerDelay := time.Duration(i) * 500 * time.Millisecond - go func(wid int, delay time.Duration) { + go func(workerIndex, wid int, delay time.Duration) { defer wg.Done() + if err := configStartGate.wait(ctx, workerIndex); err != nil { + return + } + if delay > 0 { select { case <-time.After(delay): @@ -182,6 +348,15 @@ func WorkerGroup( if getConf { cc = configCh } + requireConfig := configStartGate.enabled && getConf + var onConfigDelivered func() + if requireConfig { + onConfigDelivered = func() { + atomic.StoreInt32(&configSent, 1) + configStartGate.release() + log.Printf("[ГРУППА #%d] Новое подключение зарегистрировано; запускаем остальные воркеры", groupID) + } + } credsMu.RLock() credsSnapshot := *creds @@ -189,7 +364,9 @@ func WorkerGroup( credsMu.RUnlock() configDelivered, sessErr := RunSession(ctx, tp, peer, d, localPort, - getConf, cc, wid, &credsSnapshot, deviceID, password, deviceInfo, stats) + getConf, cc, requireConfig, onConfigDelivered, wid, &credsSnapshot, + deviceID, password, deviceInfo, + transportSession, stats) if getConf { if configDelivered { @@ -203,6 +380,27 @@ func WorkerGroup( if ctx.Err() != nil { return } + if maxWorkers, limited := workerPolicyLimit(sessErr); limited { + if shouldRetryWorkerPolicy(maxWorkers, requestedWorkers) { + startedRound, round, waitErr := policyRetryGate.wait(ctx, wid) + if startedRound && (round == 1 || round%6 == 0) { + log.Printf( + "[МОЩНОСТЬ] Лимит временно занят другими потоками этого доступа (максимум: %d); повторяем подключение", + maxWorkers, + ) + } + if waitErr != nil { + return + } + continue + } + log.Printf( + "[МОЩНОСТЬ] Сервер остановил лишний поток согласно ограничению доступа (максимум: %d)", + maxWorkers, + ) + return + } + policyRetryGate.reset() errStr := sessErr.Error() errStrLower := strings.ToLower(errStr) @@ -255,14 +453,14 @@ func WorkerGroup( return } - retryDelay := time.Duration(5+rand.Intn(11)) * time.Second + retryDelay := workerRetryDelay(sessErr) select { case <-time.After(retryDelay): case <-ctx.Done(): return } } - }(wid, workerDelay) + }(i, wid, workerDelay) } wg.Wait() @@ -280,6 +478,32 @@ func isTerminalGroupCredentialError(err error) bool { strings.Contains(message, "FATAL_AUTH") } +func isHashFallbackCredentialError(err error) bool { + if err == nil { + return false + } + message := strings.ToUpper(err.Error()) + return strings.Contains(message, "INVALID_JOIN_LINK") || + strings.Contains(message, "ANON_BLOCKED") || + strings.Contains(message, "CALL_FULL") +} + +func hashRefreshOrder(current, total int, rotate bool) []int { + if total <= 0 { + return nil + } + current = ((current % total) + total) % total + start := current + if rotate && total > 1 { + start = (current + 1) % total + } + order := make([]int, 0, total) + for offset := 0; offset < total; offset++ { + order = append(order, (start+offset)%total) + } + return order +} + func groupCredentialRetryDelay(err error) time.Duration { if err != nil { message := strings.ToUpper(err.Error()) diff --git a/go_client/group_test.go b/go_client/group_test.go index c18b6ae..d83c1a2 100644 --- a/go_client/group_test.go +++ b/go_client/group_test.go @@ -1,7 +1,9 @@ package main import ( + "context" "errors" + "reflect" "testing" "time" ) @@ -17,12 +19,106 @@ func TestTerminalGroupCredentialErrors(t *testing.T) { } } +func TestManagedHashFallbackUsesOnlyHashSpecificFailures(t *testing.T) { + for _, message := range []string{"INVALID_JOIN_LINK", "ANON_BLOCKED", "CALL_FULL"} { + if !isHashFallbackCredentialError(errors.New(message)) { + t.Fatalf("%q must try the next managed-profile hash", message) + } + } + for _, message := range []string{"CAPTCHA_WAIT_REQUIRED", "VK HTTPS timeout", "FATAL_AUTH"} { + if isHashFallbackCredentialError(errors.New(message)) { + t.Fatalf("%q must not fan out across all hashes", message) + } + } +} + +func TestHashRefreshOrderRotatesReserveAfterTurnFailure(t *testing.T) { + got := hashRefreshOrder(0, 4, true) + want := []int{1, 2, 3, 0} + if !reflect.DeepEqual(got, want) { + t.Fatalf("rotated order = %v, want %v", got, want) + } + + got = hashRefreshOrder(2, 4, false) + want = []int{2, 3, 0, 1} + if !reflect.DeepEqual(got, want) { + t.Fatalf("regular refresh order = %v, want %v", got, want) + } +} + func TestCaptchaCredentialRetryDelay(t *testing.T) { if got := groupCredentialRetryDelay(errors.New("CAPTCHA_WAIT_REQUIRED")); got != 90*time.Second { t.Fatalf("captcha retry delay = %v", got) } } +func TestWorkerPolicyRetryDelayIsBounded(t *testing.T) { + if got := workerPolicyRetryDelay(1); got != 5*time.Second { + t.Fatalf("first policy retry delay = %v", got) + } + if got := workerPolicyRetryDelay(100); got != 15*time.Second { + t.Fatalf("maximum policy retry delay = %v", got) + } +} + +func TestWrapHandshakeRetryUsesShortDedicatedWindow(t *testing.T) { + minDelay, maxDelay := workerRetryDelayBounds( + errors.New("WRAP_AUTH_TIMEOUT: отдельный DTLS-канал не ответил вовремя"), + ) + if minDelay != time.Second || maxDelay != 3*time.Second { + t.Fatalf("WRAP retry bounds = %v..%v, want 1s..3s", minDelay, maxDelay) + } + + minDelay, maxDelay = workerRetryDelayBounds(errors.New("TURN Allocate timeout")) + if minDelay != 5*time.Second || maxDelay != 15*time.Second { + t.Fatalf("regular retry bounds = %v..%v, want 5s..15s", minDelay, maxDelay) + } +} + +func TestWrapHandshakeTimeoutAllowsFourFlightsBeforeFastRetry(t *testing.T) { + if got := dtlsHandshakeTimeout(true); got != 8*time.Second { + t.Fatalf("WRAP handshake timeout = %v, want 8s", got) + } + if got := dtlsHandshakeTimeout(false); got != 20*time.Second { + t.Fatalf("regular handshake timeout = %v, want 20s", got) + } +} + +func TestConfigFirstStartGateOnlyBlocksFollowingWorkersWhenEnabled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + regular := newConfigFirstStartGate(false) + if err := regular.wait(ctx, 1); err != nil { + t.Fatalf("regular start path was blocked: %v", err) + } + + managed := newConfigFirstStartGate(true) + if err := managed.wait(ctx, 0); err != nil { + t.Fatalf("config worker was blocked: %v", err) + } + + waitDone := make(chan error, 1) + go func() { + waitDone <- managed.wait(ctx, 1) + }() + select { + case err := <-waitDone: + t.Fatalf("following worker passed before GETCONF: %v", err) + case <-time.After(20 * time.Millisecond): + } + + managed.release() + select { + case err := <-waitDone: + if err != nil { + t.Fatalf("following worker failed after GETCONF: %v", err) + } + case <-time.After(time.Second): + t.Fatal("following worker did not start after GETCONF") + } +} + func TestWebViewTimeoutOrdering(t *testing.T) { if captchaAutoWebViewTimeout <= 18*time.Second { t.Fatalf("Go auto timeout %v must exceed Android WebView timeout", captchaAutoWebViewTimeout) diff --git a/go_client/main.go b/go_client/main.go index 1d2688b..c07e90e 100644 --- a/go_client/main.go +++ b/go_client/main.go @@ -3,6 +3,8 @@ package main import ( "bufio" "context" + "crypto/rand" + "encoding/hex" "flag" "fmt" "log" @@ -122,14 +124,22 @@ func classifyHashCheckError(err error) (string, string) { switch { case strings.Contains(text, "captcha_required") || strings.Contains(text, "captcha_wait_required"): return "captcha", "VK просит капчу" - case strings.Contains(text, "call not found") || - strings.Contains(text, "joinconversationbylink") || - strings.Contains(text, "missing turn_server") || - strings.Contains(text, "9000"): + case strings.Contains(text, "invalid_join_link") || + strings.Contains(text, "call not found") || + strings.Contains(text, "join link is not valid") || + strings.Contains(text, "error 9000") || + strings.Contains(text, "error 9008") || + strings.Contains(text, "error_code:9000") || + strings.Contains(text, "error_code:9008"): return "dead", "Звонок не найден или закрыт" + case strings.Contains(text, "anon_blocked") || strings.Contains(text, "anonymous join is disabled"): + return "blocked", "В звонке запрещён анонимный вход" + case strings.Contains(text, "call_full") || strings.Contains(text, "call is full"): + return "full", "В звонке сейчас нет свободных мест" case strings.Contains(text, "flood") || strings.Contains(text, "rate limit") || strings.Contains(text, "error_code:29"): return "limited", "VK временно ограничил запросы" - case strings.Contains(text, "timeout") || strings.Contains(text, "deadline") || strings.Contains(text, "lookup") || strings.Contains(text, "network"): + case strings.Contains(text, "timeout") || strings.Contains(text, "deadline") || strings.Contains(text, "lookup") || + strings.Contains(text, "network") || strings.Contains(text, "vk https"): return "network", "Сетевая ошибка" default: return "error", err.Error() @@ -257,21 +267,23 @@ func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) - if !strings.Contains(line, "error:tunnel stopped") { - log.Printf("[STDIN] %s", line) - } switch { case line == "PAUSE": + log.Printf("[STDIN] Команда PAUSE") atomic.StoreInt32(&pauseFlag, 1) case line == "RESUME": + log.Printf("[STDIN] Команда RESUME") atomic.StoreInt32(&pauseFlag, 0) case line == "STOP": + log.Printf("[STDIN] Команда STOP") cancel() return case strings.HasPrefix(line, "CAPTCHA_RESULT|"): result := parseCaptchaResultPayload(strings.TrimPrefix(line, "CAPTCHA_RESULT|")) enqueueCaptchaResult(result) log.Printf("[КАПЧА] Результат от Kotlin принят (request=%q)", result.RequestID) + default: + log.Printf("[STDIN] Неизвестная команда проигнорирована") } } }() @@ -293,9 +305,20 @@ func main() { peerAddr := flag.String("peer", "", "адрес:порт VPS сервера") numW := flag.Int("n", 24, "количество воркеров (кратно 9)") checkHashes := flag.Bool("check-hashes", false, "проверить VK-хеши и выйти") + configFirstStart := flag.Bool( + "config-first-start", + false, + "дождаться GETCONF перед запуском остальных воркеров единственной группы", + ) + hashFallback := flag.Bool( + "hash-fallback", + false, + "использовать остальные VK-хеши как резерв единственной группы", + ) deviceID := flag.String("device-id", "unknown", "уникальный ID устройства") deviceInfo := flag.String("device-info", "", "JSON с безопасной информацией об устройстве") + transportSessionFlag := flag.String("transport-session", "", "поколение текущего запуска транспорта") connPassword := flag.String("password", "", "пароль подключения") captchaMode := flag.String("captcha-mode", "auto", "режим обхода капчи (auto/wv/rjs)") vkCallsPreflight := flag.Bool("vkcalls-preflight", true, "пробовать VKCalls до captcha-цепочки") @@ -303,6 +326,10 @@ func main() { clientIdsFlag := flag.String("client-ids", "", "ID клиентов VK через запятую") flag.Parse() + transportSession := normalizeTransportSession(*transportSessionFlag) + if transportSession == "" { + transportSession = newTransportSession() + } activeCaptchaMode := setCaptchaMode(*captchaMode) setVKCallsPreflight(*vkCallsPreflight, *deviceID) @@ -313,9 +340,18 @@ func main() { if *fingerprint != "" { SetActiveFingerprint(*fingerprint) } + customClientID := os.Getenv("WDTT_CUSTOM_VK_CLIENT_ID") + customClientSecret := os.Getenv("WDTT_CUSTOM_VK_CLIENT_SECRET") + _ = os.Unsetenv("WDTT_CUSTOM_VK_CLIENT_ID") + _ = os.Unsetenv("WDTT_CUSTOM_VK_CLIENT_SECRET") if *clientIdsFlag != "" { SetActiveClientIds(*clientIdsFlag) } + if customClientID != "" || customClientSecret != "" { + if err := SetCustomVKCredentials(customClientID, customClientSecret); err != nil { + log.Fatalf("[КЛИЕНТ] Некорректные пользовательские реквизиты VK: %v", err) + } + } hashes := ParseHashes(*vkHash) if len(hashes) == 0 { @@ -365,6 +401,8 @@ func main() { *numW = workersPerGroup } *numW = (*numW / workersPerGroup) * workersPerGroup + useConfigFirstStart := *configFirstStart && *numW == workersPerGroup + useHashFallback := *hashFallback && *numW == workersPerGroup tp := &TurnParams{ Host: *host, @@ -429,7 +467,7 @@ func main() { log.Printf("[КЛИЕНТ] Протокол: UDP") log.Printf("[КЛИЕНТ] WRAP: %s", wrapStatus) log.Printf("[WRAP] Ключ выведен из пароля, режим RTP AEAD активен") - log.Printf("[КЛИЕНТ] Device ID: %s", *deviceID) + log.Printf("[КЛИЕНТ] Идентификатор устройства инициализирован") log.Printf("[КЛИЕНТ] Captcha: %s", captchaStatus) log.Println("[КЛИЕНТ] ═══════════════════════════════════════") @@ -516,7 +554,8 @@ func main() { go func(groupID int, isFirstGroup bool, configChan chan<- string, workerIds []int, startHashIndex int, waitR <-chan struct{}, sigR chan<- struct{}) { defer wg.Done() WorkerGroup(ctx, cancel, groupID, startHashIndex, tp, peer, disp, localPort, - isFirstGroup, configChan, workerIds, &pauseFlag, *deviceID, *connPassword, *deviceInfo, stats, waitR, sigR) + isFirstGroup, configChan, workerIds, *numW, useConfigFirstStart, useHashFallback, &pauseFlag, + *deviceID, *connPassword, *deviceInfo, transportSession, stats, waitR, sigR) }(gID, isFirst, cc, ids, g, myWaitReady, mySignalReady) } @@ -525,3 +564,28 @@ func main() { <-configDone log.Println("[КЛИЕНТ] Все воркеры завершены") } + +func newTransportSession() string { + var value [16]byte + if _, err := rand.Read(value[:]); err == nil { + return hex.EncodeToString(value[:]) + } + return fmt.Sprintf("fallback-%d-%d", time.Now().UnixNano(), os.Getpid()) +} + +func normalizeTransportSession(value string) string { + value = strings.TrimSpace(value) + if len(value) < 16 || len(value) > 64 { + return "" + } + for _, char := range value { + if (char >= 'a' && char <= 'z') || + (char >= 'A' && char <= 'Z') || + (char >= '0' && char <= '9') || + char == '-' || char == '_' { + continue + } + return "" + } + return value +} diff --git a/go_client/protocol.go b/go_client/protocol.go index dcecc60..07f4af3 100644 --- a/go_client/protocol.go +++ b/go_client/protocol.go @@ -1,37 +1,49 @@ package main import ( + "context" + "errors" "fmt" "net" + "strconv" "strings" "time" ) -// RequestConfig запрашивает WireGuard конфиг через DTLS-соединение. -func RequestConfig(conn net.Conn, localPort, deviceID, password, deviceInfo string) (string, error) { - payload := fmt.Sprintf("GETCONF:%s|%s|%s", localPort, deviceID, password) - if strings.TrimSpace(deviceInfo) != "" { - payload += "|" + strings.ReplaceAll(deviceInfo, "|", " ") - } - if _, err := conn.Write([]byte(payload)); err != nil { - return "", fmt.Errorf("отправка GETCONF: %w", err) - } +type workerPolicyLimitError struct { + maxWorkers int +} - b := make([]byte, 4096) - if err := conn.SetReadDeadline(time.Now().Add(15 * time.Second)); err != nil { - return "", fmt.Errorf("установка дедлайна: %w", err) - } - n, err := conn.Read(b) - _ = conn.SetReadDeadline(time.Time{}) - if err != nil { - return "", fmt.Errorf("чтение ответа конфига: %w", err) - } +func (e *workerPolicyLimitError) Error() string { + return fmt.Sprintf("WORKER_POLICY_LIMIT:%d", e.maxWorkers) +} - resp := string(b[:n]) +func workerPolicyLimit(err error) (int, bool) { + var policyError *workerPolicyLimitError + if !errors.As(err, &policyError) { + return 0, false + } + return policyError.maxWorkers, true +} + +func shouldRetryWorkerPolicy(maxWorkers, requestedWorkers int) bool { + return requestedWorkers > 0 && maxWorkers >= requestedWorkers +} + +func parseConfigResponse(resp string) (string, error) { if resp == "NOCONF" { return "", nil } + if strings.HasPrefix(resp, "POLICY:max_workers=") { + value := strings.TrimSpace(strings.TrimPrefix(resp, "POLICY:max_workers=")) + maxWorkers, err := strconv.Atoi(value) + if err != nil || maxWorkers < 1 || maxWorkers > 128 { + return "", fmt.Errorf("некорректная политика мощности сервера") + } + return "", &workerPolicyLimitError{maxWorkers: maxWorkers} + } + if strings.HasPrefix(resp, "DENIED:") { reason := strings.TrimPrefix(resp, "DENIED:") switch reason { @@ -48,3 +60,39 @@ func RequestConfig(conn net.Conn, localPort, deviceID, password, deviceInfo stri return resp, nil } + +// RequestConfig запрашивает WireGuard конфиг через DTLS-соединение. +func RequestConfig( + ctx context.Context, + conn net.Conn, + localPort, deviceID, password, deviceInfo, transportSession string, +) (string, error) { + payload := fmt.Sprintf("GETCONF:%s|%s|%s", localPort, deviceID, password) + safeDeviceInfo := strings.ReplaceAll(strings.TrimSpace(deviceInfo), "|", " ") + safeTransportSession := normalizeTransportSession(transportSession) + if safeDeviceInfo != "" || safeTransportSession != "" { + payload += "|" + safeDeviceInfo + } + if safeTransportSession != "" { + payload += "|" + safeTransportSession + } + if _, err := conn.Write([]byte(payload)); err != nil { + return "", fmt.Errorf("отправка GETCONF: %w", err) + } + + b := make([]byte, 4096) + if err := conn.SetReadDeadline(time.Now().Add(15 * time.Second)); err != nil { + return "", fmt.Errorf("установка дедлайна: %w", err) + } + stopRead := context.AfterFunc(ctx, func() { + _ = conn.SetReadDeadline(time.Now()) + }) + defer stopRead() + n, err := conn.Read(b) + _ = conn.SetReadDeadline(time.Time{}) + if err != nil { + return "", fmt.Errorf("чтение ответа конфига: %w", err) + } + + return parseConfigResponse(string(b[:n])) +} diff --git a/go_client/protocol_test.go b/go_client/protocol_test.go new file mode 100644 index 0000000..acf57bc --- /dev/null +++ b/go_client/protocol_test.go @@ -0,0 +1,126 @@ +package main + +import ( + "context" + "net" + "strings" + "testing" + "time" +) + +func TestParseConfigResponseWorkerPolicyLimit(t *testing.T) { + config, err := parseConfigResponse("POLICY:max_workers=12") + if config != "" { + t.Fatalf("expected no config, got %q", config) + } + maxWorkers, limited := workerPolicyLimit(err) + if !limited || maxWorkers != 12 { + t.Fatalf("expected worker policy limit 12, got limit=%d error=%v", maxWorkers, err) + } +} + +func TestParseConfigResponseRejectsMalformedWorkerPolicy(t *testing.T) { + _, err := parseConfigResponse("POLICY:max_workers=none") + if err == nil || !strings.Contains(err.Error(), "некорректная политика") { + t.Fatalf("expected malformed policy error, got %v", err) + } +} + +func TestParseConfigResponseKeepsRegularConfig(t *testing.T) { + const config = "[Interface]\nAddress=10.0.0.2/32" + parsed, err := parseConfigResponse(config) + if err != nil || parsed != config { + t.Fatalf("regular config changed: parsed=%q error=%v", parsed, err) + } +} + +func TestWorkerPolicyRetriesOnlyWhenTheRequestedProfileFits(t *testing.T) { + if !shouldRetryWorkerPolicy(12, 9) { + t.Fatal("a nine-worker profile must recover after transient old sessions release") + } + if shouldRetryWorkerPolicy(12, 18) { + t.Fatal("a profile above the server policy must not retry rejected workers forever") + } +} + +func TestRequestConfigIncludesTransportSessionCompatibly(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + payload := make(chan string, 1) + go func() { + buffer := make([]byte, 4096) + n, err := server.Read(buffer) + if err != nil { + payload <- "read-error" + return + } + payload <- string(buffer[:n]) + _, _ = server.Write([]byte("NOCONF")) + }() + + config, err := RequestConfig( + context.Background(), + client, + "9000", + "android-device", + "secret", + `{"name":"Phone"}`, + "transport-session-0001", + ) + if err != nil || config != "" { + t.Fatalf("request failed: config=%q error=%v", config, err) + } + if got := <-payload; got != `GETCONF:9000|android-device|secret|{"name":"Phone"}|transport-session-0001` { + t.Fatalf("unexpected request payload: %q", got) + } +} + +func TestRequestConfigStopsWaitingWhenTransportIsCancelled(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + + ctx, cancel := context.WithCancel(context.Background()) + requestDone := make(chan error, 1) + go func() { + _, err := RequestConfig( + ctx, + client, + "9000", + "android-device", + "secret", + "", + "transport-session-0001", + ) + requestDone <- err + }() + + buffer := make([]byte, 4096) + if _, err := server.Read(buffer); err != nil { + t.Fatalf("server did not receive GETCONF: %v", err) + } + cancel() + + select { + case err := <-requestDone: + if err == nil { + t.Fatal("cancelled GETCONF unexpectedly succeeded") + } + case <-time.After(time.Second): + t.Fatal("cancelled GETCONF kept waiting") + } +} + +func TestTransportSessionNormalization(t *testing.T) { + generated := newTransportSession() + if normalizeTransportSession(generated) != generated { + t.Fatalf("generated transport session is invalid: %q", generated) + } + if normalizeTransportSession("too-short") != "" { + t.Fatal("short transport session was accepted") + } + if normalizeTransportSession("invalid transport session") != "" { + t.Fatal("transport session with spaces was accepted") + } +} diff --git a/go_client/session.go b/go_client/session.go index 8d8e2d2..b3f66c5 100644 --- a/go_client/session.go +++ b/go_client/session.go @@ -27,11 +27,20 @@ const ( socketBufSize = 625 * 1024 keepaliveByte = 0xFF // DTLS-level keepalive marker keepaliveInterval = 15 * time.Second + defaultHandshakeTimeout = 20 * time.Second + wrapHandshakeTimeout = 8 * time.Second ) // Handshake semaphore: limit to 3 concurrent DTLS handshakes var handshakeSem = make(chan struct{}, 3) +func dtlsHandshakeTimeout(useWrap bool) time.Duration { + if useWrap { + return wrapHandshakeTimeout + } + return defaultHandshakeTimeout +} + // NullLoggerFactory подавляет логи pion type NullLoggerFactory struct{} @@ -55,53 +64,57 @@ type connectedUDPConn struct{ *net.UDPConn } func (c *connectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) { return c.Write(p) } -func RunSession( +func openTURNAllocation( ctx context.Context, - tp *TurnParams, + endpoint turnEndpoint, peer *net.UDPAddr, - d *Dispatcher, - localPort string, - getConfig bool, - configCh chan<- string, - sessionID int, creds *Credentials, - deviceID, password, deviceInfo string, - stats *Stats, -) (bool, error) { - configDelivered := false + sessionID int, +) (*turn.Client, net.PacketConn, error) { + turnAddr := endpoint.address() - if len(creds.TurnURLs) == 0 { - return false, fmt.Errorf("нет TURN URL в учетных данных") + 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) + if err != nil { + return nil, nil, fmt.Errorf("TURN UDP подключение %s: %w", turnAddr, err) + } + _ = c.SetReadBuffer(socketBufSize) + _ = c.SetWriteBuffer(socketBufSize) + turnConn = &connectedUDPConn{c} + case turnTransportTCP: + dialCtx, cancel := context.WithTimeout(ctx, 6*time.Second) + defer cancel() + dialer := &net.Dialer{Timeout: 6 * time.Second, KeepAlive: 30 * time.Second} + conn, err := dialer.DialContext(dialCtx, "tcp", turnAddr) + if err != nil { + return nil, nil, fmt.Errorf("TURN TCP подключение %s: %w", turnAddr, err) + } + turnConn = turn.NewSTUNConn(conn) + case turnTransportTLS: + dialCtx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12} + if net.ParseIP(endpoint.Host) == nil { + tlsConfig.ServerName = endpoint.Host + } + dialer := &tls.Dialer{ + NetDialer: &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second}, + Config: tlsConfig, + } + conn, err := dialer.DialContext(dialCtx, "tcp", turnAddr) + if err != nil { + return nil, nil, fmt.Errorf("TURN TLS подключение %s: %w", turnAddr, err) + } + turnConn = turn.NewSTUNConn(conn) + default: + return nil, nil, fmt.Errorf("неподдерживаемый TURN transport: %s", endpoint.Transport) } - selectedURL := creds.TurnURLs[sessionID%len(creds.TurnURLs)] - - urlhost, urlport, err := net.SplitHostPort(selectedURL) - if err != nil { - return false, fmt.Errorf("разбор TURN URL %q: %w", selectedURL, err) - } - if tp.Host != "" { - urlhost = tp.Host - } - if tp.Port != "" { - urlport = tp.Port - } - turnAddr := net.JoinHostPort(urlhost, urlport) - - // Транспорт: всегда UDP - resolved, err := net.ResolveUDPAddr("udp", turnAddr) - if err != nil { - return false, fmt.Errorf("резолв TURN: %w", err) - } - c, err := net.DialUDP("udp", nil, resolved) - if err != nil { - return false, fmt.Errorf("подключение TURN UDP: %w", err) - } - defer c.Close() - _ = c.SetReadBuffer(socketBufSize) - _ = c.SetWriteBuffer(socketBufSize) - var turnConn net.PacketConn = &connectedUDPConn{c} - - log.Printf("[СЕССИЯ #%d] TURN UDP (%s)", sessionID, turnAddr) // RequestedAddressFamily var addrFamily turn.RequestedAddressFamily @@ -111,7 +124,6 @@ func RunSession( addrFamily = turn.RequestedAddressFamilyIPv6 } - // TURN Client (pion/turn/v5) tc, err := turn.NewClient(&turn.ClientConfig{ STUNServerAddr: turnAddr, TURNServerAddr: turnAddr, @@ -122,12 +134,13 @@ func RunSession( LoggerFactory: &NullLoggerFactory{}, }) if err != nil { - return false, fmt.Errorf("TURN клиент: %w", err) + _ = turnConn.Close() + return nil, nil, fmt.Errorf("TURN %s клиент %s: %w", endpoint.label(), turnAddr, err) } - defer tc.Close() if err = tc.Listen(); err != nil { - return false, fmt.Errorf("TURN Listen: %w", err) + tc.Close() + return nil, nil, fmt.Errorf("TURN %s Listen %s: %w", endpoint.label(), turnAddr, err) } relay, err := tc.Allocate() @@ -137,16 +150,88 @@ func RunSession( } errStr := err.Error() if strings.Contains(errStr, "Quota") || strings.Contains(errStr, "486") { - return false, fmt.Errorf("TURN квота: %w", err) + tc.Close() + return nil, nil, fmt.Errorf("TURN квота: %w", err) } - return false, fmt.Errorf("TURN Allocate: %w", err) + tc.Close() + return nil, nil, fmt.Errorf("TURN %s Allocate %s: %w", endpoint.label(), turnAddr, err) } + + return tc, relay, nil +} + +func isCredentialTURNError(err error) bool { + if err == nil { + return false + } + text := strings.ToLower(err.Error()) + return strings.Contains(text, "turn квота") || + strings.Contains(text, "turn allocate auth") || + strings.Contains(text, "invalid credential") || + strings.Contains(text, "stale nonce") || + strings.Contains(text, "allocation mismatch") || + strings.Contains(text, "attribute not found") || + strings.Contains(text, "error 508") || + strings.Contains(text, "quota") +} + +func RunSession( + ctx context.Context, + tp *TurnParams, + peer *net.UDPAddr, + d *Dispatcher, + localPort string, + getConfig bool, + configCh chan<- string, + requireConfig bool, + onConfigDelivered func(), + sessionID int, + creds *Credentials, + deviceID, password, deviceInfo, transportSession string, + stats *Stats, +) (bool, error) { + configDelivered := false + + if len(creds.TurnURLs) == 0 { + return false, fmt.Errorf("нет TURN URL в учетных данных") + } + candidates := sessionTURNCandidates(creds.TurnURLs, sessionID, tp) + if len(candidates) == 0 { + return false, fmt.Errorf("нет пригодных TURN URL в учетных данных") + } + + var tc *turn.Client + var relay net.PacketConn + var selectedEndpoint turnEndpoint + var lastTURNErr error + var err error + for idx, candidate := range candidates { + if idx == 0 { + log.Printf("[СЕССИЯ #%d] TURN %s (%s)", sessionID, candidate.label(), candidate.address()) + } else { + log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s) после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr) + } + + tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID) + if err == nil { + selectedEndpoint = candidate + break + } + lastTURNErr = err + if isCredentialTURNError(err) { + return false, err + } + } + if lastTURNErr != nil && relay == nil { + return false, lastTURNErr + } + defer tc.Close() defer relay.Close() // Reset error count on successful allocation getStreamCache(creds.CacheStreamID).errorCount.Store(0) - log.Printf("[СЕССИЯ #%d] Relay: %s", sessionID, relay.LocalAddr()) + log.Printf("[СЕССИЯ #%d] Relay: %s через TURN %s", sessionID, relay.LocalAddr(), selectedEndpoint.label()) // Pipe для DTLS ↔ TURN relay pipeA, pipeB := connutil.AsyncPacketPipe() @@ -279,7 +364,7 @@ func RunSession( } defer dtlsConn.Close() - hctx, hcancel := context.WithTimeout(sessCtx, 20*time.Second) + hctx, hcancel := context.WithTimeout(sessCtx, dtlsHandshakeTimeout(useWrap)) log.Printf("[ВОРКЕР #%d] [DTLS] Рукопожатие (Handshake)...", sessionID) err = dtlsConn.HandshakeContext(hctx) hcancel() @@ -289,13 +374,21 @@ func RunSession( if useWrap { errStr := strings.ToLower(err.Error()) if strings.Contains(errStr, "deadline") || strings.Contains(errStr, "timeout") { - return false, fmt.Errorf("WRAP_AUTH_TIMEOUT: DTLS timeout, пароль/WRAP не подтверждён") + return false, fmt.Errorf("WRAP_AUTH_TIMEOUT: отдельный DTLS-канал не ответил вовремя") } } - return false, fmt.Errorf("DTLS хендшейк: %w", err) + return false, fmt.Errorf("DTLS хендшейк до VPS %s не прошёл: %w", peer.String(), err) } log.Printf("[ВОРКЕР #%d] [DTLS] Соединение установлено ✓", sessionID) + // Отмена должна прерывать и стартовый GETCONF. Раньше deadline + // устанавливался только после получения конфига, поэтому остановка во время + // подключения могла ждать принудительного завершения процесса на Android. + stopDTLS := context.AfterFunc(sessCtx, func() { + _ = dtlsConn.SetDeadline(time.Now()) + }) + defer stopDTLS() + stats.ActiveConnections.Add(1) globalActiveConnections.Add(1) defer func() { @@ -305,12 +398,26 @@ func RunSession( // Запрос конфига if getConfig && configCh != nil { - conf, confErr := RequestConfig(dtlsConn, localPort, deviceID, password, deviceInfo) + conf, confErr := RequestConfig( + sessCtx, + dtlsConn, + localPort, + deviceID, + password, + deviceInfo, + transportSession, + ) if confErr != nil { + if _, limited := workerPolicyLimit(confErr); limited { + return false, confErr + } errStr := confErr.Error() if strings.Contains(errStr, "FATAL_AUTH") { return false, confErr } + if requireConfig { + return false, fmt.Errorf("регистрация нового подключения: %w", confErr) + } log.Printf("[ВОРКЕР #%d] Ошибка конфига: %v", sessionID, confErr) } else if conf != "" { select { @@ -321,7 +428,13 @@ func RunSession( configDelivered = true log.Printf("[ВОРКЕР #%d] Конфиг уже был доставлен другим воркером", sessionID) } + if onConfigDelivered != nil { + onConfigDelivered() + } } else { + if requireConfig { + return false, fmt.Errorf("сервер ещё не выдал WireGuard-конфиг") + } log.Printf("[ВОРКЕР #%d] Сервер ещё не выдал WireGuard-конфиг, повторим позже", sessionID) } } @@ -340,16 +453,12 @@ func RunSession( lastServerRxAt.Store(time.Now().UnixNano()) var lastUserTrafficAt atomic.Int64 var keepalivePongSeen atomic.Int32 + policyLimitCh := make(chan int, 1) // Proxy DTLS ↔ Dispatcher var proxyWg sync.WaitGroup proxyWg.Add(4) // writer + reader + keepalive + health monitor - stopDTLS := context.AfterFunc(sessCtx, func() { - _ = dtlsConn.SetDeadline(time.Now()) - }) - defer stopDTLS() - // DTLS Keepalive: prevents TURN allocation timeout and DTLS idle disconnect go func() { defer proxyWg.Done() @@ -448,6 +557,17 @@ func RunSession( lastServerRxAt.Store(time.Now().UnixNano()) + if _, policyErr := parseConfigResponse(string(pkt[:n])); policyErr != nil { + if maxWorkers, limited := workerPolicyLimit(policyErr); limited { + select { + case policyLimitCh <- maxWorkers: + default: + } + putPktBuf(pkt) + return + } + } + // Skip keepalive pong from server if n == 1 && pkt[0] == keepaliveByte { keepalivePongSeen.Store(1) @@ -472,5 +592,10 @@ func RunSession( _ = pipeA.Close() _ = pipeB.Close() log.Printf("[СЕССИЯ #%d] Завершена", sessionID) + select { + case maxWorkers := <-policyLimitCh: + return configDelivered, &workerPolicyLimitError{maxWorkers: maxWorkers} + default: + } return configDelivered, nil } diff --git a/go_client/turn_endpoint.go b/go_client/turn_endpoint.go new file mode 100644 index 0000000..29095d9 --- /dev/null +++ b/go_client/turn_endpoint.go @@ -0,0 +1,192 @@ +package main + +import ( + "fmt" + "net" + neturl "net/url" + "strings" +) + +type turnTransport string + +const ( + turnTransportUDP turnTransport = "udp" + turnTransportTCP turnTransport = "tcp" + turnTransportTLS turnTransport = "tls" +) + +type turnEndpoint struct { + Raw string + Host string + Port string + Scheme string + Transport turnTransport + LegacyUDP bool +} + +func normalizeTURNURL(raw string) string { + raw = strings.TrimSpace(raw) + if raw == "" { + return "" + } + return raw +} + +func parseTURNEndpoint(raw string) (turnEndpoint, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return turnEndpoint{}, fmt.Errorf("пустой TURN URL") + } + + withoutQuery := raw + rawQuery := "" + if idx := strings.Index(withoutQuery, "?"); idx >= 0 { + rawQuery = withoutQuery[idx+1:] + withoutQuery = withoutQuery[:idx] + } + + scheme := "turn" + address := withoutQuery + lower := strings.ToLower(withoutQuery) + switch { + case strings.HasPrefix(lower, "turns:"): + scheme = "turns" + address = withoutQuery[len("turns:"):] + case strings.HasPrefix(lower, "turn:"): + scheme = "turn" + address = withoutQuery[len("turn:"):] + } + address = strings.TrimPrefix(address, "//") + + transport := turnTransportUDP + values, _ := neturl.ParseQuery(rawQuery) + if strings.EqualFold(values.Get("transport"), "tcp") { + transport = turnTransportTCP + } + if scheme == "turns" { + transport = turnTransportTLS + } + + host, port, err := splitTURNHostPort(address, transport) + if err != nil { + return turnEndpoint{}, err + } + return turnEndpoint{ + Raw: raw, + Host: host, + Port: port, + Scheme: scheme, + Transport: transport, + }, nil +} + +func legacyUDPEndpoint(raw string) (turnEndpoint, error) { + endpoint, err := parseTURNEndpoint(raw) + if err != nil { + return turnEndpoint{}, err + } + endpoint.Transport = turnTransportUDP + endpoint.LegacyUDP = true + return endpoint, nil +} + +func splitTURNHostPort(address string, transport turnTransport) (string, string, error) { + host, port, err := net.SplitHostPort(address) + if err == nil { + return strings.Trim(host, "[]"), port, nil + } + defaultPort := "3478" + if transport == turnTransportTLS { + defaultPort = "5349" + } + if ip := net.ParseIP(strings.Trim(address, "[]")); ip != nil { + return strings.Trim(address, "[]"), defaultPort, nil + } + if strings.Count(address, ":") > 1 { + return "", "", fmt.Errorf("разбор TURN URL %q: %w", address, err) + } + address = strings.TrimSpace(address) + if address == "" { + return "", "", fmt.Errorf("пустой адрес TURN") + } + return address, defaultPort, nil +} + +func (e turnEndpoint) address() string { + return net.JoinHostPort(e.Host, e.Port) +} + +func (e turnEndpoint) key() string { + return string(e.Transport) + "|" + strings.ToLower(e.Host) + "|" + e.Port +} + +func (e turnEndpoint) label() string { + if e.LegacyUDP { + return "UDP" + } + switch e.Transport { + case turnTransportTLS: + return "TLS" + case turnTransportTCP: + return "TCP" + default: + return "UDP" + } +} + +func sessionTURNCandidates(rawURLs []string, sessionID int, tp *TurnParams) []turnEndpoint { + if len(rawURLs) == 0 { + return nil + } + selectedIndex := sessionID % len(rawURLs) + if selectedIndex < 0 { + selectedIndex = 0 + } + + result := make([]turnEndpoint, 0, len(rawURLs)+3) + seen := make(map[string]struct{}) + add := func(endpoint turnEndpoint) { + if tp != nil { + if tp.Host != "" { + endpoint.Host = tp.Host + } + if tp.Port != "" { + endpoint.Port = tp.Port + } + } + if endpoint.Host == "" || endpoint.Port == "" { + return + } + key := endpoint.key() + if _, exists := seen[key]; exists { + return + } + seen[key] = struct{}{} + result = append(result, endpoint) + } + + if endpoint, err := legacyUDPEndpoint(rawURLs[selectedIndex]); err == nil { + add(endpoint) + } + + for offset := 1; offset < len(rawURLs); offset++ { + idx := (selectedIndex + offset) % len(rawURLs) + if endpoint, err := legacyUDPEndpoint(rawURLs[idx]); err == nil { + add(endpoint) + } + } + + for offset := 0; offset < len(rawURLs); offset++ { + idx := (selectedIndex + offset) % len(rawURLs) + endpoint, err := parseTURNEndpoint(rawURLs[idx]) + if err != nil { + continue + } + if endpoint.Transport == turnTransportUDP { + continue + } + add(endpoint) + } + + return result +} diff --git a/go_client/turn_endpoint_test.go b/go_client/turn_endpoint_test.go new file mode 100644 index 0000000..938b1f1 --- /dev/null +++ b/go_client/turn_endpoint_test.go @@ -0,0 +1,70 @@ +package main + +import "testing" + +func TestParseTURNEndpointPreservesTransport(t *testing.T) { + tests := []struct { + raw string + host string + port string + transport turnTransport + }{ + {"turn:1.2.3.4:3478?transport=udp", "1.2.3.4", "3478", turnTransportUDP}, + {"turn:turn.example:443?transport=tcp", "turn.example", "443", turnTransportTCP}, + {"turns:turn.example:443?transport=tcp", "turn.example", "443", turnTransportTLS}, + {"turn.example:3478", "turn.example", "3478", turnTransportUDP}, + } + for _, tt := range tests { + got, err := parseTURNEndpoint(tt.raw) + if err != nil { + t.Fatalf("parseTURNEndpoint(%q) error: %v", tt.raw, err) + } + if got.Host != tt.host || got.Port != tt.port || got.Transport != tt.transport { + t.Fatalf("parseTURNEndpoint(%q) = host=%q port=%q transport=%q", tt.raw, got.Host, got.Port, got.Transport) + } + } +} + +func TestSessionTURNCandidatesKeepLegacyUDPFirst(t *testing.T) { + raw := []string{ + "turns:turn.example:443?transport=tcp", + "turn:1.2.3.4:3478?transport=udp", + "turn:turn.example:3478?transport=tcp", + } + got := sessionTURNCandidates(raw, 0, nil) + if len(got) < 3 { + t.Fatalf("not enough candidates: %#v", got) + } + if got[0].Transport != turnTransportUDP || !got[0].LegacyUDP || got[0].Host != "turn.example" || got[0].Port != "443" { + t.Fatalf("first candidate must preserve old UDP behavior, got %#v", got[0]) + } + foundTLS := false + foundTCP := false + for _, endpoint := range got[1:] { + if endpoint.Transport == turnTransportTLS { + foundTLS = true + } + if endpoint.Transport == turnTransportTCP { + foundTCP = true + } + } + if !foundTLS || !foundTCP { + t.Fatalf("expected TCP/TLS fallbacks, got %#v", got) + } +} + +func TestSessionTURNCandidatesApplyOverride(t *testing.T) { + got := sessionTURNCandidates( + []string{"turn:old.example:3478?transport=udp", "turn:new.example:443?transport=tcp"}, + 0, + &TurnParams{Host: "override.example", Port: "5555"}, + ) + if len(got) == 0 { + t.Fatal("no candidates") + } + for _, endpoint := range got { + if endpoint.Host != "override.example" || endpoint.Port != "5555" { + t.Fatalf("override not applied: %#v", endpoint) + } + } +} diff --git a/server.go b/server.go index b416932..1b4e2c4 100644 --- a/server.go +++ b/server.go @@ -44,6 +44,7 @@ import ( ) const ( + wdttServerVersion = "12" wgIfaceName = "wdtt0" wgServerAddr = "10.66.66.1" wgServerCIDR = wgServerAddr + "/24" @@ -55,6 +56,15 @@ const ( dtlsClientIdleTimeout = 90 * time.Second ) +func deviceLogRef(deviceID string) string { + clean := strings.TrimSpace(deviceID) + if clean == "" { + return "unknown" + } + sum := sha256.Sum256([]byte(clean)) + return hex.EncodeToString(sum[:6]) +} + // ==================== База данных ==================== type ClientDevice struct { @@ -78,16 +88,24 @@ type ClientDevice struct { } type PasswordEntry struct { - DeviceID string `json:"device_id"` // пусто = ещё не привязан - ExpiresAt int64 `json:"expires_at"` // unix timestamp - DownBytes int64 `json:"down_bytes"` // скачано клиентом - UpBytes int64 `json:"up_bytes"` // отдано клиентом - Traffic []TrafficBucket `json:"traffic,omitempty"` - Label string `json:"label,omitempty"` - VkHash string `json:"vk_hash,omitempty"` - Ports string `json:"ports,omitempty"` // "dtls,wg,tun" - IsDeactivated bool `json:"is_deactivated,omitempty"` - BindHistory []BindHistoryEntry `json:"bind_history,omitempty"` + DeviceID string `json:"device_id"` // пусто = ещё не привязан + ExpiresAt int64 `json:"expires_at"` // unix timestamp + PurgeAfter int64 `json:"purge_after,omitempty"` + DownBytes int64 `json:"down_bytes"` // скачано клиентом + UpBytes int64 `json:"up_bytes"` // отдано клиентом + Traffic []TrafficBucket `json:"traffic,omitempty"` + TrafficImports map[string]TrafficImport `json:"traffic_imports,omitempty"` + Label string `json:"label,omitempty"` + VkHash string `json:"vk_hash,omitempty"` + Ports string `json:"ports,omitempty"` // "dtls,wg,tun" + IsDeactivated bool `json:"is_deactivated,omitempty"` + BindHistory []BindHistoryEntry `json:"bind_history,omitempty"` +} + +type TrafficImport struct { + DownBytes int64 `json:"down_bytes"` + UpBytes int64 `json:"up_bytes"` + AppliedAt int64 `json:"applied_at"` } type AdminProfileEntry struct { @@ -279,8 +297,8 @@ func stripVkUrl(url string) string { } type wrapKeyEntry struct { - id string - key []byte + identity accessIdentity + key []byte } type wrapKeyStore struct { @@ -329,7 +347,10 @@ func (s *wrapKeyStore) SetPasswords(mainPassword string, generated []string) err if err != nil { return err } - next = append(next, wrapKeyEntry{id: "main", key: key}) + next = append(next, wrapKeyEntry{ + identity: accessIdentity{id: "main", password: mainPassword, isMain: true}, + key: key, + }) seen["main"] = struct{}{} } @@ -348,7 +369,10 @@ func (s *wrapKeyStore) SetPasswords(mainPassword string, generated []string) err } return err } - next = append(next, wrapKeyEntry{id: id, key: key}) + next = append(next, wrapKeyEntry{ + identity: accessIdentity{id: id, password: password}, + key: key, + }) seen[id] = struct{}{} } @@ -373,12 +397,15 @@ func (s *wrapKeyStore) AddPassword(password string) error { s.mu.Lock() defer s.mu.Unlock() for _, entry := range s.entries { - if entry.id == id { + if entry.identity.id == id { zeroBytes(key) return nil } } - s.entries = append(s.entries, wrapKeyEntry{id: id, key: key}) + s.entries = append(s.entries, wrapKeyEntry{ + identity: accessIdentity{id: id, password: password}, + key: key, + }) return nil } @@ -388,7 +415,7 @@ func (s *wrapKeyStore) RemovePassword(password string) { s.mu.Lock() defer s.mu.Unlock() for i, entry := range s.entries { - if entry.id != id { + if entry.identity.id != id { continue } aeadCache.Delete(string(entry.key)) @@ -406,29 +433,29 @@ func (s *wrapKeyStore) Count() int { return len(s.entries) } -func (s *wrapKeyStore) Unwrap(raw, dst []byte) ([]byte, int, error) { +func (s *wrapKeyStore) Unwrap(raw, dst []byte) ([]byte, accessIdentity, int, error) { if !obfsIsRTPPacket(raw) { - return nil, 0, errors.New("wrap: non-obfs packet") + return nil, accessIdentity{}, 0, errors.New("wrap: non-obfs packet") } s.mu.RLock() defer s.mu.RUnlock() if len(s.entries) == 0 { - return nil, 0, errors.New("wrap: no active keys") + return nil, accessIdentity{}, 0, errors.New("wrap: no active keys") } for _, entry := range s.entries { m, err := obfsUnwrapPacket(entry.key, raw, dst) if err == nil { - return append([]byte(nil), entry.key...), m, nil + return append([]byte(nil), entry.key...), entry.identity, m, nil } } - return nil, 0, errors.New("wrap: auth failed") + return nil, accessIdentity{}, 0, errors.New("wrap: auth failed") } func refreshWrapKeysFromDBLocked() error { passwords := make([]string, 0, len(db.Passwords)) for password, entry := range db.Passwords { - if !isPasswordExpired(entry) && entry != nil && !entry.IsDeactivated { + if entry != nil && !entry.IsDeactivated && !isPasswordPurgeable(entry) { passwords = append(passwords, password) } } @@ -534,13 +561,61 @@ func saveDB() { } func isPasswordExpired(entry *PasswordEntry) bool { + return isPasswordExpiredAt(entry, time.Now().Unix()) +} + +func isPasswordExpiredAt(entry *PasswordEntry, nowUnix int64) bool { if entry == nil { return true } if entry.ExpiresAt == 0 { return false // бессрочный } - return time.Now().Unix() > entry.ExpiresAt + return nowUnix >= entry.ExpiresAt +} + +func passwordPurgeDeadline(entry *PasswordEntry) int64 { + if entry == nil || entry.ExpiresAt == 0 { + return 0 + } + if entry.PurgeAfter > entry.ExpiresAt { + return entry.PurgeAfter + } + return entry.ExpiresAt +} + +func isPasswordRetainedExpiredAt(entry *PasswordEntry, nowUnix int64) bool { + return isPasswordExpiredAt(entry, nowUnix) && !isPasswordPurgeableAt(entry, nowUnix) +} + +func isPasswordPurgeable(entry *PasswordEntry) bool { + return isPasswordPurgeableAt(entry, time.Now().Unix()) +} + +func isPasswordPurgeableAt(entry *PasswordEntry, nowUnix int64) bool { + if entry == nil { + return true + } + if entry.ExpiresAt < 0 { + return true + } + deadline := passwordPurgeDeadline(entry) + return deadline > 0 && nowUnix >= deadline +} + +func setPasswordExpiryPreservingRetention(entry *PasswordEntry, expiresAt int64) { + if entry == nil { + return + } + retentionDuration := entry.PurgeAfter - entry.ExpiresAt + entry.ExpiresAt = expiresAt + entry.PurgeAfter = 0 + if expiresAt > 0 && retentionDuration > 0 { + purgeAfter := expiresAt + retentionDuration + if purgeAfter >= expiresAt { + entry.PurgeAfter = purgeAfter + } + } } func getNextIP() string { @@ -557,7 +632,7 @@ func getNextIP() string { return "" } -func removePeerFromWG(wgDev *device.Device, dev *ClientDevice) { +func removePeerFromWG(wgDev wgDevice, dev *ClientDevice) { if wgDev == nil || dev == nil || dev.PubKey == "" { return } @@ -568,7 +643,7 @@ func removePeerFromWG(wgDev *device.Device, dev *ClientDevice) { wgDev.IpcSet(fmt.Sprintf("public_key=%s\nremove=true\n", pubHex)) } -func upsertPeerInWG(wgDev *device.Device, dev *ClientDevice) { +func upsertPeerInWG(wgDev wgDevice, dev *ClientDevice) { if wgDev == nil || dev == nil || dev.PubKey == "" || dev.IP == "" { return } @@ -579,28 +654,55 @@ func upsertPeerInWG(wgDev *device.Device, dev *ClientDevice) { wgDev.IpcSet(fmt.Sprintf("public_key=%s\nallowed_ip=%s/32\n", pubHex, dev.IP)) } -func cleanupExpiredPasswordsLocked(wgDev *device.Device) int { +func cleanupExpiredPasswordsLocked(wgDev wgDevice) int { + return cleanupExpiredPasswordsLockedAt(wgDev, time.Now().Unix()) +} + +func cleanupExpiredPasswordsLockedAt(wgDev wgDevice, nowUnix int64) int { removed := 0 - nowUnix := time.Now().Unix() adminDevices := adminDeviceIDSet(db) + deviceCandidates := make(map[string]struct{}) for p, entry := range db.Passwords { - if isPasswordExpired(entry) { + if isPasswordPurgeableAt(entry, nowUnix) { if entry != nil && entry.DeviceID != "" { markActiveBindUnbound(entry, entry.DeviceID, nowUnix) - if _, isAdminDevice := adminDevices[entry.DeviceID]; !isAdminDevice { - removePeerFromWG(wgDev, db.Devices[entry.DeviceID]) - delete(db.Devices, entry.DeviceID) - } + deviceCandidates[entry.DeviceID] = struct{}{} } delete(db.Passwords, p) serverWrapKeys.RemovePassword(p) removed++ } } + for deviceID := range deviceCandidates { + if _, isAdminDevice := adminDevices[deviceID]; isAdminDevice || databaseUsesDeviceID(db, deviceID) { + continue + } + removePeerFromWG(wgDev, db.Devices[deviceID]) + delete(db.Devices, deviceID) + } return removed } -func cleanupExpiredPasswords(wgDev *device.Device) int { +func databaseUsesDeviceID(loaded *Database, deviceID string) bool { + return databaseUsesDeviceIDExcept(loaded, deviceID, "") +} + +func databaseUsesDeviceIDExcept(loaded *Database, deviceID, excludedPassword string) bool { + if loaded == nil || deviceID == "" { + return false + } + for password, entry := range loaded.Passwords { + if excludedPassword != "" && password == excludedPassword { + continue + } + if entry != nil && entry.DeviceID == deviceID { + return true + } + } + return false +} + +func cleanupExpiredPasswords(wgDev wgDevice) int { dbMutex.Lock() defer dbMutex.Unlock() removed := cleanupExpiredPasswordsLocked(wgDev) @@ -773,8 +875,8 @@ func markActiveBindUnbound(entry *PasswordEntry, deviceID string, ts int64) { } } -func expiredPasswordJanitor(ctx context.Context, wgDev *device.Device) { - ticker := time.NewTicker(1 * time.Hour) +func expiredPasswordJanitor(ctx context.Context, wgDev wgDevice) { + ticker := time.NewTicker(1 * time.Minute) defer ticker.Stop() for { select { @@ -788,7 +890,7 @@ func expiredPasswordJanitor(ctx context.Context, wgDev *device.Device) { } } -func syncPersistedPeersToWG(_ *device.Device) { +func syncPersistedPeersToWG(_ wgDevice) { dbMutex.Lock() defer dbMutex.Unlock() count := 0 @@ -817,24 +919,27 @@ func putBuf(b *[]byte) { bufPool.Put(b) } // ==================== Оптимизация ==================== func enableBBR() { - log.Println("[SYS] Оптимизация TCP...") + log.Println("[SYS] Оптимизация сетевого стека...") out, _ := runCmd("bash", "-c", "sysctl net.ipv4.tcp_congestion_control") - if strings.Contains(out, "bbr") { - log.Println("[SYS] BBR уже активен ✓") - return - } cmds := [][]string{ {"sysctl", "-w", "net.core.default_qdisc=fq"}, - {"sysctl", "-w", "net.ipv4.tcp_congestion_control=bbr"}, {"sysctl", "-w", "net.core.rmem_max=25165824"}, {"sysctl", "-w", "net.core.wmem_max=25165824"}, + {"sysctl", "-w", "net.core.rmem_default=4194304"}, + {"sysctl", "-w", "net.core.wmem_default=4194304"}, + {"sysctl", "-w", "net.core.netdev_max_backlog=16384"}, + {"sysctl", "-w", "net.ipv4.udp_rmem_min=262144"}, + {"sysctl", "-w", "net.ipv4.udp_wmem_min=262144"}, {"sysctl", "-w", "net.ipv4.tcp_rmem=4096 87380 25165824"}, {"sysctl", "-w", "net.ipv4.tcp_wmem=4096 65536 25165824"}, } + if !strings.Contains(out, "bbr") { + cmds = append(cmds, []string{"sysctl", "-w", "net.ipv4.tcp_congestion_control=bbr"}) + } for _, cmd := range cmds { runCmd(cmd[0], cmd[1:]...) } - log.Println("[SYS] BBR включен ✓") + log.Println("[SYS] Сетевые буферы, fq и BBR настроены ✓") } // ==================== Статистика ==================== @@ -916,19 +1021,28 @@ func statsLoop(ctx context.Context, configDir string) { statsFile := filepath.Join(configDir, "server.log") ticker := time.NewTicker(10 * time.Second) defer ticker.Stop() + defer func() { + flushAccessTraffic() + dbMutex.Lock() + if atomic.SwapInt32(&dbTrafficDirty, 0) == 1 { + saveDB() + } + dbMutex.Unlock() + }() for { select { case <-ctx.Done(): return case <-ticker.C: + flushAccessTraffic() fromC := atomic.LoadInt64(&totalBytesFromClient) toC := atomic.LoadInt64(&totalBytesToClient) active := atomic.LoadInt32(&activeConns) total := atomic.LoadInt64(&totalConns) uptime := time.Since(serverStartTime) - log.Printf("[СТАТ] Активных: %d | Всего: %d | NAT: %s | ↑%.2f МБ | ↓%.2f МБ", - active, total, natType, + log.Printf("[СТАТ] Активных: %d | Всего: %d | CPU: %.1f%% | RAM: %.1f%% | NAT: %s | ↑%.2f МБ | ↓%.2f МБ", + active, total, runtimeCPUPercent(), runtimeMemoryPercent(), natType, float64(fromC)/1024/1024, float64(toC)/1024/1024, ) @@ -1240,6 +1354,10 @@ PersistentKeepalive = %d`, // ==================== Main ==================== func main() { + if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "-version") { + fmt.Println(wdttServerVersion) + return + } if len(os.Args) > 1 && os.Args[1] == "admin" { os.Exit(runAdminCLI(os.Args[2:])) } @@ -1252,6 +1370,11 @@ func main() { botToken := flag.String("bot-token", "", "Telegram Bot Token") dnsValue := flag.String("dns", defaultDNS, "DNS для WireGuard-клиентов, через запятую") maxPasswordsFlag := flag.Int("max-passwords", defaultMaxGeneratedPasswords, "максимум активных сгенерированных паролей") + maxWorkersFlag := flag.Int("max-workers-per-access", defaultMaxWorkersPerAccess, "максимум одновременных DTLS-воркеров одного доступа; 0 отключает лимит") + maxHandshakesFlag := flag.Int("max-handshakes", defaultMaxHandshakes, "максимум одновременных DTLS-рукопожатий") + handshakeRateFlag := flag.Float64("handshake-rate", defaultHandshakeRate, "допустимые DTLS-рукопожатия в секунду") + clientMbpsFlag := flag.Float64("max-client-mbps", defaultClientMbps, "общий лимит Мбит/с на один доступ; 0 отключает") + wgBackendFlag := flag.String("wg-backend", "auto", "WireGuard backend: auto, kernel или userspace") flag.Parse() if *maxPasswordsFlag < 1 { @@ -1263,6 +1386,24 @@ func main() { } else { maxGeneratedPasswords = *maxPasswordsFlag } + if *maxWorkersFlag < 0 || *maxWorkersFlag > 128 { + log.Printf("[LIMIT] -max-workers-per-access=%d некорректен, использую %d", *maxWorkersFlag, defaultMaxWorkersPerAccess) + *maxWorkersFlag = defaultMaxWorkersPerAccess + } + if *maxHandshakesFlag < 1 || *maxHandshakesFlag > 256 { + log.Printf("[LIMIT] -max-handshakes=%d некорректен, использую %d", *maxHandshakesFlag, defaultMaxHandshakes) + *maxHandshakesFlag = defaultMaxHandshakes + } + if *handshakeRateFlag < 1 || *handshakeRateFlag > 1000 { + log.Printf("[LIMIT] -handshake-rate=%.1f некорректен, использую %.1f", *handshakeRateFlag, defaultHandshakeRate) + *handshakeRateFlag = defaultHandshakeRate + } + if *clientMbpsFlag < 0 || *clientMbpsFlag > 1000 { + log.Printf("[LIMIT] -max-client-mbps=%.1f некорректен, использую %.1f", *clientMbpsFlag, defaultClientMbps) + *clientMbpsFlag = defaultClientMbps + } + configureAccessRuntime(*maxWorkersFlag, *clientMbpsFlag) + configureHandshakeLimits(*maxHandshakesFlag, *handshakeRateFlag) log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) log.Println("══════════════════════════════════════════") @@ -1290,7 +1431,7 @@ func main() { enableBBR() - wgDev, err := startUserspaceWG(keys, *wgPort) + wgDev, err := startWGBackend(*wgBackendFlag, keys, *wgPort, *configDir) if err != nil { log.Fatalf("[WG] Запуск: %v", err) } @@ -1307,6 +1448,7 @@ func main() { }() go statsLoop(ctx, *configDir) + go systemMetricsLoop(ctx) go expiredPasswordJanitor(ctx, wgDev) go botLoop(*botToken, *adminID, wgDev) @@ -1356,11 +1498,32 @@ func main() { // ==================== Обработка соединений ==================== -func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgDev *device.Device, keys *wgKeys) { +func denyExpiredAccess(clientConn net.Conn, identity accessIdentity) { + if clientConn == nil || !identity.valid() || identity.isMain { + return + } + _ = clientConn.SetReadDeadline(time.Now().Add(15 * time.Second)) + buf := make([]byte, 4096) + n, err := clientConn.Read(buf) + _ = clientConn.SetReadDeadline(time.Time{}) + if err != nil { + return + } + request := strings.TrimSpace(string(buf[:n])) + if !strings.HasPrefix(request, "GETCONF:") { + return + } + parts := strings.Split(strings.TrimSpace(strings.TrimPrefix(request, "GETCONF:")), "|") + if len(parts) < 3 || parts[2] != identity.password { + _, _ = clientConn.Write([]byte("DENIED:wrong_password")) + return + } + _, _ = clientConn.Write([]byte("DENIED:expired")) +} + +func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgDev wgDevice, keys *wgKeys) { atomic.AddInt64(&totalConns, 1) - var connPassword string - var connIsMainPass bool var connDevice *ClientDevice dtlsConn, ok := clientConn.(*dtls.Conn) @@ -1369,18 +1532,75 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } hctx, hcancel := context.WithTimeout(ctx, 30*time.Second) - if err := dtlsConn.HandshakeContext(hctx); err != nil { + releaseHandshake, acquired := acquireHandshake(hctx) + if !acquired { hcancel() return } + if err := dtlsConn.HandshakeContext(hctx); err != nil { + releaseHandshake() + failures := atomic.AddInt64(&handshakeFailures, 1) + if failures <= 5 || failures%100 == 0 { + log.Printf("[DTLS] Рукопожатие от %s не завершено: %v", clientConn.RemoteAddr(), err) + } + hcancel() + return + } + releaseHandshake() hcancel() - atomic.AddInt32(&activeConns, 1) - defer atomic.AddInt32(&activeConns, -1) + // The WRAP identity is selected while DTLS reads its first encrypted packet. + // It therefore becomes available only after a successful handshake. + identity, ok := wrappedIdentity(clientConn.RemoteAddr()) + if !ok { + failures := atomic.AddInt64(&handshakeFailures, 1) + if failures <= 5 || failures%100 == 0 { + log.Printf("[WRAP] Не удалось связать соединение %s с доступом", clientConn.RemoteAddr()) + } + return + } + switch currentAccessIdentityState(identity) { + case accessIdentityExpired: + denyExpiredAccess(clientConn, identity) + return + case accessIdentityActive: + // Continue with the normal worker path. + default: + return + } + sendWorkerPolicy := func() { + if maxWorkers := configuredAccessWorkerLimit(); maxWorkers > 0 { + _ = clientConn.SetWriteDeadline(time.Now().Add(3 * time.Second)) + _, _ = clientConn.Write([]byte(fmt.Sprintf("POLICY:max_workers=%d", maxWorkers))) + _ = clientConn.SetWriteDeadline(time.Time{}) + } + } + var runtimeLease *accessRuntime + var workerLease *accessWorkerLease + var releaseWorker func() + workerAdmitted := false buf := make([]byte, 1600) - clientConn.SetReadDeadline(time.Now().Add(30 * time.Second)) + // GETCONF is sent immediately after the client handshake. Give it a short + // pre-admission window so a new authenticated transport generation can replace + // stale leases even when the old generation has filled the worker quota. Regular + // data workers still enter the normal quota before waiting for user traffic. + clientConn.SetReadDeadline(time.Now().Add(1500 * time.Millisecond)) n, err := clientConn.Read(buf) + if err != nil { + if networkError, timedOut := err.(net.Error); timedOut && networkError.Timeout() { + runtimeLease, workerLease, releaseWorker, ok = + acquireAccessWorkerSession(identity, clientConn) + if !ok { + sendWorkerPolicy() + return + } + workerAdmitted = true + defer releaseWorker() + clientConn.SetReadDeadline(time.Now().Add(30 * time.Second)) + n, err = clientConn.Read(buf) + } + } if err != nil { return } @@ -1395,6 +1615,7 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD deviceID := "unknown" password := "" deviceInfo := deviceInfoPayload{} + transportSession := "" if len(parts) > 0 { clientPort = parts[0] } @@ -1407,8 +1628,18 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD if len(parts) > 3 { deviceInfo = parseDeviceInfoPayload(parts[3]) } + if len(parts) > 4 { + transportSession = strings.TrimSpace(parts[4]) + } + if password != identity.password { + atomic.AddInt64(&handshakeFailures, 1) + _, _ = clientConn.Write([]byte("DENIED:wrong_password")) + return + } remoteIP := remoteIPFromAddr(clientConn.RemoteAddr()) nowUnix := time.Now().Unix() + authorized := false + configResponse := "" dbMutex.Lock() @@ -1419,7 +1650,11 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD if valid && isGenPass && entry.IsDeactivated { clientConn.Write([]byte("DENIED:deactivated")) - log.Printf("[WG] Отказ: пароль %s деактивирован, запрос от %s", maskPassword(password), deviceID) + log.Printf( + "[WG] Отказ: пароль %s деактивирован, устройство %s", + maskPassword(password), + deviceLogRef(deviceID), + ) dbMutex.Unlock() } else if valid && isGenPass && entry.DeviceID != "" && entry.DeviceID != deviceID { appendBindHistory(entry, BindHistoryEntry{ @@ -1434,18 +1669,25 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD saveDB() // Пароль уже привязан к другому устройству clientConn.Write([]byte("DENIED:device_mismatch")) - log.Printf("[WG] Отказ: пароль %s привязан к %s, запрос от %s", maskPassword(password), entry.DeviceID, deviceID) + log.Printf( + "[WG] Отказ: пароль %s уже привязан; сохранённое устройство %s, запрос %s", + maskPassword(password), + deviceLogRef(entry.DeviceID), + deviceLogRef(deviceID), + ) dbMutex.Unlock() } else if valid { - connPassword = password - connIsMainPass = isMainPass newlyBound := false // Привязываем пароль к устройству при первом использовании if isGenPass && entry.DeviceID == "" { entry.DeviceID = deviceID newlyBound = true - log.Printf("[WG] Пароль %s привязан к устройству %s", maskPassword(password), deviceID) + log.Printf( + "[WG] Пароль %s привязан к устройству %s", + maskPassword(password), + deviceLogRef(deviceID), + ) } if isMainPass { rememberAdminDeviceID(&db.AdminProfile, deviceID) @@ -1461,7 +1703,7 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD applyDeviceInfo(dev, deviceInfo, remoteIP, nowUnix) db.Devices[deviceID] = dev saveDB() - log.Printf("[WG] Новое устройство %s (IP: %s)", deviceID, dev.IP) + log.Printf("[WG] Новое устройство %s", deviceLogRef(deviceID)) } else { dev = nil } @@ -1485,21 +1727,58 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } if dev != nil { connDevice = dev - clientConn.Write([]byte(buildClientConfig(keys.serverPublic, dev.PrivKey, dev.IP, clientPort))) + authorized = true + configResponse = buildClientConfig(keys.serverPublic, dev.PrivKey, dev.IP, clientPort) } else { - clientConn.Write([]byte("NOCONF")) + configResponse = "NOCONF" } dbMutex.Unlock() } else { if isGenPass && isPasswordExpired(entry) { clientConn.Write([]byte("DENIED:expired")) - log.Printf("[WG] Отказ: пароль %s истёк, от %s", maskPassword(password), deviceID) + log.Printf( + "[WG] Отказ: пароль %s истёк, устройство %s", + maskPassword(password), + deviceLogRef(deviceID), + ) } else { clientConn.Write([]byte("DENIED:wrong_password")) - log.Printf("[WG] Отказ (неверный пароль) от %s", deviceID) + log.Printf("[WG] Отказ (неверный пароль), устройство %s", deviceLogRef(deviceID)) } dbMutex.Unlock() } + if !authorized { + if configResponse != "" { + _, _ = clientConn.Write([]byte(configResponse)) + } + return + } + + if workerAdmitted { + if transportSession != "" && + !activateAccessSession(workerLease, deviceID, transportSession) { + return + } + } else if transportSession != "" { + runtimeLease, workerLease, releaseWorker, ok = acquireAccessWorkerForSession( + identity, + clientConn, + deviceID, + transportSession, + ) + } else { + runtimeLease, workerLease, releaseWorker, ok = + acquireAccessWorkerSession(identity, clientConn) + } + if !workerAdmitted && !ok { + sendWorkerPolicy() + return + } + if !workerAdmitted { + workerAdmitted = true + defer releaseWorker() + } + _, _ = clientConn.Write([]byte(configResponse)) clientConn.SetReadDeadline(time.Now().Add(5 * time.Minute)) n, err = clientConn.Read(buf) @@ -1509,9 +1788,34 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD clientConn.SetReadDeadline(time.Time{}) firstPacket = buf[:n] firstStr = string(firstPacket) + } else if !workerAdmitted { + runtimeLease, workerLease, releaseWorker, ok = + acquireAccessWorkerSession(identity, clientConn) + if !ok { + sendWorkerPolicy() + return + } + workerAdmitted = true + defer releaseWorker() } + switch currentAccessIdentityState(identity) { + case accessIdentityExpired: + _, _ = clientConn.Write([]byte("DENIED:expired")) + return + case accessIdentityActive: + // Continue with the authenticated request. + default: + return + } + + atomic.AddInt32(&activeConns, 1) + defer atomic.AddInt32(&activeConns, -1) + if firstStr == "READY" { + if !accessIdentityIsActive(identity) { + return + } clientConn.Write([]byte("READY_OK")) clientConn.SetReadDeadline(time.Now().Add(10 * time.Minute)) n, err = clientConn.Read(buf) @@ -1534,26 +1838,55 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD uc.SetWriteBuffer(2 * 1024 * 1024) } + if !accessIdentityIsActive(identity) { + return + } if connDevice != nil { upsertPeerInWG(wgDev, connDevice) } + if err := runtimeLease.upload.wait(ctx, len(firstPacket)); err != nil { + return + } if _, err := wgConn.Write(firstPacket); err != nil { return } atomic.AddInt64(&totalBytesFromClient, int64(len(firstPacket))) - if connPassword != "" { - dbMutex.Lock() - if !addTrafficLocked(connPassword, connIsMainPass, 0, int64(len(firstPacket))) { - dbMutex.Unlock() - return - } - dbMutex.Unlock() - } + recordAccessTraffic(runtimeLease, 0, int64(len(firstPacket))) pctx, pcancel := context.WithCancel(ctx) defer pcancel() + if _, limited := accessIdentityExpiryUnix(identity); limited { + go func() { + for { + expiresAt, stillLimited := accessIdentityExpiryUnix(identity) + if !stillLimited { + return + } + delay := time.Until(time.Unix(expiresAt, 0)) + if delay < 0 { + delay = 0 + } + timer := time.NewTimer(delay) + select { + case <-pctx.Done(): + if !timer.Stop() { + <-timer.C + } + return + case <-timer.C: + } + if !accessIdentityIsActive(identity) { + pcancel() + return + } + // The access was renewed before the old deadline. Read the new + // expiration value and arm the monitor again. + } + }() + } + context.AfterFunc(pctx, func() { clientConn.SetDeadline(time.Now()) wgConn.SetDeadline(time.Now()) @@ -1568,6 +1901,7 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD defer pcancel() b := getBuf() defer putBuf(b) + lastAccessCheck := time.Now() for { select { case <-pctx.Done(): @@ -1589,18 +1923,20 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } continue } - atomic.AddInt64(&totalBytesFromClient, int64(nn)) - if connPassword != "" { - dbMutex.Lock() - if !addTrafficLocked(connPassword, connIsMainPass, 0, int64(nn)) { - dbMutex.Unlock() + if time.Since(lastAccessCheck) >= 5*time.Second { + if !accessIdentityIsActive(identity) { return } - dbMutex.Unlock() + lastAccessCheck = time.Now() + } + if err := runtimeLease.upload.wait(pctx, nn); err != nil { + return } if _, err := wgConn.Write((*b)[:nn]); err != nil { return } + atomic.AddInt64(&totalBytesFromClient, int64(nn)) + recordAccessTraffic(runtimeLease, 0, int64(nn)) } }() @@ -1610,6 +1946,7 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD defer pcancel() b := getBuf() defer putBuf(b) + lastAccessCheck := time.Now() for { select { case <-pctx.Done(): @@ -1627,18 +1964,20 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } return } - atomic.AddInt64(&totalBytesToClient, int64(nn)) - if connPassword != "" { - dbMutex.Lock() - if !addTrafficLocked(connPassword, connIsMainPass, int64(nn), 0) { - dbMutex.Unlock() + if time.Since(lastAccessCheck) >= 5*time.Second { + if !accessIdentityIsActive(identity) { return } - dbMutex.Unlock() + lastAccessCheck = time.Now() + } + if err := runtimeLease.download.wait(pctx, nn); err != nil { + return } if _, err := clientConn.Write((*b)[:nn]); err != nil { return } + atomic.AddInt64(&totalBytesToClient, int64(nn)) + recordAccessTraffic(runtimeLease, int64(nn), 0) } }() @@ -1703,8 +2042,8 @@ func NewObfsState() *ObfsState { } } -func obfsBuildNonce(ssrc uint32, seq uint16, ts uint32) []byte { - n := make([]byte, 12) +func obfsBuildNonce(ssrc uint32, seq uint16, ts uint32) [wrapNonceLen]byte { + var n [wrapNonceLen]byte binary.BigEndian.PutUint32(n[0:4], ssrc) binary.BigEndian.PutUint16(n[4:6], seq) binary.BigEndian.PutUint32(n[8:12], ts) @@ -1712,6 +2051,10 @@ func obfsBuildNonce(ssrc uint32, seq uint16, ts uint32) []byte { } 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)) } @@ -1735,7 +2078,10 @@ func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]b } padTotal := padRand + 1 outLen := 12 + len(payload) + chacha20poly1305.Overhead + padTotal - out := make([]byte, outLen) + if cap(dst) < outLen { + dst = make([]byte, outLen) + } + out := dst[:outLen] out[0] = 0x80 | 0x20 out[1] = cfg.PayloadType & 0x7F @@ -1747,7 +2093,7 @@ func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]b if err != nil { return nil, fmt.Errorf("obfs: cipher init: %w", err) } - sealed := aead.Seal(out[12:12], nonce, payload, out[:12]) + sealed := aead.Seal(out[12:12], nonce[:], payload, out[:12]) padStart := 12 + len(sealed) if padRand > 0 { rand.Read(out[padStart : padStart+padRand]) @@ -1790,7 +2136,7 @@ func obfsUnwrapPacket(key, wire, dst []byte) (int, error) { if err != nil { return 0, fmt.Errorf("obfs: cipher init: %w", err) } - plain, err := aead.Open(dst[:0], nonce, wire[12:payloadEnd], wire[:12]) + plain, err := aead.Open(dst[:0], nonce[:], wire[12:payloadEnd], wire[:12]) if err != nil { return 0, fmt.Errorf("obfs: auth: %w", err) } @@ -1812,7 +2158,19 @@ func listenWrapped(addr *net.UDPAddr, keys *wrapKeyStore) (dtlsnet.PacketListene if keys == nil || keys.Count() == 0 { return nil, errors.New("wrap: no active keys") } - inner, err := pionudp.Listen("udp", addr) + listenConfig := pionudp.ListenConfig{ + Backlog: 4096, + AcceptFilter: obfsIsRTPPacket, + ReadBufferSize: 16 * 1024 * 1024, + WriteBufferSize: 16 * 1024 * 1024, + Batch: pionudp.BatchIOConfig{ + Enable: true, + ReadBatchSize: 64, + WriteBatchSize: 32, + WriteBatchInterval: 200 * time.Microsecond, + }, + } + inner, err := listenConfig.Listen("udp", addr) if err != nil { return nil, fmt.Errorf("wrap: udp listen: %w", err) } @@ -1839,18 +2197,33 @@ func (l *wrapPacketListener) Close() error { return l.inner.Close() } func (l *wrapPacketListener) Addr() net.Addr { return l.inner.Addr() } type wrapPacketConn struct { - inner net.PacketConn - keys *wrapKeyStore - key []byte - selected int32 - authLog int32 - obfsCfg *ObfsConfig - obfsWrite *ObfsState + inner net.PacketConn + keys *wrapKeyStore + key []byte + identity accessIdentity + sessionKey string + session *wrappedSession + selected int32 + authLog int32 + obfsCfg *ObfsConfig + obfsWrite *ObfsState +} + +var wrapWireBufferPool = sync.Pool{ + New: func() interface{} { + buffer := make([]byte, 2048) + return &buffer + }, } func (c *wrapPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { // Extra space for RTP header (12) + AEAD tag (16) + padding. - buf := make([]byte, len(p)+80) + buffer := wrapWireBufferPool.Get().(*[]byte) + if cap(*buffer) < len(p)+80 { + *buffer = make([]byte, len(p)+80) + } + buf := (*buffer)[:len(p)+80] + defer wrapWireBufferPool.Put(buffer) n, addr, err := c.inner.ReadFrom(buf) if err != nil { return 0, addr, err @@ -1858,7 +2231,7 @@ func (c *wrapPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { raw := buf[:n] if atomic.LoadInt32(&c.selected) == 0 { - key, m, uErr := c.keys.Unwrap(raw, p) + key, identity, m, uErr := c.keys.Unwrap(raw, p) if uErr != nil { if atomic.CompareAndSwapInt32(&c.authLog, 0, 1) { log.Printf("[WRAP] Отказ: RTP AEAD auth failed from %s (keys=%d)", addr.String(), c.keys.Count()) @@ -1866,6 +2239,8 @@ func (c *wrapPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { return 0, addr, uErr } c.key = key + c.identity = identity + c.sessionKey, c.session = registerWrappedSession(addr, identity) c.obfsCfg = NewObfsConfig() c.obfsWrite = NewObfsState() atomic.StoreInt32(&c.selected, 1) @@ -1890,7 +2265,9 @@ func (c *wrapPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { c.obfsCfg = NewObfsConfig() c.obfsWrite = NewObfsState() } - wrapped, wErr := obfsWrapPacket(c.key, p, c.obfsCfg, c.obfsWrite) + buffer := wrapWireBufferPool.Get().(*[]byte) + defer wrapWireBufferPool.Put(buffer) + wrapped, wErr := obfsWrapPacketInto((*buffer)[:0], c.key, p, c.obfsCfg, c.obfsWrite) if wErr != nil { return 0, fmt.Errorf("obfs wrap: %w", wErr) } @@ -1900,7 +2277,11 @@ func (c *wrapPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { return len(p), nil } -func (c *wrapPacketConn) Close() error { return c.inner.Close() } +func (c *wrapPacketConn) Close() error { + unregisterWrappedSession(c.sessionKey, c.session) + zeroBytes(c.key) + return c.inner.Close() +} func (c *wrapPacketConn) LocalAddr() net.Addr { return c.inner.LocalAddr() } func (c *wrapPacketConn) SetDeadline(t time.Time) error { return c.inner.SetDeadline(t) } func (c *wrapPacketConn) SetReadDeadline(t time.Time) error { return c.inner.SetReadDeadline(t) } diff --git a/server_runtime.go b/server_runtime.go new file mode 100644 index 0000000..809ad8c --- /dev/null +++ b/server_runtime.go @@ -0,0 +1,771 @@ +package main + +import ( + "bufio" + "context" + "errors" + "fmt" + "net" + "os" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +const ( + defaultMaxWorkersPerAccess = 0 + defaultMaxHandshakes = 32 + defaultHandshakeRate = 24.0 + defaultClientMbps = 0.0 +) + +type accessIdentity struct { + id string + password string + isMain bool +} + +func (i accessIdentity) valid() bool { + return i.id != "" && i.password != "" +} + +type wrappedSession struct { + identity accessIdentity +} + +var wrappedSessions sync.Map + +func registerWrappedSession(addr net.Addr, identity accessIdentity) (string, *wrappedSession) { + if addr == nil || !identity.valid() { + return "", nil + } + key := addr.String() + session := &wrappedSession{identity: identity} + wrappedSessions.Store(key, session) + return key, session +} + +func unregisterWrappedSession(key string, session *wrappedSession) { + if key == "" || session == nil { + return + } + wrappedSessions.CompareAndDelete(key, session) +} + +func wrappedIdentity(addr net.Addr) (accessIdentity, bool) { + if addr == nil { + return accessIdentity{}, false + } + value, ok := wrappedSessions.Load(addr.String()) + if !ok { + return accessIdentity{}, false + } + session, ok := value.(*wrappedSession) + if !ok || session == nil || !session.identity.valid() { + return accessIdentity{}, false + } + return session.identity, true +} + +type tokenBucket struct { + mu sync.Mutex + rate float64 + burst float64 + tokens float64 + last time.Time +} + +func newTokenBucket(rate, burst float64) *tokenBucket { + now := time.Now() + return &tokenBucket{rate: rate, burst: burst, tokens: burst, last: now} +} + +func (b *tokenBucket) allow(amount float64) bool { + if b == nil || b.rate <= 0 || amount <= 0 { + return true + } + b.mu.Lock() + defer b.mu.Unlock() + b.refill(time.Now()) + if b.tokens < amount { + return false + } + b.tokens -= amount + return true +} + +func (b *tokenBucket) wait(ctx context.Context, amount int) error { + if b == nil || b.rate <= 0 || amount <= 0 { + return nil + } + need := float64(amount) + for { + b.mu.Lock() + now := time.Now() + b.refill(now) + if b.tokens >= need { + b.tokens -= need + b.mu.Unlock() + return nil + } + missing := need - b.tokens + b.tokens = 0 + b.last = now + wait := time.Duration(missing / b.rate * float64(time.Second)) + b.mu.Unlock() + if wait < time.Millisecond { + wait = time.Millisecond + } + timer := time.NewTimer(wait) + select { + case <-ctx.Done(): + if !timer.Stop() { + <-timer.C + } + return ctx.Err() + case <-timer.C: + } + } +} + +func (b *tokenBucket) refill(now time.Time) { + if now.Before(b.last) { + b.last = now + return + } + b.tokens += now.Sub(b.last).Seconds() * b.rate + if b.tokens > b.burst { + b.tokens = b.burst + } + b.last = now +} + +type accessRuntime struct { + identity accessIdentity + activeWorkers int + everConnected bool + disconnectedAt time.Time + currentDevice string + currentSession string + workers map[*accessWorkerLease]struct{} + upload *tokenBucket + download *tokenBucket + pendingDown atomic.Int64 + pendingUp atomic.Int64 +} + +type accessWorkerLease struct { + runtime *accessRuntime + connection net.Conn + session string +} + +type accessRuntimeRegistry struct { + mu sync.Mutex + items map[string]*accessRuntime + maxWorkers int + clientMbps float64 +} + +func newAccessRuntimeRegistry() *accessRuntimeRegistry { + return &accessRuntimeRegistry{ + items: make(map[string]*accessRuntime), + maxWorkers: defaultMaxWorkersPerAccess, + clientMbps: defaultClientMbps, + } +} + +var accessRuntimes = newAccessRuntimeRegistry() + +func configureAccessRuntime(maxWorkers int, clientMbps float64) { + if maxWorkers < 0 { + maxWorkers = 0 + } + if clientMbps < 0 { + clientMbps = 0 + } + accessRuntimes.mu.Lock() + accessRuntimes.maxWorkers = maxWorkers + accessRuntimes.clientMbps = clientMbps + accessRuntimes.mu.Unlock() +} + +func configuredAccessWorkerLimit() int { + maxWorkers, _ := configuredAccessRuntimeLimits() + return maxWorkers +} + +func configuredAccessRuntimeLimits() (int, float64) { + accessRuntimes.mu.Lock() + defer accessRuntimes.mu.Unlock() + return accessRuntimes.maxWorkers, accessRuntimes.clientMbps +} + +func (r *accessRuntimeRegistry) getOrCreateLocked(identity accessIdentity) *accessRuntime { + if item := r.items[identity.id]; item != nil { + return item + } + bytesPerSecond := r.clientMbps * 1_000_000 / 8 + burst := bytesPerSecond / 4 + if burst < 64*1024 { + burst = 64 * 1024 + } + if burst > 2*1024*1024 { + burst = 2 * 1024 * 1024 + } + item := &accessRuntime{ + identity: identity, + workers: make(map[*accessWorkerLease]struct{}), + upload: newTokenBucket(bytesPerSecond, burst), + download: newTokenBucket(bytesPerSecond, burst), + } + r.items[identity.id] = item + return item +} + +func acquireAccessWorker(identity accessIdentity) (*accessRuntime, func(), bool) { + runtime, _, release, ok := acquireAccessWorkerSession(identity, nil) + return runtime, release, ok +} + +func acquireAccessWorkerSession( + identity accessIdentity, + connection net.Conn, +) (*accessRuntime, *accessWorkerLease, func(), bool) { + if !identity.valid() { + return nil, nil, func() {}, false + } + accessRuntimes.mu.Lock() + item := accessRuntimes.getOrCreateLocked(identity) + activeForCurrentSession := item.activeWorkers + if item.currentSession != "" { + activeForCurrentSession = 0 + for worker := range item.workers { + if worker.session == item.currentSession { + activeForCurrentSession++ + } + } + } + if !identity.isMain && accessRuntimes.maxWorkers > 0 && activeForCurrentSession >= accessRuntimes.maxWorkers { + accessRuntimes.mu.Unlock() + atomic.AddInt64(&workerLimitRejections, 1) + return nil, nil, func() {}, false + } + lease := &accessWorkerLease{ + runtime: item, + connection: connection, + session: item.currentSession, + } + item.workers[lease] = struct{}{} + if item.activeWorkers == 0 && item.everConnected && !item.disconnectedAt.IsZero() { + atomic.AddInt64(&reconnectCount, 1) + } + item.activeWorkers++ + item.everConnected = true + item.disconnectedAt = time.Time{} + accessRuntimes.mu.Unlock() + + var once sync.Once + release := func() { + once.Do(func() { + accessRuntimes.mu.Lock() + delete(item.workers, lease) + if item.activeWorkers > 0 { + item.activeWorkers-- + } + if item.activeWorkers == 0 { + item.disconnectedAt = time.Now() + } + accessRuntimes.mu.Unlock() + }) + } + return item, lease, release, true +} + +// acquireAccessWorkerForSession admits an already authenticated GETCONF connection +// directly into its transport generation. A genuinely new generation replaces stale +// leases atomically before the worker limit is checked, so old UDP sessions cannot +// prevent the control connection from registering the replacement. +func acquireAccessWorkerForSession( + identity accessIdentity, + connection net.Conn, + deviceID, session string, +) (*accessRuntime, *accessWorkerLease, func(), bool) { + deviceID = strings.TrimSpace(deviceID) + session = strings.TrimSpace(session) + if !identity.valid() || deviceID == "" || !validTransportSession(session) { + return nil, nil, func() {}, false + } + + staleConnections := make([]net.Conn, 0) + accessRuntimes.mu.Lock() + item := accessRuntimes.getOrCreateLocked(identity) + switch { + case item.currentSession == "": + item.currentDevice = deviceID + item.currentSession = session + for worker := range item.workers { + worker.session = session + } + case item.currentSession == session: + if item.currentDevice != "" && item.currentDevice != deviceID { + accessRuntimes.mu.Unlock() + return nil, nil, func() {}, false + } + item.currentDevice = deviceID + default: + // The caller invokes this only after the persistent password/device binding + // has authorized deviceID. + item.currentDevice = deviceID + item.currentSession = session + for worker := range item.workers { + if worker.session == session { + continue + } + if worker.connection != nil { + staleConnections = append(staleConnections, worker.connection) + } + } + } + + activeForSession := 0 + for worker := range item.workers { + if worker.session == session { + activeForSession++ + } + } + if !identity.isMain && accessRuntimes.maxWorkers > 0 && activeForSession >= accessRuntimes.maxWorkers { + accessRuntimes.mu.Unlock() + atomic.AddInt64(&workerLimitRejections, 1) + return nil, nil, func() {}, false + } + + lease := &accessWorkerLease{ + runtime: item, + connection: connection, + session: session, + } + item.workers[lease] = struct{}{} + if item.activeWorkers == 0 && item.everConnected && !item.disconnectedAt.IsZero() { + atomic.AddInt64(&reconnectCount, 1) + } + item.activeWorkers++ + item.everConnected = true + item.disconnectedAt = time.Time{} + accessRuntimes.mu.Unlock() + + for _, staleConnection := range staleConnections { + _ = staleConnection.SetDeadline(time.Now()) + } + + var once sync.Once + release := func() { + once.Do(func() { + accessRuntimes.mu.Lock() + delete(item.workers, lease) + if item.activeWorkers > 0 { + item.activeWorkers-- + } + if item.activeWorkers == 0 { + item.disconnectedAt = time.Now() + } + accessRuntimes.mu.Unlock() + }) + } + return item, lease, release, true +} + +// activateAccessSession moves an authenticated device to a new transport generation. +// Workers from the preceding network are closed and stop consuming the current generation's +// quota immediately, even when their UDP sockets would otherwise linger until the idle timeout. +func activateAccessSession(lease *accessWorkerLease, deviceID, session string) bool { + deviceID = strings.TrimSpace(deviceID) + session = strings.TrimSpace(session) + if lease == nil || lease.runtime == nil || deviceID == "" || !validTransportSession(session) { + return false + } + + item := lease.runtime + staleConnections := make([]net.Conn, 0) + accessRuntimes.mu.Lock() + if _, exists := item.workers[lease]; !exists { + accessRuntimes.mu.Unlock() + return false + } + switch { + case item.currentSession == "": + item.currentDevice = deviceID + item.currentSession = session + for worker := range item.workers { + worker.session = session + } + case item.currentSession == session: + if item.currentDevice != "" && item.currentDevice != deviceID { + accessRuntimes.mu.Unlock() + return false + } + item.currentDevice = deviceID + lease.session = session + default: + // handleConn calls this only after the persistent access binding has + // authorized deviceID. A changed device therefore means an explicit + // server-side rebind; close any sessions left by the previous device too. + item.currentDevice = deviceID + item.currentSession = session + lease.session = session + for worker := range item.workers { + if worker == lease || worker.session == session { + continue + } + if worker.connection != nil { + staleConnections = append(staleConnections, worker.connection) + } + } + } + accessRuntimes.mu.Unlock() + + for _, connection := range staleConnections { + _ = connection.SetDeadline(time.Now()) + } + return true +} + +func validTransportSession(value string) bool { + if len(value) < 16 || len(value) > 64 { + return false + } + for _, char := range value { + if (char >= 'a' && char <= 'z') || + (char >= 'A' && char <= 'Z') || + (char >= '0' && char <= '9') || + char == '-' || char == '_' { + continue + } + return false + } + return true +} + +func recordAccessTraffic(runtime *accessRuntime, downBytes, upBytes int64) { + if runtime == nil { + return + } + if downBytes > 0 { + runtime.pendingDown.Add(downBytes) + } + if upBytes > 0 { + runtime.pendingUp.Add(upBytes) + } +} + +func flushAccessTraffic() { + accessRuntimes.mu.Lock() + items := make([]*accessRuntime, 0, len(accessRuntimes.items)) + for _, item := range accessRuntimes.items { + items = append(items, item) + } + accessRuntimes.mu.Unlock() + + dbMutex.Lock() + defer dbMutex.Unlock() + for _, item := range items { + down := item.pendingDown.Swap(0) + up := item.pendingUp.Swap(0) + if down == 0 && up == 0 { + continue + } + _ = addTrafficLocked(item.identity.password, item.identity.isMain, down, up) + } +} + +type accessIdentityState uint8 + +const ( + accessIdentityUnknown accessIdentityState = iota + accessIdentityActive + accessIdentityExpired + accessIdentityDeactivated +) + +func currentAccessIdentityState(identity accessIdentity) accessIdentityState { + if !identity.valid() { + return accessIdentityUnknown + } + dbMutex.Lock() + defer dbMutex.Unlock() + if identity.isMain { + if db.MainPassword != "" && db.MainPassword == identity.password { + return accessIdentityActive + } + return accessIdentityUnknown + } + entry, ok := db.Passwords[identity.password] + if !ok || entry == nil { + return accessIdentityUnknown + } + if isPasswordExpired(entry) { + return accessIdentityExpired + } + if entry.IsDeactivated { + return accessIdentityDeactivated + } + return accessIdentityActive +} + +func accessIdentityExpiryUnix(identity accessIdentity) (int64, bool) { + if !identity.valid() || identity.isMain { + return 0, false + } + dbMutex.Lock() + defer dbMutex.Unlock() + entry, ok := db.Passwords[identity.password] + if !ok || entry == nil || entry.ExpiresAt <= 0 { + return 0, false + } + return entry.ExpiresAt, true +} + +func accessIdentityIsActive(identity accessIdentity) bool { + return currentAccessIdentityState(identity) == accessIdentityActive +} + +var ( + handshakeSlots = make(chan struct{}, defaultMaxHandshakes) + handshakeRateLimiter = newTokenBucket(defaultHandshakeRate, defaultHandshakeRate*2) + handshakeFailures int64 + handshakeThrottles int64 + workerLimitRejections int64 + reconnectCount int64 +) + +func configureHandshakeLimits(maxConcurrent int, rate float64) { + if maxConcurrent < 1 { + maxConcurrent = 1 + } + if rate < 1 { + rate = 1 + } + handshakeSlots = make(chan struct{}, maxConcurrent) + handshakeRateLimiter = newTokenBucket(rate, rate*2) +} + +func acquireHandshake(ctx context.Context) (func(), bool) { + if err := handshakeRateLimiter.wait(ctx, 1); err != nil { + atomic.AddInt64(&handshakeThrottles, 1) + return func() {}, false + } + select { + case handshakeSlots <- struct{}{}: + return func() { <-handshakeSlots }, true + case <-ctx.Done(): + atomic.AddInt64(&handshakeThrottles, 1) + return func() {}, false + } +} + +type procCPUSample struct { + total uint64 + idle uint64 +} + +type procNetworkSample struct { + rxBytes uint64 + txBytes uint64 + drops uint64 +} + +var ( + runtimeCPUMilli int64 + runtimeMemoryMilli int64 + runtimeNetworkRxKbps int64 + runtimeNetworkTxKbps int64 + runtimePacketDrops int64 +) + +func systemMetricsLoop(ctx context.Context) { + iface := getDefaultInterface() + previousCPU, _ := readProcCPU() + previousNetwork, _ := readProcNetwork(iface) + previousAt := time.Now() + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case now := <-ticker.C: + currentCPU, cpuErr := readProcCPU() + if cpuErr == nil && currentCPU.total > previousCPU.total { + totalDelta := currentCPU.total - previousCPU.total + idleDelta := currentCPU.idle - previousCPU.idle + busy := float64(totalDelta-idleDelta) / float64(totalDelta) * 100 + atomic.StoreInt64(&runtimeCPUMilli, int64(busy*1000)) + previousCPU = currentCPU + } + if memory, err := readProcMemoryPercent(); err == nil { + atomic.StoreInt64(&runtimeMemoryMilli, int64(memory*1000)) + } + currentNetwork, netErr := readProcNetwork(iface) + elapsed := now.Sub(previousAt).Seconds() + if netErr == nil && elapsed > 0 { + if currentNetwork.rxBytes >= previousNetwork.rxBytes { + rxMbps := float64(currentNetwork.rxBytes-previousNetwork.rxBytes) * 8 / elapsed / 1_000_000 + atomic.StoreInt64(&runtimeNetworkRxKbps, int64(rxMbps*1000)) + } + if currentNetwork.txBytes >= previousNetwork.txBytes { + txMbps := float64(currentNetwork.txBytes-previousNetwork.txBytes) * 8 / elapsed / 1_000_000 + atomic.StoreInt64(&runtimeNetworkTxKbps, int64(txMbps*1000)) + } + udpDrops, _ := readProcUDPDrops() + atomic.StoreInt64( + &runtimePacketDrops, + int64(currentNetwork.drops+udpDrops), + ) + previousNetwork = currentNetwork + previousAt = now + } + } + } +} + +func runtimeCPUPercent() float64 { + return float64(atomic.LoadInt64(&runtimeCPUMilli)) / 1000 +} + +func runtimeMemoryPercent() float64 { + return float64(atomic.LoadInt64(&runtimeMemoryMilli)) / 1000 +} + +func runtimeNetworkRxMbps() float64 { + return float64(atomic.LoadInt64(&runtimeNetworkRxKbps)) / 1000 +} + +func runtimeNetworkTxMbps() float64 { + return float64(atomic.LoadInt64(&runtimeNetworkTxKbps)) / 1000 +} + +func readProcCPU() (procCPUSample, error) { + file, err := os.Open("/proc/stat") + if err != nil { + return procCPUSample{}, err + } + defer file.Close() + scanner := bufio.NewScanner(file) + if !scanner.Scan() { + return procCPUSample{}, errors.New("/proc/stat is empty") + } + fields := strings.Fields(scanner.Text()) + if len(fields) < 5 || fields[0] != "cpu" { + return procCPUSample{}, errors.New("unexpected /proc/stat cpu row") + } + values := make([]uint64, 0, len(fields)-1) + for _, field := range fields[1:] { + value, parseErr := strconv.ParseUint(field, 10, 64) + if parseErr != nil { + return procCPUSample{}, parseErr + } + values = append(values, value) + } + var total uint64 + for _, value := range values { + total += value + } + idle := values[3] + if len(values) > 4 { + idle += values[4] + } + return procCPUSample{total: total, idle: idle}, nil +} + +func readProcMemoryPercent() (float64, error) { + data, err := os.ReadFile("/proc/meminfo") + if err != nil { + return 0, err + } + var total, available uint64 + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + value, parseErr := strconv.ParseUint(fields[1], 10, 64) + if parseErr != nil { + continue + } + switch strings.TrimSuffix(fields[0], ":") { + case "MemTotal": + total = value + case "MemAvailable": + available = value + } + } + if total == 0 || available > total { + return 0, errors.New("invalid /proc/meminfo") + } + return float64(total-available) / float64(total) * 100, nil +} + +func readProcNetwork(iface string) (procNetworkSample, error) { + file, err := os.Open("/proc/net/dev") + if err != nil { + return procNetworkSample{}, err + } + defer file.Close() + scanner := bufio.NewScanner(file) + prefix := iface + ":" + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if !strings.HasPrefix(line, prefix) { + continue + } + fields := strings.Fields(strings.TrimSpace(strings.TrimPrefix(line, prefix))) + if len(fields) < 16 { + return procNetworkSample{}, fmt.Errorf("invalid /proc/net/dev row for %s", iface) + } + rx, err1 := strconv.ParseUint(fields[0], 10, 64) + rxDrop, err2 := strconv.ParseUint(fields[3], 10, 64) + tx, err3 := strconv.ParseUint(fields[8], 10, 64) + txDrop, err4 := strconv.ParseUint(fields[11], 10, 64) + if err := errors.Join(err1, err2, err3, err4); err != nil { + return procNetworkSample{}, err + } + return procNetworkSample{rxBytes: rx, txBytes: tx, drops: rxDrop + txDrop}, nil + } + if err := scanner.Err(); err != nil { + return procNetworkSample{}, err + } + return procNetworkSample{}, fmt.Errorf("network interface %s not found", iface) +} + +func readProcUDPDrops() (uint64, error) { + data, err := os.ReadFile("/proc/net/snmp") + if err != nil { + return 0, err + } + lines := strings.Split(string(data), "\n") + for index := 0; index+1 < len(lines); index++ { + if !strings.HasPrefix(lines[index], "Udp:") || !strings.HasPrefix(lines[index+1], "Udp:") { + continue + } + headers := strings.Fields(strings.TrimPrefix(lines[index], "Udp:")) + values := strings.Fields(strings.TrimPrefix(lines[index+1], "Udp:")) + if len(headers) != len(values) { + return 0, errors.New("invalid /proc/net/snmp Udp rows") + } + var drops uint64 + for position, header := range headers { + if header != "InErrors" && header != "SndbufErrors" { + continue + } + value, parseErr := strconv.ParseUint(values[position], 10, 64) + if parseErr != nil { + return 0, parseErr + } + drops += value + } + return drops, nil + } + return 0, errors.New("/proc/net/snmp has no Udp rows") +} diff --git a/server_runtime_test.go b/server_runtime_test.go new file mode 100644 index 0000000..2a3ff5f --- /dev/null +++ b/server_runtime_test.go @@ -0,0 +1,407 @@ +package main + +import ( + "context" + "encoding/base64" + "net" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" +) + +type singlePacketConn struct { + packet []byte + remote net.Addr +} + +type generationLeaseConn struct { + deadlineSet atomic.Bool +} + +func (c *generationLeaseConn) Read([]byte) (int, error) { return 0, net.ErrClosed } +func (c *generationLeaseConn) Write(p []byte) (int, error) { return len(p), nil } +func (c *generationLeaseConn) Close() error { return nil } +func (c *generationLeaseConn) LocalAddr() net.Addr { return &net.UDPAddr{} } +func (c *generationLeaseConn) RemoteAddr() net.Addr { return &net.UDPAddr{} } +func (c *generationLeaseConn) SetDeadline(time.Time) error { c.deadlineSet.Store(true); return nil } +func (c *generationLeaseConn) SetReadDeadline(time.Time) error { return nil } +func (c *generationLeaseConn) SetWriteDeadline(time.Time) error { return nil } + +func (c *singlePacketConn) ReadFrom(p []byte) (int, net.Addr, error) { + return copy(p, c.packet), c.remote, nil +} + +func (c *singlePacketConn) WriteTo(p []byte, _ net.Addr) (int, error) { return len(p), nil } +func (c *singlePacketConn) Close() error { return nil } +func (c *singlePacketConn) LocalAddr() net.Addr { return &net.UDPAddr{} } +func (c *singlePacketConn) SetDeadline(time.Time) error { return nil } +func (c *singlePacketConn) SetReadDeadline(time.Time) error { return nil } +func (c *singlePacketConn) SetWriteDeadline(time.Time) error { return nil } + +func TestDeviceLogRefIsStableAndDoesNotExposeIdentifier(t *testing.T) { + deviceID := "android-private-device-identifier" + first := deviceLogRef(deviceID) + second := deviceLogRef(deviceID) + if first != second { + t.Fatalf("device log reference is unstable: %q != %q", first, second) + } + if first == "" || strings.Contains(first, deviceID) || len(first) != 12 { + t.Fatalf("device log reference exposes its source: %q", first) + } +} + +func TestWrapKeyStoreReturnsAuthenticatedAccessIdentity(t *testing.T) { + store := newWrapKeyStore() + if err := store.SetPasswords("owner-secret", []string{"client-secret"}); err != nil { + t.Fatal(err) + } + key, err := deriveWrapKey("client-secret") + if err != nil { + t.Fatal(err) + } + payload := []byte("dtls handshake packet") + wire, err := obfsWrapPacket(key, payload, NewObfsConfig(), NewObfsState()) + if err != nil { + t.Fatal(err) + } + dst := make([]byte, 256) + selectedKey, identity, n, err := store.Unwrap(wire, dst) + if err != nil { + t.Fatal(err) + } + if identity.password != "client-secret" || identity.isMain || !strings.HasPrefix(identity.id, "pass:") { + t.Fatalf("unexpected identity: %#v", identity) + } + if string(dst[:n]) != string(payload) { + t.Fatalf("unexpected payload: %q", dst[:n]) + } + if string(selectedKey) != string(key) { + t.Fatal("selected key differs from authenticated key") + } +} + +func TestWrapIdentityBecomesAvailableAfterFirstRead(t *testing.T) { + store := newWrapKeyStore() + if err := store.SetPasswords("owner-secret", []string{"client-secret"}); err != nil { + t.Fatal(err) + } + key, err := deriveWrapKey("client-secret") + if err != nil { + t.Fatal(err) + } + wire, err := obfsWrapPacket(key, []byte("client hello"), NewObfsConfig(), NewObfsState()) + if err != nil { + t.Fatal(err) + } + remote := &net.UDPAddr{IP: net.ParseIP("192.0.2.10"), Port: 42000} + conn := &wrapPacketConn{ + inner: &singlePacketConn{packet: wire, remote: remote}, + keys: store, + } + if _, ok := wrappedIdentity(remote); ok { + t.Fatal("identity unexpectedly existed before the first WRAP read") + } + plain := make([]byte, 256) + if _, _, err := conn.ReadFrom(plain); err != nil { + t.Fatal(err) + } + identity, ok := wrappedIdentity(remote) + if !ok || identity.password != "client-secret" { + t.Fatalf("identity was not registered by the first WRAP read: %#v", identity) + } + if err := conn.Close(); err != nil { + t.Fatal(err) + } + if _, ok := wrappedIdentity(remote); ok { + t.Fatal("identity remained registered after closing the connection") + } +} + +func TestAccessWorkerLimitIsSharedByAllWorkers(t *testing.T) { + previous := accessRuntimes + accessRuntimes = newAccessRuntimeRegistry() + t.Cleanup(func() { accessRuntimes = previous }) + configureAccessRuntime(2, 0) + if limit := configuredAccessWorkerLimit(); limit != 2 { + t.Fatalf("configured limit = %d, want 2", limit) + } + identity := accessIdentity{id: "pass:test", password: "secret"} + + _, releaseFirst, ok := acquireAccessWorker(identity) + if !ok { + t.Fatal("first worker rejected") + } + _, releaseSecond, ok := acquireAccessWorker(identity) + if !ok { + t.Fatal("second worker rejected") + } + if _, _, ok := acquireAccessWorker(identity); ok { + t.Fatal("worker over the per-access limit was accepted") + } + releaseFirst() + if _, releaseThird, ok := acquireAccessWorker(identity); !ok { + t.Fatal("worker was not accepted after capacity release") + } else { + releaseThird() + } + releaseSecond() +} + +func TestOwnerWorkersAreNotRestrictedByClientAccessLimit(t *testing.T) { + previous := accessRuntimes + accessRuntimes = newAccessRuntimeRegistry() + t.Cleanup(func() { accessRuntimes = previous }) + configureAccessRuntime(2, 0) + identity := accessIdentity{id: "main", password: "owner-secret", isMain: true} + + releases := make([]func(), 0, 5) + for worker := 0; worker < 5; worker++ { + _, release, ok := acquireAccessWorker(identity) + if !ok { + t.Fatalf("owner worker %d was restricted by the client access limit", worker) + } + releases = append(releases, release) + } + for _, release := range releases { + release() + } +} + +func TestNewTransportSessionReplacesStaleWorkersWithoutRaisingLimit(t *testing.T) { + previous := accessRuntimes + accessRuntimes = newAccessRuntimeRegistry() + t.Cleanup(func() { accessRuntimes = previous }) + configureAccessRuntime(3, 0) + identity := accessIdentity{id: "pass:replace", password: "secret"} + + oldFirstConn := &generationLeaseConn{} + _, oldFirst, releaseOldFirst, ok := acquireAccessWorkerSession(identity, oldFirstConn) + if !ok { + t.Fatal("first old worker rejected") + } + oldSecondConn := &generationLeaseConn{} + _, _, releaseOldSecond, ok := acquireAccessWorkerSession(identity, oldSecondConn) + if !ok { + t.Fatal("second old worker rejected") + } + if !activateAccessSession(oldFirst, "device-one", "session-old-0001") { + t.Fatal("initial transport session was not activated") + } + + newConfigConn := &generationLeaseConn{} + _, newConfig, releaseNewConfig, ok := acquireAccessWorkerSession(identity, newConfigConn) + if !ok { + t.Fatal("new config worker must fit the configured transition headroom") + } + if !activateAccessSession(newConfig, "device-one", "session-new-0002") { + t.Fatal("new transport session was not activated") + } + if !oldFirstConn.deadlineSet.Load() || !oldSecondConn.deadlineSet.Load() { + t.Fatal("stale transport workers were not closed") + } + + newReleases := []func(){releaseNewConfig} + for worker := 0; worker < 2; worker++ { + _, _, release, accepted := acquireAccessWorkerSession(identity, &generationLeaseConn{}) + if !accepted { + t.Fatalf("new generation worker %d was blocked by stale workers", worker) + } + newReleases = append(newReleases, release) + } + if _, _, _, accepted := acquireAccessWorkerSession(identity, &generationLeaseConn{}); accepted { + t.Fatal("current generation exceeded the unchanged worker limit") + } + + releaseOldFirst() + releaseOldSecond() + for _, release := range newReleases { + release() + } +} + +func TestAuthenticatedConfigConnectionReplacesAFullStaleGeneration(t *testing.T) { + previous := accessRuntimes + accessRuntimes = newAccessRuntimeRegistry() + t.Cleanup(func() { accessRuntimes = previous }) + configureAccessRuntime(3, 0) + identity := accessIdentity{id: "pass:full-replace", password: "secret"} + + oldConnections := make([]*generationLeaseConn, 0, 3) + oldReleases := make([]func(), 0, 3) + for worker := 0; worker < 3; worker++ { + connection := &generationLeaseConn{} + _, lease, release, ok := acquireAccessWorkerSession(identity, connection) + if !ok { + t.Fatalf("old worker %d was rejected", worker) + } + if worker == 0 && !activateAccessSession(lease, "device-one", "session-old-0001") { + t.Fatal("old generation was not activated") + } + oldConnections = append(oldConnections, connection) + oldReleases = append(oldReleases, release) + } + + newConnection := &generationLeaseConn{} + _, newLease, releaseNew, ok := acquireAccessWorkerForSession( + identity, + newConnection, + "device-one", + "session-new-0002", + ) + if !ok || newLease == nil { + t.Fatal("authenticated GETCONF was blocked by a full stale generation") + } + for index, connection := range oldConnections { + if !connection.deadlineSet.Load() { + t.Fatalf("stale worker %d was not closed", index) + } + } + + newReleases := []func(){releaseNew} + for worker := 0; worker < 2; worker++ { + _, _, release, accepted := acquireAccessWorkerSession(identity, &generationLeaseConn{}) + if !accepted { + t.Fatalf("new worker %d was rejected after generation replacement", worker) + } + newReleases = append(newReleases, release) + } + if _, _, _, accepted := acquireAccessWorkerSession(identity, &generationLeaseConn{}); accepted { + t.Fatal("new generation exceeded the unchanged worker limit") + } + + for _, release := range oldReleases { + release() + } + for _, release := range newReleases { + release() + } +} + +func TestSameTransportSessionCannotBeClaimedByAnotherDevice(t *testing.T) { + previous := accessRuntimes + accessRuntimes = newAccessRuntimeRegistry() + t.Cleanup(func() { accessRuntimes = previous }) + configureAccessRuntime(3, 0) + identity := accessIdentity{id: "pass:device", password: "secret"} + oldConn := &generationLeaseConn{} + _, first, releaseFirst, ok := acquireAccessWorkerSession(identity, oldConn) + if !ok || !activateAccessSession(first, "device-one", "session-old-0001") { + t.Fatal("initial session failed") + } + _, second, releaseSecond, ok := acquireAccessWorkerSession(identity, &generationLeaseConn{}) + if !ok { + t.Fatal("second worker rejected") + } + if activateAccessSession(second, "device-two", "session-old-0001") { + t.Fatal("another device claimed the same transport session") + } + if !activateAccessSession(second, "device-two", "session-new-0002") { + t.Fatal("an authorized new generation did not replace the explicitly rebound device") + } + if !oldConn.deadlineSet.Load() { + t.Fatal("the explicitly rebound device left its old transport alive") + } + releaseFirst() + releaseSecond() +} + +func TestGeneralServerRuntimeDefaultsAreUnrestricted(t *testing.T) { + registry := newAccessRuntimeRegistry() + if registry.maxWorkers != 0 { + t.Fatalf("default worker limit = %d, want disabled", registry.maxWorkers) + } + if registry.clientMbps != 0 { + t.Fatalf("default client speed limit = %v, want disabled", registry.clientMbps) + } +} + +func TestFiftyClientNineWorkerAcceptanceProfile(t *testing.T) { + previous := accessRuntimes + accessRuntimes = newAccessRuntimeRegistry() + t.Cleanup(func() { accessRuntimes = previous }) + configureAccessRuntime(12, 50) + + releases := make([]func(), 0, 50*9) + for client := 0; client < 50; client++ { + identity := accessIdentity{ + id: "pass:client-" + strconv.Itoa(client), + password: "secret-" + strconv.Itoa(client), + } + for worker := 0; worker < 9; worker++ { + _, release, ok := acquireAccessWorker(identity) + if !ok { + t.Fatalf("client %d worker %d was rejected", client, worker) + } + releases = append(releases, release) + } + } + if len(releases) != 450 { + t.Fatalf("expected 450 workers, got %d", len(releases)) + } + for _, release := range releases { + release() + } +} + +func TestUnlimitedWorkerPolicyDoesNotRestrictGeneralServer(t *testing.T) { + previous := accessRuntimes + accessRuntimes = newAccessRuntimeRegistry() + t.Cleanup(func() { accessRuntimes = previous }) + configureAccessRuntime(0, 50) + + identity := accessIdentity{id: "pass:general", password: "secret-general"} + releases := make([]func(), 0, 256) + for worker := 0; worker < 256; worker++ { + _, release, ok := acquireAccessWorker(identity) + if !ok { + t.Fatalf("general server rejected worker %d with disabled limit", worker) + } + releases = append(releases, release) + } + for _, release := range releases { + release() + } +} + +func TestTokenBucketWaitHonorsContext(t *testing.T) { + bucket := newTokenBucket(1, 1) + if !bucket.allow(1) { + t.Fatal("initial burst was unavailable") + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) + defer cancel() + if err := bucket.wait(ctx, 1); err == nil { + t.Fatal("expected context cancellation while waiting for bandwidth") + } +} + +func TestWireGuardHexToBase64(t *testing.T) { + hexKey := strings.Repeat("01", 32) + got, err := wireGuardHexToBase64(hexKey) + if err != nil { + t.Fatal(err) + } + raw, err := base64.StdEncoding.DecodeString(got) + if err != nil { + t.Fatal(err) + } + if len(raw) != 32 || raw[0] != 1 || raw[31] != 1 { + t.Fatalf("unexpected key conversion: %x", raw) + } +} + +func TestLinuxRuntimeReaders(t *testing.T) { + cpu, err := readProcCPU() + if err != nil || cpu.total == 0 { + t.Fatalf("readProcCPU: %#v, %v", cpu, err) + } + memory, err := readProcMemoryPercent() + if err != nil || memory < 0 || memory > 100 { + t.Fatalf("readProcMemoryPercent: %.2f, %v", memory, err) + } + if _, err := readProcUDPDrops(); err != nil { + t.Fatalf("readProcUDPDrops: %v", err) + } +} diff --git a/wg_backend.go b/wg_backend.go new file mode 100644 index 0000000..e2b26f4 --- /dev/null +++ b/wg_backend.go @@ -0,0 +1,186 @@ +package main + +import ( + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "sync" +) + +type wgDevice interface { + IpcSet(string) error + Close() +} + +type kernelWGDevice struct { + iface string + mu sync.Mutex +} + +func (d *kernelWGDevice) Close() { + if d == nil || d.iface == "" { + return + } + _, _ = runCmd("ip", "link", "del", d.iface) +} + +func (d *kernelWGDevice) IpcSet(configuration string) error { + if d == nil || d.iface == "" { + return errors.New("kernel WireGuard is not initialized") + } + d.mu.Lock() + defer d.mu.Unlock() + + values := make(map[string]string) + for _, line := range strings.Split(configuration, "\n") { + key, value, ok := strings.Cut(strings.TrimSpace(line), "=") + if ok { + values[key] = value + } + } + publicHex := strings.TrimSpace(values["public_key"]) + if publicHex == "" { + return errors.New("kernel WireGuard peer update has no public key") + } + publicKey, err := wireGuardHexToBase64(publicHex) + if err != nil { + return fmt.Errorf("kernel WireGuard public key: %w", err) + } + args := []string{"set", d.iface, "peer", publicKey} + if values["remove"] == "true" { + args = append(args, "remove") + } else if allowedIP := strings.TrimSpace(values["allowed_ip"]); allowedIP != "" { + args = append(args, "allowed-ips", allowedIP) + } else { + return errors.New("kernel WireGuard peer update has no operation") + } + if output, err := runCmd("wg", args...); err != nil { + return fmt.Errorf("wg peer update: %s", output) + } + return nil +} + +func wireGuardHexToBase64(value string) (string, error) { + raw, err := hex.DecodeString(value) + if err != nil { + return "", err + } + if len(raw) != 32 { + return "", fmt.Errorf("key length %d != 32", len(raw)) + } + return base64.StdEncoding.EncodeToString(raw), nil +} + +func startKernelWG(keys *wgKeys, wgPort int, configDir string) (wgDevice, error) { + if !commandExists("wg") || !commandExists("ip") { + return nil, errors.New("commands ip/wg are not installed") + } + _, _ = runCmd("ip", "link", "del", wgIfaceName) + if output, err := runCmd("ip", "link", "add", wgIfaceName, "type", "wireguard"); err != nil { + return nil, fmt.Errorf("kernel WireGuard unavailable: %s", output) + } + dev := &kernelWGDevice{iface: wgIfaceName} + ok := false + defer func() { + if !ok { + dev.Close() + } + }() + + runtimeDir := filepath.Join(configDir, ".runtime") + if err := os.MkdirAll(runtimeDir, 0700); err != nil { + return nil, fmt.Errorf("create WireGuard runtime directory: %w", err) + } + keyFile, err := os.CreateTemp(runtimeDir, "wg-private-*") + if err != nil { + return nil, fmt.Errorf("create WireGuard key file: %w", err) + } + keyPath := keyFile.Name() + defer os.Remove(keyPath) + if err := keyFile.Chmod(0600); err != nil { + keyFile.Close() + return nil, err + } + if _, err := keyFile.WriteString(keys.serverPrivate + "\n"); err != nil { + keyFile.Close() + return nil, err + } + if err := keyFile.Close(); err != nil { + return nil, err + } + if output, err := runCmd( + "wg", "set", wgIfaceName, + "private-key", keyPath, + "listen-port", strconv.Itoa(wgPort), + ); err != nil { + return nil, fmt.Errorf("configure kernel WireGuard: %s", output) + } + if err := configureInterface(wgIfaceName); err != nil { + return nil, err + } + if err := setupFullConeNAT(wgIfaceName); err != nil { + return nil, err + } + ok = true + logWGBackend("kernel") + return dev, nil +} + +func startWGBackend(mode string, keys *wgKeys, wgPort int, configDir string) (wgDevice, error) { + mode = strings.ToLower(strings.TrimSpace(mode)) + if mode == "" { + mode = "auto" + } + switch mode { + case "kernel": + return startKernelWG(keys, wgPort, configDir) + case "userspace": + dev, err := startUserspaceWG(keys, wgPort) + if err == nil { + logWGBackend("userspace") + } + return dev, err + case "auto": + if dev, err := startKernelWG(keys, wgPort, configDir); err == nil { + return dev, nil + } else { + fmt.Printf("[WG] Kernel backend недоступен, использую userspace: %v\n", err) + } + dev, err := startUserspaceWG(keys, wgPort) + if err == nil { + logWGBackend("userspace") + } + return dev, err + default: + return nil, fmt.Errorf("unknown WireGuard backend %q", mode) + } +} + +var activeWGBackend atomicString + +type atomicString struct { + mu sync.RWMutex + value string +} + +func (s *atomicString) Store(value string) { + s.mu.Lock() + s.value = value + s.mu.Unlock() +} + +func (s *atomicString) Load() string { + s.mu.RLock() + defer s.mu.RUnlock() + return s.value +} + +func logWGBackend(name string) { + activeWGBackend.Store(name) + fmt.Printf("[WG] Backend: %s\n", name) +}