diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..6e0e042
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,82 @@
+# История изменений WDTT Plus
+
+Здесь фиксируются заметные пользовательские изменения WDTT Plus.
+
+## v2 — 03.07.2026
+
+Второй выпуск — крупное обновление WDTT Plus.
+
+> [!IMPORTANT]
+> Для корректной работы новых функций и приложения в целом после установки v2 нужно обновить деплой сервера с сохранением данных.
+
+### Клиенты и сервер
+
+- Во вкладке «Деплой» добавлен блок «Клиенты и сервер».
+- Управление клиентами и сервером из приложения находится во вкладке «Деплой» → «Клиенты и сервер»: там доступны создание клиентов, действия выбранного клиента и кнопка «Сервер» для серверных инструментов.
+- Клиентов теперь можно обслуживать прямо из приложения без Telegram-бота: создавать доступы, продлевать срок, отключать, удалять, отвязывать устройства и смотреть подробности.
+- Названия клиентов синхронизируются между Telegram-ботом и приложением: если имя задано при создании или редактировании, оно показывается вместо технического имени устройства или части пароля.
+- Добавлены серверные инструменты: просмотр параметров, обновление сетевых настроек, очистка устаревших записей, сброс статистики и ручной перезапуск службы.
+- Реализованы поиск по данным клиентов и фильтрация по основным параметрам.
+- Изменения клиентов и основных настроек применяются на работающем сервере через admin-команды без перезапуска службы; чувствительные действия требуют отдельного подтверждения.
+- Главный пароль владельца вынесен в отдельный профиль: он не показывается в списках клиентов, доступен отдельным пунктом в приложении и Telegram-боте, а поля владельца сохраняются на сервере и восстанавливаются при подключении без установки.
+
+### Передача и перенос данных
+
+- Приём и передача подключения находятся в плавающей кнопке «Настройки» → «Передать или получить»: раздел «Получение VPN» принимает QR, изображение из галереи или файл, а раздел «Передача VPN» создаёт QR, ссылку или файл текущего VPN-профиля.
+- VPN-профиль можно передать ссылкой, файлом или QR-кодом, а принять — через Android share, выбор файла, камеру или изображение из галереи.
+- QR-коды передачи создаются единообразно во всех местах приложения, с подписью WDTT Plus и иконкой приложения рядом с кодом или под ним.
+- Добавлен выбор профиля для замены при импорте подключения.
+- В режиме администратора добавлена защищённая паролем передача локальных настроек: VPN-профили, параметры деплоя, исключения и настройки выходного IP.
+
+### Деплой и обновление
+
+- Повторный деплой с сохранением данных стал безопаснее: приложение создаёт страховочную копию и проверяет результат обновления.
+- Установка и подключение без установки разделены по направлению данных: перед записью локальных настроек на сервер показываются отличия, а восстановление с готового сервера не изменяет его данные.
+- Добавлено предупреждение о необходимости обновить серверную часть после установки второй версии приложения.
+- Блок «Выходной IP и прокси» умеет читать состояние сервера, заполнять формы после переустановки приложения и проверять установленные WireGuard/VPN-режимы.
+
+### Интерфейс
+
+- В «Инфо → О проекте» добавлена ссылка на историю изменений.
+- Доработана навигация в диалогах и блоке «Клиенты»: закрытие возвращает пользователя к предыдущему меню, а список клиентов, поиск и позиция во вкладке «Деплой» сохраняются при переключении между вкладками.
+
+## v1 — 01.07.2026
+
+Первый публичный выпуск WDTT Plus — переработанной Android-версии WDTT с собственным приложением, серверной частью и деплоем с телефона.
+
+### Деплой и подключение
+
+- Деплой сервера выполняется прямо с телефона по SSH: приложение загружает серверный бинарь, создаёт `systemd`-службу, настраивает WireGuard, NAT/firewall и рабочие UDP-порты.
+- Сервер поддерживает главный пароль владельца и отдельные клиентские пароли со сроком действия, лимитом, привязкой к первому устройству и обновлением WRAP-ключей без перезапуска ядра.
+- Приложение разворачивает серверную часть с телефона и заполняет параметры, необходимые для подключения Android-клиента.
+- Добавлено подключение к уже установленному серверу без переустановки: приложение проверяет главный пароль и заполняет клиентские поля.
+- Повторный деплой поддерживает обновление с сохранением данных и чистую установку.
+- Добавлен перенос сервера через экспорт/импорт: сохраняются пароли, Telegram-настройки, привязки устройств и история; полный экспорт дополнительно переносит WireGuard-ключи.
+- Telegram-бот остаётся основным инструментом для выдачи и обслуживания клиентских доступов в первом выпуске.
+
+### Подключения и VK-хеши
+
+- VK-ссылки можно отправлять в приложение через «Поделиться»: WDTT Plus извлекает хеш звонка, убирает лишние параметры и заполняет свободный слот.
+- Поддерживаются несколько VPN-профилей, чтобы хранить разные подключения и быстро переключаться между ними.
+
+### Транспорт, капча и устойчивость
+
+- Транспорт работает как WireGuard поверх TURN/DTLS с RTP AEAD/WRAP-обфускацией; WRAP-ключ выводится из пароля подключения и не хранится в APK.
+- Добавлен режим VKCalls для анонимного получения TURN-учётных данных без прохождения капчи, если звонок VK разрешает такой вход.
+- Добавлена проверка VK-хешей по слотам с понятным статусом и прохождением captcha при необходимости.
+- Captcha-цепочка стала устойчивее: VKCalls preflight, Auto WebView, Go v2 и ручной WebView используются по очереди, а строгие slider/puzzle-проверки передаются пользователю.
+- Улучшены восстановление после смены сети, пробуждения устройства, DNS-сбоев и падения нативного процесса; VPN корректно освобождает системный слот, если Android или другой VPN забирает управление.
+
+### Маршрутизация и выходной IP
+
+- Добавлены независимые списки исключений приложений: в ЧС выбранные приложения обходят VPN, в БС только выбранные приложения идут через VPN.
+- Добавлены режимы выходного IP для пользователей WDTT: прямой выход, прокси VPS, внешний TCP-прокси, WireGuard-выход через другой сервер и VPN/WARP-файл в формате WireGuard `.conf`.
+- Управление выходным IP доступно из Android-приложения и Telegram-бота, с проверками, диагностикой и откатом нерабочей конфигурации.
+
+### Интерфейс и диагностика
+
+- Добавлено полноценное Android-приложение на Jetpack Compose с VPN-профилями, темами, логами, автообновлениями и отдельным пакетом `com.wdtt.plus`.
+- Добавлены системные способы быстрого управления туннелем: плитка быстрых настроек Android и виджет с отображением состояния.
+- Добавлен живой лог-вьюер с группировкой повторяющихся сообщений, статусами Go-клиента, DTLS, WireGuard, WRAP, капчи, деплоя и статистики.
+- Добавлены проверка обновлений из GitHub Releases и сбор диагностического отчёта для обращения в issue.
+- Переработано множество мелких и внутренних деталей, не вынесенных в этот список.
diff --git a/README.md b/README.md
index 66623fb..837c331 100644
--- a/README.md
+++ b/README.md
@@ -43,11 +43,11 @@
### Что изменено в модификации
-- **Расширенное управление сервером:** Telegram-бот вынесен в отдельный модуль с inline-меню, редактируемыми карточками и подтверждением важных действий. Из бота настраиваются DNS, публичный адрес, лимит доступов и порты; доступны названия и бессрочный срок паролей, история привязок устройств и статистика трафика по периодам.
-- **Обновление, восстановление и перенос сервера:** повторный деплой предлагает обновление с сохранением данных или чистую установку. После переустановки APK можно подключиться к уже работающему серверу, а экспорт/импорт переносит базу доступов и при необходимости WireGuard-ключи.
-- **Ссылки и роли:** `wdtt://` поддерживает домены, открывается как Android-ссылка, проверяется до запуска и импортируется в свободный VPN-профиль. При первом запуске выбирается интерфейс пользователя или администратора; VK-ссылки можно передавать приложению через системное меню **«Поделиться»**.
+- **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями.
+- **Обновление, восстановление и перенос сервера:** повторный деплой предлагает безопасное обновление с сохранением данных или чистую установку. Перед обновлением создаётся страховочная копия сервера; новая служба и целостность доступов проверяются, а при ошибке выполняется откат. Экспорт/импорт переносит базу доступов и при необходимости WireGuard-ключи.
+- **Ссылки, роли и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Импорт проверяется и занимает свободный VPN-профиль; при трёх занятых приложение запрашивает выбор профиля для замены. Для администратора доступен защищённый паролем перенос локальных настроек.
- **Проверка VK-хешей:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Настройка мощности сопровождается пояснением о потоках, нагрузке и частоте проверок VK.
-- **Настраиваемый выходной IP:** из Android и Telegram-бота управляются прямой выход, локальный 3proxy, внешний SOCKS5/HTTP-прокси, готовый WireGuard-профиль и WireGuard exit с проверкой и откатом нерабочей конфигурации.
+- **Настраиваемый выходной IP:** из Android и Telegram-бота управляются прямой выход, прокси VPS, внешний TCP-прокси, VPN/WARP-файл в формате WireGuard `.conf` и WireGuard-выход через другой сервер с проверкой, восстановлением полей с сервера и откатом нерабочей конфигурации.
- **Маршрутизация приложений:** ЧС и БС являются отдельными списками: в ЧС отмеченные приложения обходят VPN, в БС только отмеченные идут через VPN. Есть быстрый подбор приложений, чувствительных к VPN; смена режима перезапускает только WireGuard-слой.
- **Captcha и устойчивость транспорта:** перед captcha-цепочкой можно использовать VKCalls preflight; временный flood не создаёт повторный шквал запросов. Авто-режим начинает с Auto WebView и переходит к Go v2 и ручному WebView только при необходимости. Расширены восстановление после смены сети и пробуждения, контроль зависшего трафика и fail-open отключение неработающего VPN.
- **Самостоятельная сборка WDTT Plus:** приложение использует пакет `com.wdtt.plus`, собственный канал обновлений и отдельное оформление. Gradle пересобирает Android `libclient.so` и сервер для деплоя из исходников, а release APK получает понятные имена для каждой ABI.
@@ -58,13 +58,14 @@
- **Корректная передача VPN-слота:** если Android отключает WDTT Plus VPN или другой VPN забирает системный VPN-слот, WDTT Plus останавливает транспорт и переводит плитку/виджет в неактивное состояние.
- **TURN/DTLS-транспорт:** нативный Go-клиент получает временные TURN-учётные данные VK-звонка и поднимает DTLS-соединения к relay-серверу, через который передаётся трафик до вашего сервера.
- **Импорт VK-ссылок через «Поделиться»:** ссылку VK-звонка можно отправить прямо в WDTT Plus. Приложение извлечёт хеш после `/call/join/`, заполнит следующий слот VK-хеша и покажет, какой номер был обновлён.
+- **Передача между устройствами:** текущий VPN-профиль отправляется как `wdtt://`-ссылка, файл или QR-код. Приложение принимает эти данные через Android, камеру, галерею и выбор файла, сохраняя совместимость со старыми ссылками.
- **Проверка 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.
- **Деплой с телефона:** вкладка **«Деплой»** подключается к серверу по SSH, загружает `wdtt-server`, создаёт `systemd`-сервис, включает NAT/firewall и открывает рабочие UDP-порты.
-- **Подключение к готовому серверу:** если сервер уже установлен, приложение может проверить SSH-доступ и главный пароль, забрать клиентские поля с сервера и заполнить их без повторного деплоя.
-- **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит активных пользовательских паролей, 16-символьную генерацию, привязку пароля к устройству, истечение срока и управление через Telegram-бота.
+- **Подключение к готовому серверу:** если сервер уже установлен, приложение проверяет SSH-доступ и главный пароль, показывает отличия и после подтверждения восстанавливает локальные поля. Этот режим работает только от сервера к приложению и ничего не записывает на сервер.
+- **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит пользовательских паролей, 16-символьную генерацию, привязку к устройству и срок действия. Клиентов можно создавать, отключать, продлевать, отвязывать и удалять из приложения или Telegram-бота.
- **Горячее обновление WRAP-ключей:** создание, удаление и истечение паролей обновляют набор WRAP-ключей на сервере без перезапуска ядра.
- **Исключения приложений:** ЧС и БС хранят независимые наборы. В ЧС отмеченные приложения работают напрямую, в БС только отмеченные направляются в VPN; изменения применяются быстрой перезагрузкой WireGuard.
- **Рабочая captcha-цепочка:** сначала приложение пробует получить TURN credentials через отключаемый VKCalls preflight. Если анонимный вход недоступен, Auto WebView решает обычную проверку, Go v2 используется как следующий автоматический этап, а ручной WebView остаётся fallback для slider/puzzle и других строгих проверок.
@@ -105,7 +106,7 @@ Android-приложение → VpnService / WireGuard GoBackend → локал
Если на сервере уже есть установленный WDTT Plus, приложение покажет предупреждение перед деплоем. Режим **«Обновить с сохранением»** заменит серверный бинарник и применит настройки из текущих полей деплоя, сохранив выданные ссылки, привязки устройств, историю и WireGuard-ключи. Режим **«Начать с нуля»** удалит серверные данные WDTT Plus и развернёт чистую установку.
-Для переноса на другой сервер во вкладке **«Деплой»** используйте блок **«Перенос сервера»**. Экспорт проверяет доступ к серверу и структуру базы перед сохранением файла, затем сохраняет пароли, Telegram-настройки, привязки устройств и историю. Полный экспорт дополнительно сохраняет WireGuard-ключи сервера/клиентов: это полезно при переезде своего сервера, чтобы привязки устройств и серверная WireGuard-идентичность сохранились. Старые `wdtt://` ссылки останутся рабочими без перевыдачи только если в них был домен и DNS этого домена теперь указывает на новый сервер; ссылки со старым IP нужно сгенерировать и отправить пользователям заново. Импорт можно выполнить при деплое или на уже работающем сервере: режим **«Заменить»** подходит для переезда, режим **«Добавить»** добавляет отсутствующие записи без перезаписи конфликтов. Перед применением приложение показывает подтверждение и берёт новый адрес сервера, порты и DNS из текущих полей деплоя.
+Для переноса на другой сервер во вкладке **«Деплой»** используйте блок **«Перенос сервера»**. Экспорт проверяет доступ к серверу и структуру базы перед сохранением файла, затем сохраняет пароли, Telegram-настройки, привязки устройств и историю. Полный экспорт дополнительно сохраняет WireGuard-ключи сервера/клиентов: это полезно при переезде своего сервера, чтобы привязки устройств и серверная WireGuard-идентичность сохранились. Старые `wdtt://` ссылки останутся рабочими без перевыдачи только если в них был домен и DNS этого домена теперь указывает на новый сервер; ссылки со старым IP нужно сгенерировать и отправить пользователям заново. Импорт можно выполнить при деплое или на уже работающем сервере: режим **«Заменить»** подходит для переезда, режим **«Добавить»** добавляет отсутствующие записи без перезаписи конфликтов. Перед применением приложение показывает подтверждение и берёт новый адрес сервера, порты и DNS из текущих полей деплоя. Настройки выходного IP, прокси и VPN/WARP-файлы серверным экспортом не переносятся — после переезда нужный режим выхода включается на новом сервере заново.
## Получение VK-хеша
@@ -146,14 +147,23 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se
Сервер WDTT Plus поддерживает две модели подключения:
- **Главный пароль:** задаётся при деплое и используется владельцем сервера.
-- **Сгенерированные пароли:** создаются при деплое или через Telegram-бота, имеют срок действия, привязываются к первому устройству и обновляют WRAP-ключи на сервере без перезапуска.
+- **Сгенерированные пароли:** создаются из приложения или Telegram-бота, имеют срок действия, привязываются к первому устройству и обновляют WRAP-ключи на сервере без перезапуска.
-Лимит активных пользовательских паролей задаётся в настройках Telegram-бота. Новые пароли генерируются длиной **16 символов**.
+В блоке **«Клиенты и сервер»** вкладки **«Деплой»** можно искать и фильтровать клиентов, создавать доступы, редактировать их параметры, срок и привязку устройства, а также передавать подключение ссылкой, файлом или QR-кодом. Там же доступны история, трафик, настройки сервера, очистка устаревших записей и сервисные действия.
-Команда `/list` показывает активные пароли и устройства. Через inline-кнопки можно отвязать устройство или удалить пароль. При удалении или истечении пароля соответствующий WRAP-ключ удаляется из памяти сервера.
+Обычные изменения применяются работающим сервером сразу и не прерывают остальных клиентов: Android вызывает admin-команды по SSH, а они обращаются к закрытому локальному сокету `wdtt-server`, не открывая отдельный управляющий порт в сеть. Явный перезапуск сервиса оставлен отдельным подтверждаемым действием. При удалении или истечении пароля соответствующий WRAP-ключ удаляется из памяти сервера.
## Дополнительные возможности
+#### Передача между устройствами
+
+Раздел **«Передать или получить»** находится в боковых настройках. Пользователь может отправить активный VPN-профиль ссылкой, файлом или QR-кодом; на другом устройстве данные можно открыть напрямую, выбрать как файл, отсканировать камерой либо распознать на изображении из галереи. Приложение использует первый пустой профиль VPN, а если заняты все три — предлагает выбрать профиль и подтвердить замену.
+
+В режиме администратора там же можно передать все локальные VPN-профили, параметры деплоя, исключения и настройки выхода. Такой экспорт шифруется отдельным паролем; пароль не сохраняется и должен передаваться получателю отдельно. Резервная копия состояния самого сервера по-прежнему импортируется через **«Деплой» → «Перенос сервера»**.
+
+> [!WARNING]
+> Ссылка и пользовательский QR содержат пароль подключения и VK-хеши. Не публикуйте их и передавайте только доверенному получателю.
+
#### Исключения приложений
Вкладка **«Исключ.»** показывает установленные приложения с поиском. В режиме ЧС отмеченные приложения обходят VPN, а в режиме БС только отмеченные приложения идут через VPN. ЧС и БС запоминают свои наборы галочек независимо; переключение активного режима быстро перезапускает только WireGuard-слой. Само приложение WDTT Plus и VK-клиенты всегда обходят VPN, чтобы не ломать TURN-соединение.
@@ -175,7 +185,17 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se
#### Выходной IP и прокси
-Первичная установка сложных схем выхода выполняется из приложения во вкладке **«Деплой»**. Telegram-бот в настройках сервера умеет посмотреть статус и диагностику, вернуть режим `direct`, создать/проверить/остановить локальный SOCKS5/HTTP-прокси на текущем сервере, включить внешний SOCKS5/HTTP-прокси и посмотреть или отключить WireGuard exit. В Android также можно подключить готовый WireGuard-конфиг как отдельную точку выхода.
+Первичная настройка выполняется во вкладке **«Деплой»** в блоке **«Выходной IP и прокси»**. Эти режимы меняют IP, который видят сайты и сервисы у пользователей WDTT; сам адрес WDTT-сервера, входящие DTLS/SSH и ссылка подключения этим не скрываются.
+
+Формы этого блока можно заполнить с сервера: приложение читает сохранённый профиль администратора и текущие конфиги прокси/WireGuard. При установке направление обратное — текущие поля приложения сохраняются на сервере; перед заменой отличающихся серверных значений приложение предупреждает об этом. Профиль также обновляется при включении режимов из приложения.
+
+- **Прямой выход** — трафик пользователей выходит через текущий VPS.
+- **Прокси VPS** — создаёт SOCKS5/HTTP-прокси на этом же сервере. IP не скрывает, потому что выход остаётся через текущий VPS.
+- **Внешний TCP-прокси** — направляет обычные TCP-подключения через внешний SOCKS5/HTTP-прокси. UDP, QUIC и часть звонкового трафика могут идти напрямую.
+- **Другой сервер** — подключает отдельный VPS по WireGuard и выпускает пользователей через него. Это самый понятный вариант для отдельного выходного IP.
+- **VPN/WARP-файл** — подключает готовый WireGuard `.conf` как выход только для пользователей WDTT. WARP подходит, если он сохранён именно как WireGuard-конфиг с `[Interface]` и `[Peer]`; профиль `warp-cli`, MASQUE или Zero Trust-настройки напрямую сюда не импортируются.
+
+Telegram-бот умеет посмотреть статус и диагностику выхода, вернуть режим `direct`, создать/проверить/остановить прокси VPS, включить внешний TCP-прокси и посмотреть или отключить WireGuard/VPN-выход.
#### Обновления
diff --git a/admin.go b/admin.go
new file mode 100644
index 0000000..62c9f59
--- /dev/null
+++ b/admin.go
@@ -0,0 +1,1359 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "golang.zx2c4.com/wireguard/device"
+)
+
+type adminResponse struct {
+ OK bool `json:"ok"`
+ 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"`
+}
+
+type adminRequest struct {
+ MainPassword string `json:"main_password"`
+ Args []string `json:"args"`
+}
+
+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"`
+}
+
+type adminTrafficValue struct {
+ Down int64 `json:"down"`
+ Up int64 `json:"up"`
+}
+
+type adminTrafficPeriod struct {
+ Today adminTrafficValue `json:"today"`
+ Week adminTrafficValue `json:"week"`
+ Month adminTrafficValue `json:"month"`
+ All adminTrafficValue `json:"all"`
+}
+
+type adminDeviceInfo struct {
+ DeviceID string `json:"device_id"`
+ IP string `json:"ip,omitempty"`
+ Name string `json:"name,omitempty"`
+ Manufacturer string `json:"manufacturer,omitempty"`
+ Brand string `json:"brand,omitempty"`
+ Model string `json:"model,omitempty"`
+ AndroidVersion string `json:"android_version,omitempty"`
+ SDK int `json:"sdk,omitempty"`
+ ABI string `json:"abi,omitempty"`
+ AppVersion string `json:"app_version,omitempty"`
+ Locale string `json:"locale,omitempty"`
+ Country string `json:"country,omitempty"`
+ TimeZone string `json:"time_zone,omitempty"`
+ RemoteIP string `json:"remote_ip,omitempty"`
+ LastSeenAt int64 `json:"last_seen_at,omitempty"`
+}
+
+type adminPasswordInfo struct {
+ Password string `json:"password"`
+ Label string `json:"label,omitempty"`
+ VkHash string `json:"vk_hash,omitempty"`
+ Ports string `json:"ports"`
+ Status string `json:"status"`
+ ExpiresAt int64 `json:"expires_at,omitempty"`
+ DownBytes int64 `json:"down_bytes,omitempty"`
+ UpBytes int64 `json:"up_bytes,omitempty"`
+ DeviceID string `json:"device_id,omitempty"`
+ DeviceName string `json:"device_name,omitempty"`
+ DeviceIP string `json:"device_ip,omitempty"`
+ DeviceLastSeen int64 `json:"device_last_seen,omitempty"`
+ BindEventsCount int `json:"bind_events_count,omitempty"`
+ Traffic adminTrafficPeriod `json:"traffic"`
+ Device *adminDeviceInfo `json:"device,omitempty"`
+ BindHistory []BindHistoryEntry `json:"bind_history,omitempty"`
+}
+
+func runAdminCLI(args []string) int {
+ fs := flag.NewFlagSet("admin", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ configDir := fs.String("config-dir", "/etc/wdtt", "директория конфигурации WDTT")
+ mainPassword := fs.String("main-password", "", "главный пароль администратора для проверки")
+ offline := fs.Bool("offline", false, "изменить остановленный сервер напрямую (потребуется запуск сервиса)")
+ if err := fs.Parse(args); err != nil {
+ writeAdminError(err)
+ return 2
+ }
+ rest := fs.Args()
+ if len(rest) == 0 {
+ writeAdminError(errors.New("укажите admin-команду"))
+ return 2
+ }
+
+ if !*offline {
+ response, err := callAdminSocket(*configDir, adminRequest{
+ MainPassword: *mainPassword,
+ Args: rest,
+ })
+ if err != nil {
+ writeAdminError(fmt.Errorf("admin_socket_unavailable: %w; заново установите сервер из WDTT Plus или используйте --offline только при остановленном wdtt.service", err))
+ return 1
+ }
+ writeAdminJSON(response)
+ if !response.OK {
+ return 1
+ }
+ return 0
+ }
+
+ loaded, err := readAdminDB(*configDir)
+ if err != nil {
+ writeAdminError(err)
+ return 1
+ }
+ if strings.TrimSpace(*mainPassword) != "" && loaded.MainPassword != *mainPassword {
+ writeAdminError(errors.New("главный пароль администратора не совпадает"))
+ return 1
+ }
+ response, err := executeAdminCommand(*configDir, loaded, rest, nil, false)
+ if err != nil {
+ writeAdminError(err)
+ return 1
+ }
+ writeAdminJSON(response)
+ return 0
+}
+
+func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDev *device.Device, live bool) (adminResponse, error) {
+ var response adminResponse
+ var err error
+ snapshot := captureAdminLiveSnapshot(loaded, rest)
+ if live && len(rest) > 0 && rest[0] == "create" {
+ cleanupExpiredPasswordsLocked(wgDev)
+ }
+ switch rest[0] {
+ case "list":
+ response = adminResponse{
+ OK: true,
+ Server: buildAdminServerInfo(configDir, loaded),
+ Passwords: buildAdminPasswordList(loaded),
+ }
+ case "details":
+ response, err = adminPasswordDetails(configDir, loaded, rest[1:])
+ case "create":
+ response, err = adminCreatePassword(configDir, loaded, rest[1:])
+ case "delete":
+ response, err = adminDeletePassword(configDir, loaded, rest[1:])
+ case "unbind":
+ response, err = adminUnbindPassword(configDir, loaded, rest[1:])
+ case "deactivate":
+ response, err = adminSetPasswordActivation(configDir, loaded, rest[1:], true)
+ case "activate":
+ response, err = adminSetPasswordActivation(configDir, loaded, rest[1:], false)
+ case "set-label":
+ response, err = adminSetPasswordLabel(configDir, loaded, rest[1:])
+ case "set-hash":
+ response, err = adminSetPasswordHash(configDir, loaded, rest[1:])
+ case "set-expiry":
+ response, err = adminSetPasswordExpiry(configDir, loaded, rest[1:])
+ case "set-ports":
+ response, err = adminSetPasswordPorts(configDir, loaded, rest[1:])
+ case "update-client":
+ response, err = adminUpdateClient(configDir, loaded, rest[1:])
+ case "set-dns":
+ response, err = adminSetDNS(configDir, loaded, rest[1:])
+ case "set-limit":
+ response, err = adminSetLimit(configDir, loaded, rest[1:])
+ case "set-default-ports":
+ response, err = adminSetDefaultPorts(configDir, loaded, rest[1:])
+ case "set-public-ip":
+ response, err = adminSetPublicIP(configDir, loaded, rest[1:])
+ case "update-settings":
+ response, err = adminUpdateSettings(configDir, loaded, rest[1:])
+ case "update-admin-profile":
+ response, err = adminUpdateAdminProfile(configDir, loaded, rest[1:])
+ case "refresh-public-ip":
+ response, err = adminRefreshPublicIP(configDir, loaded, live)
+ case "cleanup-expired":
+ response, err = adminCleanupExpired(configDir, loaded, wgDev, live)
+ case "cleanup-orphans":
+ response, err = adminCleanupOrphans(configDir, loaded, wgDev, live)
+ case "reset-traffic":
+ response, err = adminResetTraffic(configDir, loaded)
+ case "restart":
+ response = adminResponse{OK: true, Message: "Перезапуск сервиса", RestartRequired: true}
+ default:
+ err = fmt.Errorf("неизвестная admin-команда: %s", rest[0])
+ }
+ if err != nil || !live {
+ return response, err
+ }
+ if err := applyLiveAdminEffects(configDir, loaded, rest, response, snapshot, wgDev); err != nil {
+ return adminResponse{}, err
+ }
+ if rest[0] != "restart" {
+ response.RestartRequired = false
+ }
+ return response, nil
+}
+
+func captureAdminLiveSnapshot(loaded *Database, args []string) adminLiveSnapshot {
+ if len(args) == 0 {
+ return adminLiveSnapshot{}
+ }
+ switch args[0] {
+ case "delete", "unbind", "deactivate", "activate":
+ password, err := adminPasswordArg(args[0], args[1:])
+ if err != nil {
+ return adminLiveSnapshot{}
+ }
+ snapshot := adminLiveSnapshot{password: password}
+ if entry := loaded.Passwords[password]; entry != nil && entry.DeviceID != "" {
+ if dev := loaded.Devices[entry.DeviceID]; dev != nil {
+ copyOfDevice := *dev
+ snapshot.device = ©OfDevice
+ }
+ }
+ return snapshot
+ default:
+ return adminLiveSnapshot{}
+ }
+}
+
+func applyLiveAdminEffects(configDir string, loaded *Database, args []string, response adminResponse, snapshot adminLiveSnapshot, wgDev *device.Device) error {
+ if len(args) == 0 {
+ return nil
+ }
+ switch args[0] {
+ case "create":
+ if response.Password == nil {
+ return errors.New("сервер создал клиента без пароля")
+ }
+ password := response.Password.Password
+ if err := serverWrapKeys.AddPassword(password); err != nil {
+ delete(loaded.Passwords, password)
+ _ = saveAdminDB(configDir, loaded)
+ return fmt.Errorf("не удалось добавить WRAP-ключ: %w", err)
+ }
+ case "delete":
+ if !isAdminSnapshotDevice(loaded, snapshot) {
+ removePeerFromWG(wgDev, snapshot.device)
+ }
+ serverWrapKeys.RemovePassword(snapshot.password)
+ case "unbind":
+ if !isAdminSnapshotDevice(loaded, snapshot) {
+ removePeerFromWG(wgDev, snapshot.device)
+ }
+ case "deactivate":
+ if !isAdminSnapshotDevice(loaded, snapshot) {
+ removePeerFromWG(wgDev, snapshot.device)
+ }
+ serverWrapKeys.RemovePassword(snapshot.password)
+ case "activate":
+ if err := serverWrapKeys.AddPassword(snapshot.password); err != nil {
+ if entry := loaded.Passwords[snapshot.password]; entry != nil {
+ entry.IsDeactivated = true
+ _ = saveAdminDB(configDir, loaded)
+ }
+ return fmt.Errorf("не удалось вернуть WRAP-ключ: %w", err)
+ }
+ upsertPeerInWG(wgDev, snapshot.device)
+ case "set-dns", "update-settings":
+ setServerDNS(loaded.DNS)
+ setServerDefaultPorts(loaded.DefaultPorts)
+ setServerPublicIPOverride(loaded.PublicIP)
+ maxGeneratedPasswords = loaded.MaxPasswords
+ if loaded.PublicIP == "" {
+ publicIP = ""
+ }
+ case "set-limit":
+ maxGeneratedPasswords = loaded.MaxPasswords
+ case "set-default-ports":
+ setServerDefaultPorts(loaded.DefaultPorts)
+ case "set-public-ip":
+ setServerPublicIPOverride(loaded.PublicIP)
+ if loaded.PublicIP == "" {
+ publicIP = ""
+ }
+ }
+ return nil
+}
+
+func isAdminSnapshotDevice(loaded *Database, snapshot adminLiveSnapshot) bool {
+ if snapshot.device == nil {
+ return false
+ }
+ _, ok := adminDeviceIDSet(loaded)[snapshot.device.DeviceID]
+ return ok
+}
+
+func adminSocketPath(configDir string) string {
+ if filepath.Clean(configDir) == "/etc/wdtt" {
+ return "/run/wdtt/admin.sock"
+ }
+ return filepath.Join(configDir, "admin.sock")
+}
+
+func callAdminSocket(configDir string, request adminRequest) (adminResponse, error) {
+ conn, err := net.DialTimeout("unix", adminSocketPath(configDir), 3*time.Second)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ defer conn.Close()
+ _ = conn.SetDeadline(time.Now().Add(15 * time.Second))
+ if err := json.NewEncoder(conn).Encode(request); err != nil {
+ return adminResponse{}, err
+ }
+ var response adminResponse
+ if err := json.NewDecoder(io.LimitReader(conn, 2<<20)).Decode(&response); err != nil {
+ return adminResponse{}, err
+ }
+ return response, nil
+}
+
+func startAdminSocket(ctx context.Context, configDir string, wgDev *device.Device) error {
+ path := adminSocketPath(configDir)
+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
+ return err
+ }
+ if err := os.Chmod(filepath.Dir(path), 0700); err != nil {
+ return err
+ }
+ _ = os.Remove(path)
+ listener, err := net.Listen("unix", path)
+ if err != nil {
+ return err
+ }
+ if err := os.Chmod(path, 0600); err != nil {
+ listener.Close()
+ _ = os.Remove(path)
+ return err
+ }
+ context.AfterFunc(ctx, func() {
+ listener.Close()
+ _ = os.Remove(path)
+ })
+ go func() {
+ for {
+ conn, err := listener.Accept()
+ if err != nil {
+ if ctx.Err() == nil {
+ log.Printf("[ADMIN] socket accept: %v", err)
+ }
+ return
+ }
+ go handleAdminSocketConn(conn, configDir, wgDev)
+ }
+ }()
+ log.Printf("[ADMIN] Локальное управление: %s", path)
+ return nil
+}
+
+func handleAdminSocketConn(conn net.Conn, configDir string, wgDev *device.Device) {
+ defer conn.Close()
+ _ = conn.SetDeadline(time.Now().Add(15 * time.Second))
+ var request adminRequest
+ if err := json.NewDecoder(io.LimitReader(conn, 2<<20)).Decode(&request); err != nil {
+ _ = json.NewEncoder(conn).Encode(adminResponse{OK: false, Message: "некорректный admin-запрос"})
+ return
+ }
+ if len(request.Args) == 0 {
+ _ = json.NewEncoder(conn).Encode(adminResponse{OK: false, Message: "не указана admin-команда"})
+ return
+ }
+ dbMutex.Lock()
+ defer dbMutex.Unlock()
+ if strings.TrimSpace(request.MainPassword) == "" || db.MainPassword != request.MainPassword {
+ _ = json.NewEncoder(conn).Encode(adminResponse{OK: false, Message: "главный пароль администратора не совпадает"})
+ return
+ }
+ response, err := executeAdminCommand(configDir, db, request.Args, wgDev, true)
+ if err != nil {
+ response = adminResponse{OK: false, Message: err.Error()}
+ }
+ _ = json.NewEncoder(conn).Encode(response)
+}
+
+func readAdminDB(configDir string) (*Database, error) {
+ path := filepath.Join(configDir, "passwords.json")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, fmt.Errorf("no_passwords_json: %s", path)
+ }
+ return nil, err
+ }
+ var loaded Database
+ if err := json.Unmarshal(data, &loaded); err != nil {
+ return nil, fmt.Errorf("bad_passwords_json: %w", err)
+ }
+ ensureAdminDBDefaults(&loaded)
+ return &loaded, nil
+}
+
+func ensureAdminDBDefaults(loaded *Database) {
+ if loaded.Passwords == nil {
+ loaded.Passwords = make(map[string]*PasswordEntry)
+ }
+ if loaded.Devices == nil {
+ loaded.Devices = make(map[string]*ClientDevice)
+ }
+ if strings.TrimSpace(loaded.DNS) == "" {
+ loaded.DNS = defaultDNS
+ }
+ if strings.TrimSpace(loaded.DefaultPorts) == "" {
+ loaded.DefaultPorts = "56000,56001,9000"
+ }
+ if loaded.MaxPasswords <= 0 {
+ loaded.MaxPasswords = defaultMaxGeneratedPasswords
+ }
+ if loaded.MaxPasswords > 500 {
+ loaded.MaxPasswords = 500
+ }
+ loaded.AdminProfile = normalizeAdminProfileForStorage(loaded.AdminProfile, loaded.DefaultPorts)
+}
+
+func normalizeAdminProfileForStorage(profile AdminProfileEntry, defaultPorts string) AdminProfileEntry {
+ normalizedDefaultPorts, err := parsePortsSpec(defaultPorts)
+ if err != nil {
+ normalizedDefaultPorts = "56000,56001,9000"
+ }
+ profile.VkHashes = strings.TrimSpace(profile.VkHashes)
+ profile.SecondaryVkHash = strings.TrimSpace(profile.SecondaryVkHash)
+ if profile.WorkersPerHash < 1 || profile.WorkersPerHash > 128 {
+ profile.WorkersPerHash = 16
+ }
+ protocol, err := normalizeAdminProfileProtocol(profile.Protocol)
+ if err != nil {
+ protocol = "udp"
+ }
+ profile.Protocol = protocol
+ ports, err := parsePortsSpec(profile.Ports)
+ if err != nil {
+ ports = normalizedDefaultPorts
+ }
+ profile.Ports = ports
+ if profile.ListenPort < 1 || profile.ListenPort > 65535 {
+ profile.ListenPort = adminProfileDefaultListenPort(profile.Ports)
+ }
+ profile.SNI = normalizeAdminProfileSNI(profile.SNI)
+ profile.DeviceIDs = normalizeAdminProfileDeviceIDs(profile.DeviceIDs)
+ return profile
+}
+
+func normalizeAdminProfileForView(profile AdminProfileEntry, defaultPorts string) AdminProfileEntry {
+ return normalizeAdminProfileForStorage(profile, defaultPorts)
+}
+
+func normalizeAdminProfileProtocol(value string) (string, error) {
+ value = strings.ToLower(strings.TrimSpace(value))
+ if value == "" {
+ return "udp", nil
+ }
+ switch value {
+ case "udp", "tcp":
+ return value, nil
+ default:
+ return "", errors.New("protocol должен быть udp или tcp")
+ }
+}
+
+func normalizeAdminProfileSNI(value string) string {
+ value = strings.TrimSpace(value)
+ value = strings.Map(func(r rune) rune {
+ if r < 32 || r == 127 {
+ return -1
+ }
+ return r
+ }, value)
+ if len([]rune(value)) > 253 {
+ value = string([]rune(value)[:253])
+ }
+ return value
+}
+
+func normalizeAdminProfileDeviceIDs(values []string) []string {
+ if len(values) == 0 {
+ return nil
+ }
+ seen := make(map[string]struct{}, len(values))
+ cleaned := make([]string, 0, len(values))
+ for _, value := range values {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ continue
+ }
+ if _, ok := seen[value]; ok {
+ continue
+ }
+ seen[value] = struct{}{}
+ cleaned = append(cleaned, value)
+ if len(cleaned) >= 64 {
+ break
+ }
+ }
+ if len(cleaned) == 0 {
+ return nil
+ }
+ return cleaned
+}
+
+func adminProfileDefaultListenPort(ports string) int {
+ parts := strings.Split(ports, ",")
+ if len(parts) == 3 {
+ if port, err := strconv.Atoi(strings.TrimSpace(parts[2])); err == nil && port >= 1 && port <= 65535 {
+ return port
+ }
+ }
+ return 9000
+}
+
+func saveAdminDB(configDir string, loaded *Database) error {
+ ensureAdminDBDefaults(loaded)
+ data, err := json.MarshalIndent(loaded, "", " ")
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(configDir, 0700); err != nil {
+ return err
+ }
+ path := filepath.Join(configDir, "passwords.json")
+ tmp := path + ".admin.tmp"
+ if err := os.WriteFile(tmp, data, 0600); err != nil {
+ return err
+ }
+ return os.Rename(tmp, path)
+}
+
+func buildAdminServerInfo(configDir string, loaded *Database) *adminServerInfo {
+ expired := 0
+ usedDevices := make(map[string]struct{})
+ for _, entry := range loaded.Passwords {
+ if entry == nil {
+ continue
+ }
+ if isPasswordExpired(entry) {
+ expired++
+ }
+ if entry.DeviceID != "" {
+ usedDevices[entry.DeviceID] = struct{}{}
+ }
+ }
+ for deviceID := range adminDeviceIDSet(loaded) {
+ usedDevices[deviceID] = struct{}{}
+ }
+ orphans := 0
+ orphanDevices := make([]adminDeviceInfo, 0)
+ for deviceID := range loaded.Devices {
+ if _, used := usedDevices[deviceID]; !used {
+ orphans++
+ if dev := loaded.Devices[deviceID]; dev != nil {
+ orphanDevices = append(orphanDevices, buildAdminDeviceInfo(dev))
+ }
+ }
+ }
+ sort.SliceStable(orphanDevices, func(i, j int) bool {
+ return strings.ToLower(orphanDevices[i].Name+orphanDevices[i].DeviceID) < strings.ToLower(orphanDevices[j].Name+orphanDevices[j].DeviceID)
+ })
+ effectivePublic := loaded.PublicIP
+ if effectivePublic == "" {
+ effectivePublic = publicIP
+ }
+ 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),
+ }
+}
+
+func buildAdminProfileInfo(loaded *Database) AdminProfileEntry {
+ return normalizeAdminProfileForView(loaded.AdminProfile, loaded.DefaultPorts)
+}
+
+func buildAdminPasswordList(loaded *Database) []adminPasswordInfo {
+ result := make([]adminPasswordInfo, 0, len(loaded.Passwords))
+ for password, entry := range loaded.Passwords {
+ info := buildAdminPasswordInfo(loaded, password, entry)
+ info.Device = nil
+ info.BindHistory = nil
+ result = append(result, info)
+ }
+ sort.SliceStable(result, func(i, j int) bool {
+ left := strings.ToLower(strings.TrimSpace(result[i].Label))
+ right := strings.ToLower(strings.TrimSpace(result[j].Label))
+ if left == "" {
+ left = strings.ToLower(result[i].Password)
+ }
+ if right == "" {
+ right = strings.ToLower(result[j].Password)
+ }
+ return left < right
+ })
+ return result
+}
+
+func adminPasswordDetails(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ password, err := adminPasswordArg("details", args)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ entry, err := requireAdminPassword(loaded, password)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{
+ OK: true, Server: buildAdminServerInfo(configDir, loaded),
+ Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, password, entry)),
+ }, nil
+}
+
+func buildAdminPasswordInfo(loaded *Database, password string, entry *PasswordEntry) adminPasswordInfo {
+ info := adminPasswordInfo{
+ Password: password,
+ Ports: loaded.DefaultPorts,
+ Status: "active",
+ }
+ if entry == nil {
+ info.Status = "broken"
+ return info
+ }
+ if strings.TrimSpace(entry.Ports) != "" {
+ info.Ports = entry.Ports
+ }
+ info.Label = entry.Label
+ info.VkHash = entry.VkHash
+ info.ExpiresAt = entry.ExpiresAt
+ 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) {
+ info.Status = "expired"
+ }
+ if entry.DeviceID != "" {
+ if dev := loaded.Devices[entry.DeviceID]; dev != nil {
+ info.DeviceName = deviceDisplayName(dev)
+ info.DeviceIP = dev.IP
+ info.DeviceLastSeen = dev.LastSeenAt
+ deviceInfo := buildAdminDeviceInfo(dev)
+ info.Device = &deviceInfo
+ }
+ }
+ return info
+}
+
+func buildAdminDeviceInfo(dev *ClientDevice) adminDeviceInfo {
+ if dev == nil {
+ return adminDeviceInfo{}
+ }
+ return adminDeviceInfo{
+ DeviceID: dev.DeviceID, IP: dev.IP, Name: deviceDisplayName(dev),
+ Manufacturer: dev.Manufacturer, Brand: dev.Brand, Model: dev.Model,
+ AndroidVersion: dev.AndroidVersion, SDK: dev.SDK, ABI: dev.ABI,
+ AppVersion: dev.AppVersion, Locale: dev.Locale, Country: dev.Country,
+ TimeZone: dev.TimeZone, RemoteIP: dev.RemoteIP, LastSeenAt: dev.LastSeenAt,
+ }
+}
+
+func buildAdminTrafficPeriod(buckets []TrafficBucket, down, up int64) adminTrafficPeriod {
+ period := func(days int) adminTrafficValue {
+ if days <= 0 {
+ return adminTrafficValue{Down: down, Up: up}
+ }
+ total := trafficSince(buckets, days)
+ return adminTrafficValue{Down: total.Down, Up: total.Up}
+ }
+ return adminTrafficPeriod{Today: period(1), Week: period(7), Month: period(30), All: period(0)}
+}
+
+func buildAdminDatabaseTraffic(loaded *Database) adminTrafficPeriod {
+ total := func(days int) adminTrafficValue {
+ var down, up int64
+ if days <= 0 {
+ down, up = loaded.AdminDownBytes, loaded.AdminUpBytes
+ } else {
+ value := trafficSince(loaded.AdminTraffic, days)
+ down, up = value.Down, value.Up
+ }
+ for _, entry := range loaded.Passwords {
+ if entry == nil {
+ continue
+ }
+ if days <= 0 {
+ down += entry.DownBytes
+ up += entry.UpBytes
+ } else {
+ value := trafficSince(entry.Traffic, days)
+ down += value.Down
+ up += value.Up
+ }
+ }
+ return adminTrafficValue{Down: down, Up: up}
+ }
+ return adminTrafficPeriod{Today: total(1), Week: total(7), Month: total(30), All: total(0)}
+}
+
+func adminCreatePassword(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("create", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ days := fs.Int("days", 30, "срок действия в днях, 0 = бессрочно")
+ label := fs.String("label", "", "название клиента")
+ vkHash := fs.String("vk-hash", "", "VK-хеш или ссылка")
+ ports := fs.String("ports", "", "DTLS,WG,TUN")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ if *days < 0 || *days > 365 {
+ return adminResponse{}, errors.New("days должен быть 0..365")
+ }
+ cleanupExpiredPasswordsAdmin(loaded)
+ if len(loaded.Passwords) >= loaded.MaxPasswords {
+ return adminResponse{}, fmt.Errorf("лимит клиентов: максимум %d", loaded.MaxPasswords)
+ }
+ normalizedPorts := loaded.DefaultPorts
+ if strings.TrimSpace(*ports) != "" {
+ value, err := parsePortsSpec(*ports)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ normalizedPorts = value
+ }
+ normalizedHash := ""
+ if strings.TrimSpace(*vkHash) != "" {
+ value, err := normalizeVKHashesInput(*vkHash)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ normalizedHash = value
+ }
+ password := ""
+ for i := 0; i < 64; i++ {
+ candidate := generatePassword()
+ if _, exists := loaded.Passwords[candidate]; !exists {
+ password = candidate
+ break
+ }
+ }
+ if password == "" {
+ return adminResponse{}, errors.New("не удалось создать уникальный пароль")
+ }
+ entry := &PasswordEntry{
+ Label: normalizePasswordLabel(*label),
+ VkHash: normalizedHash,
+ Ports: normalizedPorts,
+ }
+ if *days > 0 {
+ entry.ExpiresAt = time.Now().Add(time.Duration(*days) * 24 * time.Hour).Unix()
+ }
+ loaded.Passwords[password] = entry
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{
+ OK: true,
+ Message: "Клиент создан",
+ RestartRequired: true,
+ Server: buildAdminServerInfo(configDir, loaded),
+ Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, password, entry)),
+ }, nil
+}
+
+func adminDeletePassword(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ password, err := adminPasswordArg("delete", args)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ entry, exists := loaded.Passwords[password]
+ if !exists || entry == nil {
+ return adminResponse{}, errors.New("пароль не найден")
+ }
+ unbindPasswordDeviceAdmin(loaded, entry)
+ delete(loaded.Passwords, password)
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{
+ OK: true,
+ Message: "Клиент удалён",
+ RestartRequired: true,
+ Server: buildAdminServerInfo(configDir, loaded),
+ }, nil
+}
+
+func adminUnbindPassword(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ password, err := adminPasswordArg("unbind", args)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ entry, exists := loaded.Passwords[password]
+ if !exists || entry == nil {
+ return adminResponse{}, errors.New("пароль не найден")
+ }
+ unbindPasswordDeviceAdmin(loaded, entry)
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{
+ OK: true,
+ Message: "Устройство отвязано",
+ RestartRequired: true,
+ Server: buildAdminServerInfo(configDir, loaded),
+ Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, password, entry)),
+ }, nil
+}
+
+func adminSetPasswordActivation(configDir string, loaded *Database, args []string, deactivated bool) (adminResponse, error) {
+ command := "activate"
+ if deactivated {
+ command = "deactivate"
+ }
+ password, err := adminPasswordArg(command, args)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ entry, exists := loaded.Passwords[password]
+ if !exists || entry == nil {
+ return adminResponse{}, errors.New("пароль не найден")
+ }
+ if !deactivated && isPasswordExpired(entry) {
+ return adminResponse{}, errors.New("срок действия клиента истёк")
+ }
+ entry.IsDeactivated = deactivated
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ message := "Клиент активирован"
+ if deactivated {
+ message = "Клиент отключён"
+ }
+ return adminResponse{
+ OK: true,
+ Message: message,
+ RestartRequired: true,
+ Server: buildAdminServerInfo(configDir, loaded),
+ Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, password, entry)),
+ }, nil
+}
+
+func adminSetPasswordLabel(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("set-label", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ password := fs.String("password", "", "пароль клиента")
+ label := fs.String("label", "", "новое название")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ entry, err := requireAdminPassword(loaded, *password)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ entry.Label = normalizePasswordLabel(*label)
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{
+ OK: true,
+ Message: "Название обновлено",
+ Server: buildAdminServerInfo(configDir, loaded),
+ Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, *password, entry)),
+ }, nil
+}
+
+func adminSetPasswordHash(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("set-hash", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ password := fs.String("password", "", "пароль клиента")
+ hash := fs.String("vk-hash", "", "новый VK-хеш или ссылка")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ entry, err := requireAdminPassword(loaded, *password)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ normalized := ""
+ if strings.TrimSpace(*hash) != "" {
+ normalized, err = normalizeVKHashesInput(*hash)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ }
+ entry.VkHash = normalized
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{
+ OK: true,
+ Message: "VK-хеш обновлён",
+ Server: buildAdminServerInfo(configDir, loaded),
+ Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, *password, entry)),
+ }, nil
+}
+
+func adminSetPasswordExpiry(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("set-expiry", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ password := fs.String("password", "", "пароль клиента")
+ days := fs.Int("days", 30, "новый срок от текущего момента, 0 = бессрочно")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ if *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()
+ }
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{
+ OK: true,
+ Message: "Срок обновлён",
+ Server: buildAdminServerInfo(configDir, loaded),
+ Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, *password, entry)),
+ }, nil
+}
+
+func adminSetPasswordPorts(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("set-ports", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ password := fs.String("password", "", "пароль клиента")
+ ports := fs.String("ports", "", "DTLS,WG,TUN")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ entry, err := requireAdminPassword(loaded, *password)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ normalized, err := parsePortsSpec(*ports)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ entry.Ports = normalized
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{OK: true, Message: "Порты ссылки обновлены", Server: buildAdminServerInfo(configDir, loaded), Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, *password, entry))}, nil
+}
+
+func adminUpdateClient(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("update-client", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ password := fs.String("password", "", "пароль клиента")
+ label := fs.String("label", "", "название")
+ hash := fs.String("vk-hash", "", "VK-хеш или ссылка")
+ ports := fs.String("ports", "", "DTLS,WG,TUN")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ entry, err := requireAdminPassword(loaded, *password)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ normalizedHash := ""
+ if strings.TrimSpace(*hash) != "" {
+ normalizedHash, err = normalizeVKHashesInput(*hash)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ }
+ normalizedPorts, err := parsePortsSpec(*ports)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ entry.Label = normalizePasswordLabel(*label)
+ entry.VkHash = normalizedHash
+ entry.Ports = normalizedPorts
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{OK: true, Message: "Клиент обновлён", Server: buildAdminServerInfo(configDir, loaded), Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, *password, entry))}, nil
+}
+
+func adminSetDNS(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("set-dns", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ value := fs.String("value", "", "DNS через запятую")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ normalized, err := normalizeDNSInput(*value)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ loaded.DNS = normalized
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{OK: true, Message: "DNS обновлён", Server: buildAdminServerInfo(configDir, loaded)}, nil
+}
+
+func adminSetLimit(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("set-limit", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ value := fs.Int("value", 0, "лимит клиентов")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ if *value < 1 || *value > 500 {
+ return adminResponse{}, errors.New("лимит должен быть 1..500")
+ }
+ loaded.MaxPasswords = *value
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{OK: true, Message: "Лимит клиентов обновлён", Server: buildAdminServerInfo(configDir, loaded)}, nil
+}
+
+func adminSetDefaultPorts(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("set-default-ports", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ value := fs.String("value", "", "DTLS,WG,TUN")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ normalized, err := parsePortsSpec(*value)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ loaded.DefaultPorts = normalized
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{OK: true, Message: "Стандартные порты ссылок обновлены", Server: buildAdminServerInfo(configDir, loaded)}, nil
+}
+
+func adminSetPublicIP(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("set-public-ip", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ value := fs.String("value", "", "домен, IP или автоматическое определение (`auto`)")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ normalized, err := normalizePublicAddressInput(*value)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ loaded.PublicIP = normalized
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ message := "Публичный адрес обновлён"
+ if normalized == "" {
+ message = "Включено автоматическое определение публичного IP"
+ }
+ return adminResponse{OK: true, Message: message, Server: buildAdminServerInfo(configDir, loaded)}, nil
+}
+
+func adminUpdateSettings(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("update-settings", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ dns := fs.String("dns", "", "DNS через запятую")
+ limit := fs.Int("limit", 0, "лимит клиентов")
+ ports := fs.String("ports", "", "стандартные порты ссылок")
+ publicHost := fs.String("public-ip", "auto", "домен, IP или автоматическое определение (`auto`)")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+ normalizedDNS, err := normalizeDNSInput(*dns)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ if *limit < 1 || *limit > 500 {
+ return adminResponse{}, errors.New("лимит должен быть 1..500")
+ }
+ normalizedPorts, err := parsePortsSpec(*ports)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ normalizedPublic, err := normalizePublicAddressInput(*publicHost)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ loaded.DNS = normalizedDNS
+ loaded.MaxPasswords = *limit
+ loaded.DefaultPorts = normalizedPorts
+ loaded.PublicIP = normalizedPublic
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{OK: true, Message: "Настройки сервера обновлены", Server: buildAdminServerInfo(configDir, loaded)}, nil
+}
+
+func adminUpdateAdminProfile(configDir string, loaded *Database, args []string) (adminResponse, error) {
+ fs := flag.NewFlagSet("update-admin-profile", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ vkHashes := fs.String("vk-hashes", "", "VK-хеши владельца")
+ secondaryVkHash := fs.String("secondary-vk-hash", "", "резервный VK-хеш владельца")
+ workers := fs.Int("workers", 16, "потоков на хеш")
+ protocol := fs.String("protocol", "udp", "протокол клиента")
+ listenPort := fs.Int("listen-port", 0, "локальный порт клиента")
+ sni := fs.String("sni", "", "SNI клиента")
+ noDNS := fs.Bool("no-dns", false, "отключить DNS-перехват")
+ ports := fs.String("ports", "", "DTLS,WG,TUN")
+ if err := fs.Parse(args); err != nil {
+ return adminResponse{}, err
+ }
+
+ profile := loaded.AdminProfile
+ profile.VkHashes = ""
+ if strings.TrimSpace(*vkHashes) != "" {
+ normalized, err := normalizeVKHashesInput(*vkHashes)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ profile.VkHashes = normalized
+ }
+ profile.SecondaryVkHash = ""
+ if strings.TrimSpace(*secondaryVkHash) != "" {
+ normalized, err := normalizeVKHashesInput(*secondaryVkHash)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ profile.SecondaryVkHash = normalized
+ }
+ if *workers < 1 || *workers > 128 {
+ return adminResponse{}, errors.New("workers должен быть 1..128")
+ }
+ profile.WorkersPerHash = *workers
+ normalizedProtocol, err := normalizeAdminProfileProtocol(*protocol)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ profile.Protocol = normalizedProtocol
+ if strings.TrimSpace(*ports) != "" {
+ normalizedPorts, err := parsePortsSpec(*ports)
+ if err != nil {
+ return adminResponse{}, err
+ }
+ profile.Ports = normalizedPorts
+ } else {
+ profile.Ports = loaded.DefaultPorts
+ }
+ if *listenPort < 0 || *listenPort > 65535 {
+ return adminResponse{}, errors.New("listen-port должен быть 1..65535")
+ }
+ if *listenPort > 0 {
+ profile.ListenPort = *listenPort
+ } else {
+ profile.ListenPort = adminProfileDefaultListenPort(profile.Ports)
+ }
+ profile.SNI = normalizeAdminProfileSNI(*sni)
+ profile.NoDNS = *noDNS
+ profile.UpdatedAt = time.Now().Unix()
+ profile = normalizeAdminProfileForStorage(profile, loaded.DefaultPorts)
+
+ loaded.AdminProfile = profile
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{OK: true, Message: "Профиль владельца обновлён", Server: buildAdminServerInfo(configDir, loaded)}, nil
+}
+
+func adminRefreshPublicIP(configDir string, loaded *Database, live bool) (adminResponse, error) {
+ if !live {
+ return adminResponse{}, errors.New("повторное определение публичного IP доступно только на работающем сервере")
+ }
+ publicIP = ""
+ value := getPublicIP()
+ if value == "YOUR_SERVER_IP" {
+ return adminResponse{}, errors.New("не удалось определить публичный IP")
+ }
+ 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) {
+ removed := 0
+ if live {
+ removed = cleanupExpiredPasswordsLocked(wgDev)
+ } else {
+ removed = cleanupExpiredPasswordsAdmin(loaded)
+ }
+ if removed > 0 {
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ }
+ 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) {
+ used := make(map[string]struct{})
+ for _, entry := range loaded.Passwords {
+ if entry != nil && entry.DeviceID != "" {
+ used[entry.DeviceID] = struct{}{}
+ }
+ }
+ for deviceID := range adminDeviceIDSet(loaded) {
+ used[deviceID] = struct{}{}
+ }
+ removed := 0
+ for deviceID, dev := range loaded.Devices {
+ if _, exists := used[deviceID]; exists {
+ continue
+ }
+ if live {
+ removePeerFromWG(wgDev, dev)
+ }
+ delete(loaded.Devices, deviceID)
+ removed++
+ }
+ if removed > 0 {
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ }
+ return adminResponse{OK: true, Message: fmt.Sprintf("Удалено забытых устройств: %d", removed), Server: buildAdminServerInfo(configDir, loaded)}, nil
+}
+
+func adminResetTraffic(configDir string, loaded *Database) (adminResponse, error) {
+ loaded.AdminDownBytes = 0
+ loaded.AdminUpBytes = 0
+ loaded.AdminTraffic = nil
+ for _, entry := range loaded.Passwords {
+ if entry == nil {
+ continue
+ }
+ entry.DownBytes = 0
+ entry.UpBytes = 0
+ entry.Traffic = nil
+ }
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ return adminResponse{}, err
+ }
+ return adminResponse{OK: true, Message: "Счётчики трафика сброшены", Server: buildAdminServerInfo(configDir, loaded)}, nil
+}
+
+func adminPasswordArg(command string, args []string) (string, error) {
+ fs := flag.NewFlagSet(command, flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ password := fs.String("password", "", "пароль клиента")
+ if err := fs.Parse(args); err != nil {
+ return "", err
+ }
+ value := strings.TrimSpace(*password)
+ if value == "" {
+ return "", errors.New("укажите --password")
+ }
+ return value, nil
+}
+
+func requireAdminPassword(loaded *Database, password string) (*PasswordEntry, error) {
+ password = strings.TrimSpace(password)
+ if password == "" {
+ return nil, errors.New("укажите --password")
+ }
+ entry, exists := loaded.Passwords[password]
+ if !exists || entry == nil {
+ return nil, errors.New("пароль не найден")
+ }
+ return entry, nil
+}
+
+func cleanupExpiredPasswordsAdmin(loaded *Database) int {
+ removed := 0
+ nowUnix := time.Now().Unix()
+ for password, entry := range loaded.Passwords {
+ if isPasswordExpired(entry) {
+ if entry != nil {
+ unbindPasswordDeviceAdminAt(loaded, entry, nowUnix)
+ }
+ delete(loaded.Passwords, password)
+ removed++
+ }
+ }
+ return removed
+}
+
+func unbindPasswordDeviceAdmin(loaded *Database, entry *PasswordEntry) {
+ unbindPasswordDeviceAdminAt(loaded, entry, time.Now().Unix())
+}
+
+func unbindPasswordDeviceAdminAt(loaded *Database, entry *PasswordEntry, ts int64) {
+ if entry == nil || entry.DeviceID == "" {
+ return
+ }
+ oldDeviceID := entry.DeviceID
+ markActiveBindUnbound(entry, oldDeviceID, ts)
+ if _, isAdminDevice := adminDeviceIDSet(loaded)[oldDeviceID]; !isAdminDevice {
+ delete(loaded.Devices, oldDeviceID)
+ }
+ entry.DeviceID = ""
+}
+
+func ptrAdminPasswordInfo(value adminPasswordInfo) *adminPasswordInfo {
+ return &value
+}
+
+func writeAdminJSON(response adminResponse) {
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetEscapeHTML(false)
+ _ = enc.Encode(response)
+}
+
+func writeAdminError(err error) {
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetEscapeHTML(false)
+ _ = enc.Encode(adminResponse{OK: false, Message: err.Error()})
+}
+
+func adminAtoi(value string) (int, error) {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return 0, nil
+ }
+ return strconv.Atoi(value)
+}
diff --git a/admin_test.go b/admin_test.go
new file mode 100644
index 0000000..8b84077
--- /dev/null
+++ b/admin_test.go
@@ -0,0 +1,170 @@
+package main
+
+import (
+ "context"
+ "reflect"
+ "testing"
+)
+
+func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) {
+ configDir := t.TempDir()
+ loaded := &Database{
+ MainPassword: "owner-secret",
+ DefaultPorts: "56000,56001,9000",
+ MaxPasswords: 10,
+ Passwords: make(map[string]*PasswordEntry),
+ Devices: make(map[string]*ClientDevice),
+ }
+ if err := saveAdminDB(configDir, loaded); err != nil {
+ t.Fatal(err)
+ }
+
+ dbMutex.Lock()
+ db = loaded
+ dbFile = configDir + "/passwords.json"
+ serverWrapKeys = newWrapKeyStore()
+ dbMutex.Unlock()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ if err := startAdminSocket(ctx, configDir, nil); err != nil {
+ t.Fatal(err)
+ }
+ denied, err := callAdminSocket(configDir, adminRequest{MainPassword: "wrong", Args: []string{"list"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if denied.OK {
+ t.Fatal("admin socket accepted an invalid main password")
+ }
+
+ request := func(args ...string) adminResponse {
+ t.Helper()
+ response, err := callAdminSocket(configDir, adminRequest{
+ MainPassword: "owner-secret",
+ Args: args,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !response.OK {
+ t.Fatalf("admin request %v failed: %s", args, response.Message)
+ }
+ if response.RestartRequired {
+ t.Fatalf("admin request %v unexpectedly requires restart", args)
+ }
+ return response
+ }
+
+ created := request("create", "--days", "30", "--label", "Тест")
+ if created.Password == nil || created.Password.Password == "" {
+ t.Fatal("create did not return a password")
+ }
+ if created.Password.Label != "Тест" {
+ t.Fatalf("create did not preserve client label: %q", created.Password.Label)
+ }
+ password := created.Password.Password
+ if serverWrapKeys.Count() != 1 {
+ t.Fatalf("expected one live WRAP key, got %d", serverWrapKeys.Count())
+ }
+ updated := request(
+ "update-client", "--password", password,
+ "--label", "Телефон", "--vk-hash", "hash-value", "--ports", "56010,56011,9010",
+ )
+ if updated.Password == nil || updated.Password.Label != "Телефон" || updated.Password.Ports != "56010,56011,9010" {
+ t.Fatal("client fields were not updated")
+ }
+ renamed := request("set-label", "--password", password, "--label", "Папа")
+ if renamed.Password == nil || renamed.Password.Label != "Папа" {
+ t.Fatalf("set-label did not preserve client label: %#v", renamed.Password)
+ }
+ request(
+ "update-settings", "--dns", "1.1.1.1,8.8.8.8", "--limit", "25",
+ "--ports", "56000,56001,9000", "--public-ip", "vpn.example.com",
+ )
+ if db.DNS != "1.1.1.1,8.8.8.8" || db.MaxPasswords != 25 || getServerPublicIPOverride() != "vpn.example.com" {
+ t.Fatal("live server settings were not applied")
+ }
+
+ request(
+ "update-admin-profile",
+ "--vk-hashes", "abcdefghijklmnop,qrstuvwxyzABCDEF",
+ "--secondary-vk-hash", "1234567890abcdef",
+ "--workers", "27",
+ "--protocol", "tcp",
+ "--listen-port", "9010",
+ "--sni", "owner.example.com",
+ "--ports", "56010,56011,9010",
+ "--no-dns",
+ )
+ listedOwner := request("list")
+ if listedOwner.Server == nil {
+ t.Fatal("list did not return server state after owner profile update")
+ }
+ profile := listedOwner.Server.AdminProfile
+ if profile.VkHashes != "abcdefghijklmnop,qrstuvwxyzABCDEF" ||
+ profile.SecondaryVkHash != "1234567890abcdef" ||
+ profile.WorkersPerHash != 27 ||
+ profile.Protocol != "tcp" ||
+ profile.ListenPort != 9010 ||
+ profile.SNI != "owner.example.com" ||
+ !profile.NoDNS ||
+ profile.Ports != "56010,56011,9010" ||
+ profile.UpdatedAt == 0 {
+ t.Fatalf("owner profile was not returned intact: %#v", profile)
+ }
+ persisted, err := readAdminDB(configDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(persisted.AdminProfile, profile) {
+ t.Fatalf("owner profile on disk differs from live state: disk=%#v live=%#v", persisted.AdminProfile, profile)
+ }
+
+ dbMutex.Lock()
+ db.Devices["phone"] = &ClientDevice{DeviceID: "phone", IP: "10.66.66.2"}
+ db.Devices["orphan"] = &ClientDevice{DeviceID: "orphan", IP: "10.66.66.3"}
+ db.Passwords[password].DeviceID = "phone"
+ db.Passwords[password].DownBytes = 1024
+ db.Passwords[password].UpBytes = 2048
+ if err := saveAdminDB(configDir, db); err != nil {
+ dbMutex.Unlock()
+ t.Fatal(err)
+ }
+ dbMutex.Unlock()
+ listed := request("list")
+ if listed.Server == nil || listed.Server.OrphanDeviceCount != 1 || len(listed.Server.OrphanDevices) != 1 || listed.Server.OrphanDevices[0].DeviceID != "orphan" {
+ t.Fatal("orphan device preview is incomplete")
+ }
+ request("cleanup-orphans")
+ dbMutex.Lock()
+ if db.Devices["orphan"] != nil {
+ dbMutex.Unlock()
+ t.Fatal("orphan device was not removed")
+ }
+ dbMutex.Unlock()
+ request("reset-traffic")
+ if db.Passwords[password].DownBytes != 0 || db.Passwords[password].UpBytes != 0 {
+ t.Fatal("traffic counters were not reset")
+ }
+
+ request("deactivate", "--password", password)
+ dbMutex.Lock()
+ if db.Passwords[password].DeviceID != "phone" || db.Devices["phone"] == nil {
+ dbMutex.Unlock()
+ t.Fatal("deactivation must preserve the device binding")
+ }
+ dbMutex.Unlock()
+ if serverWrapKeys.Count() != 0 {
+ t.Fatalf("expected deactivation to remove live WRAP key, got %d", serverWrapKeys.Count())
+ }
+
+ request("activate", "--password", password)
+ if serverWrapKeys.Count() != 1 {
+ t.Fatalf("expected activation to restore live WRAP key, got %d", serverWrapKeys.Count())
+ }
+ request("delete", "--password", password)
+ if serverWrapKeys.Count() != 0 {
+ t.Fatalf("expected deletion to remove live WRAP key, got %d", serverWrapKeys.Count())
+ }
+}
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 884313e..622032a 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -5,7 +5,7 @@ plugins {
id("org.jetbrains.kotlin.plugin.compose")
}
-val appVersionName = "1"
+val appVersionName = "2"
val releaseApkBaseName = "WDTT-Plus"
val localProperties = Properties()
@@ -22,9 +22,9 @@ android {
applicationId = "com.wdtt.plus"
minSdk = 28
targetSdk = 35
- versionCode = 1
+ versionCode = 2
versionName = appVersionName
- buildConfigField("String", "MOD_RELEASE_DATE", "\"01.07.2026\"")
+ buildConfigField("String", "MOD_RELEASE_DATE", "\"03.07.2026\"")
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
@@ -283,8 +283,12 @@ dependencies {
implementation("androidx.activity:activity-compose:1.9.3")
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")
implementation("androidx.datastore:datastore-preferences:1.1.1")
implementation("com.wireguard.android:tunnel:1.0.20230706")
implementation("com.github.mwiede:jsch:0.2.16")
+ implementation("com.journeyapps:zxing-android-embedded:4.3.0")
+ implementation("com.google.zxing:core:3.5.4")
testImplementation("junit:junit:4.13.2")
+ testImplementation("org.json:json:20260522")
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 451836c..9b0c2d2 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -11,6 +11,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/dev/null || true
- cleanup_config_dir_keep_access_db
+ if [ "$WDTT_PRESERVE_DATA" = "1" ]; then
+ [ -f "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" ] && chmod 600 "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" 2>/dev/null || true
+ [ -f "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] && chmod 600 "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" 2>/dev/null || true
+ echo "✓ Режим обновления: конфигурация и данные сохранены"
+ else
+ rm -f /usr/local/bin/wdtt-server 2>/dev/null || true
+ cleanup_config_dir_keep_access_db
+ fi
echo "✓ Очистка завершена (база доступа сохранена)"
}
@@ -424,7 +431,10 @@ setup_wdtt_binary() {
if [ -f /tmp/wdtt-server ]; then
chmod +x /tmp/wdtt-server
- install -m 0755 /tmp/wdtt-server /usr/local/bin/wdtt-server 2>/dev/null || mv /tmp/wdtt-server /usr/local/bin/wdtt-server
+ rm -f /usr/local/bin/.wdtt-server.new
+ install -m 0755 /tmp/wdtt-server /usr/local/bin/.wdtt-server.new || die "Не удалось подготовить новый wdtt-server"
+ mv -f /usr/local/bin/.wdtt-server.new /usr/local/bin/wdtt-server || die "Не удалось атомарно заменить wdtt-server"
+ rm -f /tmp/wdtt-server
echo "✓ wdtt-server установлен"
elif [ -f /usr/local/bin/wdtt-server ]; then
echo "✓ wdtt-server уже установлен"
diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt
index b428883..8f868fc 100644
--- a/app/src/main/java/com/wdtt/plus/MainActivity.kt
+++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt
@@ -59,13 +59,17 @@ import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.input.pointer.PointerEventPass
+import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.dp
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
+import androidx.compose.ui.window.DialogProperties
import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
@@ -77,6 +81,8 @@ import com.wdtt.plus.ui.SettingsTab
import com.wdtt.plus.ui.DeployTab
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.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.first
@@ -91,6 +97,7 @@ class MainActivity : ComponentActivity() {
private var sharedVkHashError by mutableStateOf(null)
private var wdttDeepLinkMessage by mutableStateOf(null)
private var pendingWdttDeepLinkPlan by mutableStateOf(null)
+ private var pendingAdminTransfer by mutableStateOf(null)
companion object {
var activeActivities = 0
@@ -138,6 +145,16 @@ class MainActivity : ComponentActivity() {
wdttDeepLinkMessage = wdttDeepLinkMessage,
onWdttDeepLinkMessageShown = { wdttDeepLinkMessage = null },
pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan,
+ pendingAdminTransfer = pendingAdminTransfer,
+ onIncomingTransferContent = ::handleIncomingTransferText,
+ onAdminTransferDismissed = { pendingAdminTransfer = null },
+ onAdminTransferFinished = { message ->
+ pendingAdminTransfer = null
+ wdttDeepLinkMessage = message
+ },
+ onSelectWdttDeepLinkOverwriteProfile = { profile ->
+ pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan?.copy(targetProfile = profile)
+ },
onConfirmWdttDeepLinkOverwrite = { plan ->
pendingWdttDeepLinkPlan = null
applyWdttDeepLinkPlan(plan)
@@ -171,21 +188,82 @@ class MainActivity : ComponentActivity() {
)
}
}
- handleIncomingShareIntent(intent)
- handleIncomingWdttDeepLink(intent)
+ handleIncomingIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
- handleIncomingShareIntent(intent)
- handleIncomingWdttDeepLink(intent)
+ handleIncomingIntent(intent)
}
- private fun handleIncomingWdttDeepLink(intent: Intent?) {
- if (intent?.action != Intent.ACTION_VIEW) return
- val link = intent.dataString?.trim().orEmpty()
- if (!link.startsWith("wdtt://", ignoreCase = true)) return
+ private fun handleIncomingIntent(intent: Intent?) {
+ when (intent?.action) {
+ Intent.ACTION_VIEW -> {
+ val data = intent.data ?: return
+ if (data.scheme.equals("wdtt", ignoreCase = true)) {
+ handleIncomingTransferText(data.toString())
+ } else {
+ handleIncomingUri(data, intent.type)
+ }
+ }
+ Intent.ACTION_SEND -> {
+ 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/octet-stream"
+ } == true
+ if (streamFirst && streamUri != null) {
+ handleIncomingUri(streamUri, intent.type)
+ 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)
+ }
+ }
+ }
+
+ private fun handleIncomingUri(uri: Uri, mimeType: String?) {
+ lifecycleScope.launch {
+ runCatching {
+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ if (mimeType?.startsWith("image/") == true) {
+ TransferFiles.decodeQrImage(this@MainActivity, uri)
+ } else {
+ TransferFiles.readText(this@MainActivity, uri)
+ }
+ }
+ }.onSuccess(::handleIncomingTransferText)
+ .onFailure { wdttDeepLinkMessage = it.message ?: "Не удалось прочитать переданные данные." }
+ }
+ }
+
+ private fun handleIncomingTransferText(value: String) {
+ val link = WdttTransferCodec.extractWdttLink(value)
+ when {
+ link != null -> handleIncomingWdttLink(link)
+ WdttTransferCodec.isAdminTransfer(value) -> pendingAdminTransfer = value.trim()
+ WdttTransferCodec.documentFormat(value) == "wdtt-server-backup" -> {
+ wdttDeepLinkMessage = "Распознана резервная копия сервера. Она применяется к выбранному серверу во вкладке «Деплой» → «Перенос сервера» → «Импорт»."
+ }
+ WdttTransferCodec.documentFormat(value) == "wdtt-plus-admin-settings" -> {
+ wdttDeepLinkMessage = "Распознаны незашифрованные настройки администратора. В целях безопасности импортируется только защищённый файл, созданный через раздел «Передача»."
+ }
+ else -> handleIncomingVkShare(value)
+ }
+ }
+
+ private fun handleIncomingWdttLink(link: String) {
lifecycleScope.launch {
val store = SettingsStore(this@MainActivity)
runCatching {
@@ -224,11 +302,14 @@ class MainActivity : ComponentActivity() {
}
}
- private fun handleIncomingShareIntent(intent: Intent?) {
- if (intent?.action != Intent.ACTION_SEND) return
- val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT)
- ?: intent.clipData?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(this)?.toString()
- ?: return
+ private fun handleIncomingVkShare(sharedText: String) {
+ val trimmed = sharedText.trim().trim('<', '>', '"', '\'')
+ val looksLikeJoinLink = trimmed.contains("/call/join/", ignoreCase = true)
+ val looksLikeRawHash = Regex("^[A-Za-z0-9_-]{16,512}$").matches(trimmed)
+ if (!looksLikeJoinLink && !looksLikeRawHash) {
+ sharedVkHashError = "Данные не распознаны. Поддерживаются ссылка подключения wdtt://, файл или QR WDTT Plus и ссылка VK-звонка."
+ return
+ }
val hash = VkJoinLink.extractHash(sharedText)
if (hash.length < 16) {
sharedVkHashError = "В переданной ссылке не найден VK-хеш звонка."
@@ -533,6 +614,11 @@ fun MainScreen(
wdttDeepLinkMessage: String? = null,
onWdttDeepLinkMessageShown: () -> Unit = {},
pendingWdttDeepLinkPlan: WdttDeepLinkApplyPlan? = null,
+ pendingAdminTransfer: String? = null,
+ onIncomingTransferContent: (String) -> Unit = {},
+ onAdminTransferDismissed: () -> Unit = {},
+ onAdminTransferFinished: (String) -> Unit = {},
+ onSelectWdttDeepLinkOverwriteProfile: (Int) -> Unit = {},
onConfirmWdttDeepLinkOverwrite: (WdttDeepLinkApplyPlan) -> Unit = {},
onCancelWdttDeepLinkOverwrite: () -> Unit = {},
themeMode: String = "system",
@@ -551,13 +637,29 @@ fun MainScreen(
val view = LocalView.current
val context = LocalContext.current
val density = LocalDensity.current
+ val focusManager = LocalFocusManager.current
val scope = rememberCoroutineScope()
val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0)
val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false)
val interfaceRole by settingsStore.interfaceRole.collectAsStateWithLifecycle(initialValue = "")
val permissionOnboardingComplete by settingsStore.permissionOnboardingComplete.collectAsStateWithLifecycle(initialValue = false)
+ val migrationNoticeV2Shown by settingsStore.migrationNoticeV2Shown.collectAsStateWithLifecycle(initialValue = true)
val isAdminInterface = interfaceRole == "admin"
+ val isUpdatedInstall = remember(context) {
+ runCatching {
+ context.packageManager.getPackageInfo(context.packageName, 0).let { info ->
+ info.lastUpdateTime > info.firstInstallTime
+ }
+ }.getOrDefault(false)
+ }
var selectedTab by rememberSaveable { mutableIntStateOf(0) }
+ val tunnelScrollPosition = rememberSaveable { mutableIntStateOf(0) }
+ val deployScrollPosition = rememberSaveable { mutableIntStateOf(0) }
+ val exceptionsFirstVisibleItemIndex = rememberSaveable { mutableIntStateOf(0) }
+ val exceptionsFirstVisibleItemScrollOffset = rememberSaveable { mutableIntStateOf(0) }
+ val logsFirstVisibleItemIndex = rememberSaveable { mutableIntStateOf(0) }
+ val logsFirstVisibleItemScrollOffset = rememberSaveable { mutableIntStateOf(0) }
+ val infoScrollPosition = rememberSaveable { mutableIntStateOf(0) }
var dragTargetIndex by remember { mutableIntStateOf(-1) }
var dragProgress by remember { mutableFloatStateOf(0f) }
val updateCheckIntervalHours by settingsStore.updateCheckIntervalHours.collectAsStateWithLifecycle(
@@ -567,6 +669,7 @@ fun MainScreen(
val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" }
val safeBottomInset = with(density) { WindowInsets.safeDrawing.getBottom(density).toDp() }
val navOverlayReserve = safeBottomInset + 96.dp
+ var showTransferCenter by rememberSaveable { mutableStateOf(false) }
if (interfaceRole.isBlank()) {
RoleSelectionScreen(
@@ -688,6 +791,16 @@ fun MainScreen(
.fillMaxSize()
.padding(padding)
.consumeWindowInsets(padding)
+ .pointerInput(focusManager) {
+ awaitPointerEventScope {
+ while (true) {
+ val event = awaitPointerEvent(PointerEventPass.Initial)
+ if (event.type == PointerEventType.Press) {
+ focusManager.clearFocus()
+ }
+ }
+ }
+ }
.pointerInput(selectedTab, wdttLinkMode) {
var totalDrag = 0f
detectHorizontalDragGestures(
@@ -709,6 +822,7 @@ fun MainScreen(
dragProgress = 0f
}
) { change, dragAmount ->
+ if (change.isConsumed) return@detectHorizontalDragGestures
change.consume()
totalDrag += dragAmount
if (abs(totalDrag) < 12f) {
@@ -741,11 +855,21 @@ fun MainScreen(
label = "tab_content"
) { tab ->
when (tab) {
- 0 -> SettingsTab()
- 1 -> if (!wdttLinkMode) DeployTab() else Spacer(modifier = Modifier.fillMaxSize())
- 2 -> ExceptionsTab()
- 3 -> LogsTab()
- 4 -> InfoTab(actionsExpandedState = actionsExpanded, projectExpandedState = projectExpanded)
+ 0 -> SettingsTab(scrollPosition = tunnelScrollPosition)
+ 1 -> if (!wdttLinkMode) DeployTab(scrollPosition = deployScrollPosition) else Spacer(modifier = Modifier.fillMaxSize())
+ 2 -> ExceptionsTab(
+ firstVisibleItemIndex = exceptionsFirstVisibleItemIndex,
+ firstVisibleItemScrollOffset = exceptionsFirstVisibleItemScrollOffset
+ )
+ 3 -> LogsTab(
+ firstVisibleItemIndex = logsFirstVisibleItemIndex,
+ firstVisibleItemScrollOffset = logsFirstVisibleItemScrollOffset
+ )
+ 4 -> InfoTab(
+ actionsExpandedState = actionsExpanded,
+ projectExpandedState = projectExpanded,
+ scrollPosition = infoScrollPosition
+ )
}
}
@@ -789,7 +913,62 @@ fun MainScreen(
activeFingerprint = activeFingerprint,
onFingerprintChange = onFingerprintChange,
activeClientIds = activeClientIds,
- onClientIdsChange = onClientIdsChange
+ onClientIdsChange = onClientIdsChange,
+ onTransferRequested = { showTransferCenter = true }
+ )
+ }
+
+ if (
+ BuildConfig.VERSION_CODE == 2 &&
+ isAdminInterface &&
+ isUpdatedInstall &&
+ !migrationNoticeV2Shown
+ ) {
+ AlertDialog(
+ onDismissRequest = {},
+ properties = DialogProperties(
+ dismissOnBackPress = false,
+ dismissOnClickOutside = false
+ ),
+ title = { Text("Требуется обновление сервера") },
+ text = {
+ Text(
+ "Это крупное обновление WDTT Plus. Для корректной работы новых функций необходимо выполнить установку сервера во вкладке «Деплой».\n\n" +
+ "Выберите установку с сохранением данных. Настройки, клиенты и выданные доступы сохранятся — будет обновлена только серверная часть.\n\n" +
+ "Установку с нуля выполнять не нужно."
+ )
+ },
+ confirmButton = {
+ Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ Button(
+ onClick = { scope.launch { settingsStore.saveMigrationNoticeV2Shown() } }
+ ) {
+ Text("Хорошо")
+ }
+ }
+ }
+ )
+ }
+
+ if (showTransferCenter) {
+ TransferCenterDialog(
+ settingsStore = settingsStore,
+ activeProfile = activeProfile,
+ isAdmin = isAdminInterface,
+ onIncomingContent = {
+ showTransferCenter = false
+ onIncomingTransferContent(it)
+ },
+ onDismiss = { showTransferCenter = false }
+ )
+ }
+
+ pendingAdminTransfer?.let { document ->
+ AdminImportDialog(
+ settingsStore = settingsStore,
+ encryptedDocument = document,
+ onFinished = onAdminTransferFinished,
+ onDismiss = onAdminTransferDismissed
)
}
@@ -836,7 +1015,7 @@ fun MainScreen(
sharedVkHashError?.let { error ->
AlertDialog(
onDismissRequest = onSharedVkHashMessageShown,
- title = { Text("VK-хеш не добавлен") },
+ title = { Text("Данные не импортированы") },
text = { Text(error) },
confirmButton = {
TextButton(onClick = onSharedVkHashMessageShown) {
@@ -849,7 +1028,7 @@ fun MainScreen(
wdttDeepLinkMessage?.let { message ->
AlertDialog(
onDismissRequest = onWdttDeepLinkMessageShown,
- title = { Text("Ссылка WDTT") },
+ title = { Text("Передача WDTT") },
text = { Text(message) },
confirmButton = {
TextButton(onClick = onWdttDeepLinkMessageShown) {
@@ -865,9 +1044,19 @@ fun MainScreen(
onDismissRequest = onCancelWdttDeepLinkOverwrite,
title = { Text("Профили VPN заполнены") },
text = {
- Text(
- "Свободных профилей VPN нет. Ссылка перезапишет профиль $profileLabel. Выполнить действие?"
- )
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text("Свободных профилей VPN нет. Выберите профиль, который можно перезаписать:")
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ repeat(3) { profile ->
+ FilterChip(
+ selected = plan.targetProfile == profile,
+ onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) },
+ label = { Text("VPN ${profile + 1}") }
+ )
+ }
+ }
+ Text("Будет полностью заменено подключение в профиле $profileLabel.")
+ }
},
confirmButton = {
TextButton(onClick = { onConfirmWdttDeepLinkOverwrite(plan) }) {
diff --git a/app/src/main/java/com/wdtt/plus/QrCaptureActivity.kt b/app/src/main/java/com/wdtt/plus/QrCaptureActivity.kt
new file mode 100644
index 0000000..70323bf
--- /dev/null
+++ b/app/src/main/java/com/wdtt/plus/QrCaptureActivity.kt
@@ -0,0 +1,33 @@
+package com.wdtt.plus
+
+import android.os.Bundle
+import android.view.View
+import com.journeyapps.barcodescanner.CaptureActivity
+import androidx.core.view.ViewCompat
+import androidx.core.view.WindowInsetsCompat
+import com.google.zxing.client.android.R as ZxingR
+
+class QrCaptureActivity : CaptureActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val statusView = findViewById(ZxingR.id.zxing_status_view) ?: return
+ val originalLeft = statusView.paddingLeft
+ val originalTop = statusView.paddingTop
+ val originalRight = statusView.paddingRight
+ val originalBottom = statusView.paddingBottom
+ val extraBottom = (24 * resources.displayMetrics.density).toInt()
+ ViewCompat.setOnApplyWindowInsetsListener(statusView) { view, insets ->
+ val systemBottom = insets.getInsets(
+ WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()
+ ).bottom
+ view.setPadding(
+ originalLeft,
+ originalTop,
+ originalRight,
+ originalBottom + systemBottom + extraBottom
+ )
+ insets
+ }
+ ViewCompat.requestApplyInsets(statusView)
+ }
+}
diff --git a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt
new file mode 100644
index 0000000..4b63837
--- /dev/null
+++ b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt
@@ -0,0 +1,614 @@
+package com.wdtt.plus
+
+import com.jcraft.jsch.ChannelExec
+import com.jcraft.jsch.JSch
+import com.jcraft.jsch.Session
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import org.json.JSONObject
+import java.util.Properties
+
+data class ServerAdminTarget(
+ val host: String,
+ val user: String,
+ val sshPassword: String,
+ val sshPort: Int,
+ val mainPassword: String
+)
+
+data class ServerAdminProfileInfo(
+ val vkHashes: String = "",
+ val secondaryVkHash: String = "",
+ val workersPerHash: Int = 16,
+ val protocol: String = "udp",
+ val listenPort: Int = 9000,
+ val sni: String = "",
+ val noDns: Boolean = false,
+ val ports: String = "56000,56001,9000",
+ val deviceIds: List = emptyList(),
+ val updatedAt: Long = 0
+) {
+ val hasSavedFields: Boolean
+ get() = updatedAt > 0L || vkHashes.isNotBlank() || secondaryVkHash.isNotBlank()
+}
+
+data class ServerAdminState(
+ val publicHost: String,
+ val effectivePublicHost: String,
+ val dns: String,
+ val defaultPorts: String,
+ val maxPasswords: Int,
+ val passwordCount: Int,
+ val deviceCount: Int,
+ val expiredCount: Int,
+ val orphanDeviceCount: Int,
+ val orphanDevices: List,
+ val traffic: ServerTrafficPeriod,
+ val adminTraffic: ServerTrafficPeriod,
+ val adminProfile: ServerAdminProfileInfo,
+ val clients: List
+) {
+ val linkHost: String
+ get() = publicHost.ifBlank { "" }
+}
+
+data class ServerTrafficValue(val down: Long = 0, val up: Long = 0)
+
+data class ServerTrafficPeriod(
+ val today: ServerTrafficValue = ServerTrafficValue(),
+ val week: ServerTrafficValue = ServerTrafficValue(),
+ val month: ServerTrafficValue = ServerTrafficValue(),
+ val all: ServerTrafficValue = ServerTrafficValue()
+)
+
+data class ServerDeviceInfo(
+ val deviceId: String,
+ val ip: String,
+ val name: String,
+ val manufacturer: String,
+ val brand: String,
+ val model: String,
+ val androidVersion: String,
+ val sdk: Int,
+ val abi: String,
+ val appVersion: String,
+ val locale: String,
+ val country: String,
+ val timeZone: String,
+ val remoteIp: String,
+ val lastSeenAt: Long
+)
+
+data class ServerBindEvent(
+ val deviceId: String,
+ val deviceName: String,
+ val deviceIp: String,
+ val remoteIp: String,
+ val country: String,
+ val boundAt: Long,
+ val unboundAt: Long,
+ val eventAt: Long,
+ val status: String,
+ val note: String
+)
+
+data class ServerClientInfo(
+ val password: String,
+ val label: String,
+ val vkHash: String,
+ val ports: String,
+ val status: String,
+ val expiresAt: Long,
+ val downBytes: Long,
+ val upBytes: Long,
+ val deviceId: String,
+ val deviceName: String,
+ val deviceIp: String,
+ val deviceLastSeen: Long,
+ val bindEventsCount: Int,
+ val traffic: ServerTrafficPeriod,
+ val device: ServerDeviceInfo?,
+ val bindHistory: List
+) {
+ val title: String
+ get() = label.ifBlank { "Без имени" }
+
+ val isActive: Boolean
+ get() = status == "active"
+
+ val isBound: Boolean
+ get() = deviceId.isNotBlank()
+}
+
+data class ServerClientCreateRequest(
+ val days: Int,
+ val label: String,
+ val vkHash: String,
+ val ports: String
+)
+
+data class ServerAdminActionResult(
+ val message: String,
+ val restartRequired: Boolean,
+ val restarted: Boolean,
+ val createdClient: ServerClientInfo?
+)
+
+object ServerAdminClient {
+ private const val ADMIN_TIMEOUT = 45_000L
+ private const val RESTART_TIMEOUT = 70_000L
+
+ suspend fun list(target: ServerAdminTarget): ServerAdminState = withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ parseState(callAdmin(ssh, target, listOf("list")))
+ }
+ }
+
+ suspend fun details(target: ServerAdminTarget, password: String): ServerClientInfo = withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ val json = callAdmin(ssh, target, listOf("details", "--password", password))
+ json.optJSONObject("password")?.let(::parseClient)
+ ?: throw IllegalStateException("сервер не вернул данные клиента")
+ }
+ }
+
+ suspend fun create(target: ServerAdminTarget, request: ServerClientCreateRequest): ServerAdminActionResult =
+ withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ val args = mutableListOf(
+ "create",
+ "--days", request.days.coerceIn(0, 365).toString()
+ )
+ if (request.label.isNotBlank()) args += listOf("--label", request.label.trim())
+ if (request.vkHash.isNotBlank()) args += listOf("--vk-hash", request.vkHash.trim())
+ if (request.ports.isNotBlank()) args += listOf("--ports", request.ports.trim())
+ actionFromResponse(callAdmin(ssh, target, args))
+ }
+ }
+
+ suspend fun delete(target: ServerAdminTarget, password: String): ServerAdminActionResult =
+ runPasswordAction(target, "delete", password)
+
+ suspend fun unbind(target: ServerAdminTarget, password: String): ServerAdminActionResult =
+ runPasswordAction(target, "unbind", password)
+
+ suspend fun deactivate(target: ServerAdminTarget, password: String): ServerAdminActionResult =
+ runPasswordAction(target, "deactivate", password)
+
+ suspend fun activate(target: ServerAdminTarget, password: String): ServerAdminActionResult =
+ runPasswordAction(target, "activate", password)
+
+ suspend fun setExpiry(target: ServerAdminTarget, password: String, days: Int): ServerAdminActionResult =
+ withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ actionFromResponse(
+ callAdmin(ssh, target, listOf("set-expiry", "--password", password, "--days", days.coerceIn(0, 365).toString()))
+ )
+ }
+ }
+
+ suspend fun setLabel(target: ServerAdminTarget, password: String, label: String): ServerAdminActionResult =
+ withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ actionFromResponse(
+ callAdmin(ssh, target, listOf("set-label", "--password", password, "--label", label))
+ )
+ }
+ }
+
+ suspend fun setHash(target: ServerAdminTarget, password: String, hash: String): ServerAdminActionResult =
+ withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ actionFromResponse(
+ callAdmin(ssh, target, listOf("set-hash", "--password", password, "--vk-hash", hash))
+ )
+ }
+ }
+
+ suspend fun setPorts(target: ServerAdminTarget, password: String, ports: String): ServerAdminActionResult =
+ runArgsAction(target, listOf("set-ports", "--password", password, "--ports", ports))
+
+ suspend fun updateClient(target: ServerAdminTarget, password: String, label: String, hash: String, ports: String): ServerAdminActionResult =
+ withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ val requestedLabel = label.trim()
+ val updated = actionFromResponse(callAdmin(ssh, target, listOf(
+ "update-client", "--password", password,
+ "--label", requestedLabel, "--vk-hash", hash, "--ports", ports
+ )))
+ val relabeled = actionFromResponse(
+ callAdmin(ssh, target, listOf("set-label", "--password", password, "--label", requestedLabel))
+ )
+ val savedClient = relabeled.createdClient ?: updated.createdClient
+ if (requestedLabel.isNotBlank() && savedClient?.label.isNullOrBlank()) {
+ throw IllegalStateException("Название не сохранилось на сервере. Попробуйте обновить сервер WDTT Plus и повторить.")
+ }
+ relabeled.copy(
+ message = updated.message,
+ restartRequired = updated.restartRequired || relabeled.restartRequired,
+ restarted = updated.restarted || relabeled.restarted,
+ createdClient = savedClient
+ )
+ }
+ }
+
+ suspend fun setDns(target: ServerAdminTarget, value: String): ServerAdminActionResult =
+ runArgsAction(target, listOf("set-dns", "--value", value))
+
+ suspend fun setLimit(target: ServerAdminTarget, value: Int): ServerAdminActionResult =
+ runArgsAction(target, listOf("set-limit", "--value", value.coerceIn(1, 500).toString()))
+
+ suspend fun setDefaultPorts(target: ServerAdminTarget, value: String): ServerAdminActionResult =
+ runArgsAction(target, listOf("set-default-ports", "--value", value))
+
+ suspend fun setPublicHost(target: ServerAdminTarget, value: String): ServerAdminActionResult =
+ runArgsAction(target, listOf("set-public-ip", "--value", value.ifBlank { "auto" }))
+
+ suspend fun updateSettings(
+ target: ServerAdminTarget,
+ dns: String,
+ limit: Int,
+ defaultPorts: String,
+ publicHost: String
+ ): ServerAdminActionResult = runArgsAction(target, listOf(
+ "update-settings", "--dns", dns,
+ "--limit", limit.coerceIn(1, 500).toString(),
+ "--ports", defaultPorts,
+ "--public-ip", publicHost.ifBlank { "auto" }
+ ))
+
+ suspend fun updateAdminProfile(target: ServerAdminTarget, profile: ServerAdminProfileInfo): ServerAdminActionResult {
+ val args = mutableListOf(
+ "update-admin-profile",
+ "--vk-hashes", profile.vkHashes.trim(),
+ "--secondary-vk-hash", profile.secondaryVkHash.trim(),
+ "--workers", profile.workersPerHash.coerceIn(1, 128).toString(),
+ "--protocol", profile.protocol.trim().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
+ "--listen-port", profile.listenPort.coerceIn(1, 65535).toString(),
+ "--sni", profile.sni.trim(),
+ "--ports", profile.ports.trim().ifBlank { "56000,56001,9000" }
+ )
+ if (profile.noDns) args += "--no-dns"
+ return runArgsAction(target, args)
+ }
+
+ suspend fun refreshPublicHost(target: ServerAdminTarget): ServerAdminActionResult =
+ runArgsAction(target, listOf("refresh-public-ip"))
+
+ suspend fun cleanupExpired(target: ServerAdminTarget): ServerAdminActionResult =
+ runArgsAction(target, listOf("cleanup-expired"))
+
+ suspend fun cleanupOrphans(target: ServerAdminTarget): ServerAdminActionResult =
+ runArgsAction(target, listOf("cleanup-orphans"))
+
+ suspend fun resetTraffic(target: ServerAdminTarget): ServerAdminActionResult =
+ runArgsAction(target, listOf("reset-traffic"))
+
+ suspend fun restart(target: ServerAdminTarget): ServerAdminActionResult =
+ withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ ssh.exec(rootCommand("systemctl restart wdtt"), RESTART_TIMEOUT)
+ ServerAdminActionResult(
+ message = "Готово",
+ restartRequired = false,
+ restarted = true,
+ createdClient = null
+ )
+ }
+ }
+
+ private suspend fun runPasswordAction(target: ServerAdminTarget, command: String, password: String): ServerAdminActionResult =
+ withContext(Dispatchers.IO) {
+ withSession(target) { ssh ->
+ actionFromResponse(callAdmin(ssh, target, listOf(command, "--password", password)))
+ }
+ }
+
+ private suspend fun runArgsAction(target: ServerAdminTarget, args: List): ServerAdminActionResult =
+ withContext(Dispatchers.IO) {
+ withSession(target) { ssh -> actionFromResponse(callAdmin(ssh, target, args)) }
+ }
+
+ private fun withSession(target: ServerAdminTarget, block: (AdminSshClient) -> T): T {
+ var session: Session? = null
+ try {
+ session = createSession(target)
+ return block(AdminSshClient(session, target.sshPassword))
+ } finally {
+ try { session?.disconnect() } catch (_: Exception) {}
+ }
+ }
+
+ private fun callAdmin(ssh: AdminSshClient, target: ServerAdminTarget, args: List): JSONObject {
+ val command = buildString {
+ append("/usr/local/bin/wdtt-server admin")
+ append(" --config-dir /etc/wdtt")
+ append(" --main-password ")
+ append(shellQuote(target.mainPassword))
+ args.forEach {
+ append(' ')
+ append(shellQuote(it))
+ }
+ }
+ val output = ssh.exec(rootCommand(command), ADMIN_TIMEOUT)
+ val json = extractJson(output)
+ if (!json.optBoolean("ok", false)) {
+ throw IllegalStateException(friendlyAdminError(json.optString("message", output)))
+ }
+ return json
+ }
+
+ private fun actionFromResponse(json: JSONObject): ServerAdminActionResult {
+ val restartRequired = json.optBoolean("restart_required", false)
+ if (restartRequired) {
+ throw IllegalStateException(
+ "Сервер вернул старый режим сохранения через перезапуск. " +
+ "Переустановите сервер из этой версии WDTT Plus, чтобы изменения применялись на живую."
+ )
+ }
+ val createdClient = json.optJSONObject("password")?.let(::parseClient)
+ return ServerAdminActionResult(
+ message = json.optString("message", "Готово"),
+ restartRequired = restartRequired,
+ restarted = false,
+ createdClient = createdClient
+ )
+ }
+
+ private fun parseState(json: JSONObject): ServerAdminState {
+ val server = json.optJSONObject("server") ?: JSONObject()
+ val clientsJson = json.optJSONArray("passwords")
+ val clients = buildList {
+ if (clientsJson != null) {
+ for (i in 0 until clientsJson.length()) {
+ val item = clientsJson.optJSONObject(i) ?: continue
+ add(parseClient(item))
+ }
+ }
+ }
+ val defaultPorts = server.optString("default_ports", "56000,56001,9000")
+ return ServerAdminState(
+ publicHost = server.optString("public_ip", ""),
+ effectivePublicHost = server.optString("effective_public_ip", ""),
+ dns = server.optString("dns", ""),
+ defaultPorts = defaultPorts,
+ maxPasswords = server.optInt("max_passwords", 50),
+ passwordCount = server.optInt("password_count", clients.size),
+ deviceCount = server.optInt("device_count", 0),
+ expiredCount = server.optInt("expired_count", 0),
+ orphanDeviceCount = server.optInt("orphan_device_count", 0),
+ orphanDevices = buildList {
+ val devices = server.optJSONArray("orphan_devices") ?: return@buildList
+ for (i in 0 until devices.length()) {
+ devices.optJSONObject(i)?.let { add(parseDevice(it)) }
+ }
+ },
+ traffic = parseTrafficPeriod(server.optJSONObject("traffic")),
+ adminTraffic = parseTrafficPeriod(server.optJSONObject("admin_traffic")),
+ adminProfile = parseAdminProfile(server.optJSONObject("admin_profile"), defaultPorts),
+ clients = clients
+ )
+ }
+
+ private fun parseAdminProfile(json: JSONObject?, defaultPorts: String): ServerAdminProfileInfo {
+ val ports = json?.optString("ports", defaultPorts).orEmpty().ifBlank { defaultPorts }
+ val listenPort = json?.optInt("listen_port", 0)
+ ?.takeIf { it in 1..65535 }
+ ?: ports.thirdPortOrDefault(9000)
+ val deviceIds = buildList {
+ val raw = json?.optJSONArray("device_ids") ?: return@buildList
+ for (i in 0 until raw.length()) {
+ raw.optString(i).trim().takeIf { it.isNotBlank() }?.let(::add)
+ }
+ }
+ return ServerAdminProfileInfo(
+ vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(),
+ secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(),
+ workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128),
+ protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
+ listenPort = listenPort,
+ sni = json?.optString("sni", "").orEmpty().trim(),
+ noDns = json?.optBoolean("no_dns", false) ?: false,
+ ports = ports,
+ deviceIds = deviceIds,
+ updatedAt = json?.optLong("updated_at", 0L) ?: 0L
+ )
+ }
+
+ private fun parseClient(json: JSONObject): ServerClientInfo =
+ ServerClientInfo(
+ password = json.optString("password"),
+ label = json.optString("label", "").trim(),
+ vkHash = json.optString("vk_hash"),
+ ports = json.optString("ports", "56000,56001,9000"),
+ status = json.optString("status", "active"),
+ expiresAt = json.optLong("expires_at", 0),
+ downBytes = json.optLong("down_bytes", 0),
+ upBytes = json.optLong("up_bytes", 0),
+ deviceId = json.optString("device_id"),
+ deviceName = json.optString("device_name"),
+ deviceIp = json.optString("device_ip"),
+ deviceLastSeen = json.optLong("device_last_seen", 0),
+ bindEventsCount = json.optInt("bind_events_count", 0),
+ traffic = parseTrafficPeriod(json.optJSONObject("traffic")),
+ device = json.optJSONObject("device")?.let(::parseDevice),
+ bindHistory = buildList {
+ val history = json.optJSONArray("bind_history") ?: return@buildList
+ for (i in 0 until history.length()) {
+ history.optJSONObject(i)?.let { add(parseBindEvent(it)) }
+ }
+ }
+ )
+
+ private fun parseTrafficPeriod(json: JSONObject?): ServerTrafficPeriod = ServerTrafficPeriod(
+ today = parseTrafficValue(json?.optJSONObject("today")),
+ week = parseTrafficValue(json?.optJSONObject("week")),
+ month = parseTrafficValue(json?.optJSONObject("month")),
+ all = parseTrafficValue(json?.optJSONObject("all"))
+ )
+
+ private fun parseTrafficValue(json: JSONObject?): ServerTrafficValue = ServerTrafficValue(
+ down = json?.optLong("down", 0) ?: 0,
+ up = json?.optLong("up", 0) ?: 0
+ )
+
+ private fun parseDevice(json: JSONObject): ServerDeviceInfo = ServerDeviceInfo(
+ deviceId = json.optString("device_id"), ip = json.optString("ip"), name = json.optString("name"),
+ manufacturer = json.optString("manufacturer"), brand = json.optString("brand"), model = json.optString("model"),
+ androidVersion = json.optString("android_version"), sdk = json.optInt("sdk", 0), abi = json.optString("abi"),
+ appVersion = json.optString("app_version"), locale = json.optString("locale"), country = json.optString("country"),
+ timeZone = json.optString("time_zone"), remoteIp = json.optString("remote_ip"), lastSeenAt = json.optLong("last_seen_at", 0)
+ )
+
+ private fun parseBindEvent(json: JSONObject): ServerBindEvent = ServerBindEvent(
+ deviceId = json.optString("device_id"), deviceName = json.optString("device_name"),
+ deviceIp = json.optString("device_ip"), remoteIp = json.optString("remote_ip"), country = json.optString("country"),
+ boundAt = json.optLong("bound_at", 0), unboundAt = json.optLong("unbound_at", 0), eventAt = json.optLong("event_at", 0),
+ status = json.optString("status"), note = json.optString("note")
+ )
+
+ private fun createSession(target: ServerAdminTarget): Session {
+ val session = JSch().getSession(target.user.ifBlank { "root" }, target.host, target.sshPort)
+ session.setPassword(target.sshPassword)
+ session.setConfig(Properties().apply {
+ put("StrictHostKeyChecking", "no")
+ put("ServerAliveInterval", "10")
+ put("ServerAliveCountMax", "6")
+ put("ConnectTimeout", "15000")
+ put("PreferredAuthentications", "password,keyboard-interactive")
+ })
+ session.connect(20_000)
+ return session
+ }
+
+ private fun shellQuote(value: String): String =
+ "'" + value.replace("'", "'\"'\"'") + "'"
+
+ private fun rootCommand(command: String): String {
+ val quoted = shellQuote(command)
+ return "if command -v sudo >/dev/null 2>&1; then sudo -S bash -c $quoted; " +
+ "elif [ \"\$(id -u)\" = \"0\" ]; then bash -c $quoted; " +
+ "else echo 'error: root privileges required and sudo not found'; exit 1; fi"
+ }
+
+ private fun extractJson(output: String): JSONObject {
+ val candidate = output
+ .lineSequence()
+ .map { it.trim() }
+ .filter { it.startsWith("{") && it.endsWith("}") }
+ .lastOrNull()
+ ?: throw IllegalStateException(friendlyAdminError(output.ifBlank { "сервер не вернул JSON" }))
+ return JSONObject(candidate)
+ }
+
+ private fun friendlyAdminError(raw: String): String {
+ val text = raw.trim()
+ val lower = text.lowercase()
+ return when {
+ "no_passwords_json" in lower ->
+ "на сервере не найдена база WDTT Plus. Сначала выполните деплой."
+ "admin_socket_unavailable" in lower ->
+ "сервер ещё не поддерживает управление без перезапуска. Переустановите сервер из этой версии WDTT Plus."
+ "главный пароль" in lower ->
+ "главный пароль администратора не совпадает с сервером."
+ "no such file" in lower || "not found" in lower && "wdtt-server" in lower ->
+ "на сервере старый wdtt-server без admin-команд. Переустановите сервер из этой версии WDTT Plus."
+ "permission denied" in lower || "authentication failed" in lower || "auth fail" in lower ->
+ "не удалось войти по SSH. Проверьте логин, пароль и порт."
+ "root privileges required" in lower || "sudo not found" in lower ->
+ "для управления нужны root-права или sudo на сервере."
+ "connection refused" in lower ->
+ "сервер отклонил SSH-подключение. Проверьте SSH-порт."
+ "timeout" in lower || "timed out" in lower ->
+ "сервер не ответил вовремя."
+ text.isBlank() -> "операция не выполнена"
+ else -> text.take(220)
+ }
+ }
+}
+
+private class AdminSshClient(private val session: Session, private val sudoPassword: String) {
+ fun exec(command: String, timeout: Long): String {
+ if (!session.isConnected) throw IllegalStateException("SSH-сессия разорвана")
+ var channel: ChannelExec? = null
+ val result = StringBuilder()
+ try {
+ channel = session.openChannel("exec") as ChannelExec
+ channel.setCommand(command)
+ val outStream = channel.outputStream
+ val input = channel.inputStream
+ val err = channel.errStream
+ channel.connect(15_000)
+ if (command.contains("sudo -S")) {
+ outStream.write("$sudoPassword\n".toByteArray())
+ outStream.flush()
+ }
+ val reader = input.bufferedReader()
+ val errReader = err.bufferedReader()
+ val started = System.currentTimeMillis()
+ while (!channel.isClosed || reader.ready() || errReader.ready()) {
+ if (System.currentTimeMillis() - started > timeout) {
+ try { channel.disconnect() } catch (_: Exception) {}
+ throw IllegalStateException("timeout")
+ }
+ if (reader.ready()) {
+ reader.readLine()?.let { result.appendLine(cleanShellLine(it)) }
+ }
+ if (errReader.ready()) {
+ errReader.readLine()
+ ?.takeIf { !it.contains("password for", ignoreCase = true) }
+ ?.let { result.appendLine(cleanShellLine(it)) }
+ }
+ if (!reader.ready() && !errReader.ready()) Thread.sleep(80)
+ }
+ val output = result.toString().trim()
+ if (channel.exitStatus != 0) {
+ if (output.startsWith("{") && output.endsWith("}")) return output
+ throw IllegalStateException(output.ifBlank { "команда завершилась с кодом ${channel.exitStatus}" })
+ }
+ if (output.startsWith("error:", ignoreCase = true)) {
+ throw IllegalStateException(output)
+ }
+ return output
+ } finally {
+ try { channel?.disconnect() } catch (_: Exception) {}
+ }
+ }
+
+ private fun cleanShellLine(line: String): String =
+ line.replace(Regex("\u001B\\[[;\\d]*m"), "")
+}
+
+private fun String.thirdPortOrDefault(default: Int): Int =
+ split(",").map { it.trim().toIntOrNull() }.getOrNull(2)?.takeIf { it in 1..65535 } ?: default
+
+fun ServerClientInfo.connectionLink(fallbackHost: String, publicHost: String): String? {
+ return buildServerConnectionLink(password, vkHash, ports, fallbackHost, publicHost)
+}
+
+fun buildServerConnectionLink(
+ password: String,
+ hashes: String,
+ ports: String,
+ fallbackHost: String,
+ publicHost: String
+): String? {
+ if (hashes.isBlank() || password.isBlank()) return null
+ val parts = ports.split(",").map { it.trim().toIntOrNull() }
+ if (parts.size != 3) return null
+ val dtls = parts[0]?.takeIf { it in 1..65535 } ?: return null
+ val wg = parts[1]?.takeIf { it in 1..65535 } ?: return null
+ val local = parts[2]?.takeIf { it in 1..65535 } ?: return null
+ val host = publicHost.ifBlank { fallbackHost }.trim()
+ if (host.isBlank()) return null
+ return WdttTransferCodec.buildConnectionLink(
+ WdttLinkParts(
+ host = host,
+ dtlsPort = dtls,
+ wgPort = wg,
+ localPort = local,
+ password = password,
+ hashes = hashes
+ )
+ )
+}
diff --git a/app/src/main/java/com/wdtt/plus/SettingsStore.kt b/app/src/main/java/com/wdtt/plus/SettingsStore.kt
index 1eee9ae..069f136 100644
--- a/app/src/main/java/com/wdtt/plus/SettingsStore.kt
+++ b/app/src/main/java/com/wdtt/plus/SettingsStore.kt
@@ -16,6 +16,8 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
+import org.json.JSONArray
+import org.json.JSONObject
import android.os.Build
@@ -81,7 +83,7 @@ object WdttDeepLink {
}
fun validate(value: String): WdttDeepLinkValidation {
- val clean = value.trim()
+ val clean = WdttTransferCodec.extractWdttLink(value) ?: value.trim()
val errors = mutableListOf()
val warnings = mutableListOf()
@@ -99,8 +101,18 @@ object WdttDeepLink {
)
}
- val parts = clean.substringAfter("://").split(":")
- if (parts.size != 6) {
+ val modernParts = if (clean.startsWith("wdtt://connect?", ignoreCase = true)) {
+ WdttTransferCodec.parseConnectionLink(clean)
+ } else null
+ if (clean.startsWith("wdtt://connect?", ignoreCase = true) && modernParts == null) {
+ return WdttDeepLinkValidation(
+ parts = null,
+ errors = listOf("Новая ссылка повреждена, содержит неподдерживаемую версию или не все поля.")
+ )
+ }
+
+ val parts = if (modernParts == null) clean.substringAfter("://").split(":") else emptyList()
+ if (modernParts == null && parts.size != 6) {
val found = parts.size
val detail = when {
found < 6 -> "не хватает ${6 - found} ${fieldWord(6 - found)}"
@@ -112,21 +124,21 @@ object WdttDeepLink {
)
}
- val host = parts[0].trim()
+ val host = modernParts?.host?.trim() ?: parts[0].trim()
if (!isValidTunnelHost(host)) {
errors += "Адрес сервера пустой или неверный. Нужен домен или IPv4 без https://, порта и пути."
}
- val dtlsPort = validatePort(parts[1], "DTLS-порт", errors)
- val wgPort = validatePort(parts[2], "WG-порт", errors)
- val localPort = validatePort(parts[3], "локальный порт", errors)
+ val dtlsPort = validatePort((modernParts?.dtlsPort ?: parts[1]).toString(), "DTLS-порт", errors)
+ val wgPort = validatePort((modernParts?.wgPort ?: parts[2]).toString(), "WG-порт", errors)
+ val localPort = validatePort((modernParts?.localPort ?: parts[3]).toString(), "локальный порт", errors)
- val password = parts[4].trim()
+ val password = modernParts?.password?.trim() ?: parts[4].trim()
if (password.isBlank()) {
errors += "Не указан пароль туннеля."
}
- val rawHashes = parts[5].split(",")
+ val rawHashes = (modernParts?.hashes ?: parts[5]).split(",")
val hashes = rawHashes
.map { VkJoinLink.extractHash(it) }
.filter { it.isNotBlank() && it.length >= 16 }
@@ -284,6 +296,10 @@ class SettingsStore(context: Context) {
private val UPDATE_DIALOG_LAST_ACTION_VERSION = stringPreferencesKey("update_dialog_last_action_version")
private val UPDATE_DIALOG_LAST_ACTION = stringPreferencesKey("update_dialog_last_action")
private val UPDATE_DIALOG_LAST_ACTION_AT = longPreferencesKey("update_dialog_last_action_at")
+ private val MIGRATION_NOTICE_V2_SHOWN = booleanPreferencesKey("migration_notice_v2_shown")
+ private val DEPLOY_CLIENTS_SECTION_EXPANDED = booleanPreferencesKey("deploy_clients_section_expanded")
+ private val DEPLOY_OUTBOUND_SECTION_EXPANDED = booleanPreferencesKey("deploy_outbound_section_expanded")
+ private val DEPLOY_MIGRATION_SECTION_EXPANDED = booleanPreferencesKey("deploy_migration_section_expanded")
private val CLIENT_ID_CHECK_RESULTS = stringPreferencesKey("client_id_check_results")
private val INTERFACE_ROLE = stringPreferencesKey("interface_role")
@@ -297,7 +313,7 @@ class SettingsStore(context: Context) {
return when (baseKey) {
PEER, VK_HASHES, SECONDARY_VK_HASH, PROTOCOL, SNI, USER_AGENT, DEPLOY_IP, DEPLOY_LOGIN, DEPLOY_PASSWORD, DEPLOY_PASSWORD_ENCRYPTED, 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 -> booleanPreferencesKey(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
else -> throw IllegalArgumentException("Unsupported key type: ${baseKey.name}")
}
}
@@ -408,7 +424,10 @@ class SettingsStore(context: Context) {
prefs[getProfileKey(baseKey, profile)] ?: ""
}
- val detailedLogs: Flow = dataStore.data.map { it[DETAILED_LOGS] ?: false }
+ val detailedLogs: Flow = dataStore.data.map { prefs ->
+ val profile = prefs[ACTIVE_PROFILE] ?: 0
+ prefs[getProfileKey(DETAILED_LOGS, profile)] ?: false
+ }
// ═══ Пароли и Управление ═══
val connectionPassword: Flow = dataStore.data.map { prefs ->
@@ -495,6 +514,10 @@ class SettingsStore(context: Context) {
val updateDialogLastActionVersion: Flow = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_VERSION] ?: "" }
val updateDialogLastAction: Flow = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION] ?: "" }
val updateDialogLastActionAt: Flow = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_AT] ?: 0L }
+ val migrationNoticeV2Shown: Flow = dataStore.data.map { it[MIGRATION_NOTICE_V2_SHOWN] ?: false }
+ val deployClientsSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: true }
+ val deployOutboundSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_OUTBOUND_SECTION_EXPANDED] ?: false }
+ val deployMigrationSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_MIGRATION_SECTION_EXPANDED] ?: false }
val interfaceRole: Flow = dataStore.data.map { it[INTERFACE_ROLE] ?: "" }
val permissionOnboardingComplete: Flow = dataStore.data.map { prefs ->
prefs[PERMISSION_ONBOARDING_COMPLETE] ?: !prefs[INTERFACE_ROLE].isNullOrBlank()
@@ -592,6 +615,30 @@ class SettingsStore(context: Context) {
}
}
+ suspend fun saveMigrationNoticeV2Shown() {
+ dataStore.edit { prefs ->
+ prefs[MIGRATION_NOTICE_V2_SHOWN] = true
+ }
+ }
+
+ suspend fun saveDeployClientsSectionExpanded(expanded: Boolean) {
+ dataStore.edit { prefs ->
+ prefs[DEPLOY_CLIENTS_SECTION_EXPANDED] = expanded
+ }
+ }
+
+ suspend fun saveDeployOutboundSectionExpanded(expanded: Boolean) {
+ dataStore.edit { prefs ->
+ prefs[DEPLOY_OUTBOUND_SECTION_EXPANDED] = expanded
+ }
+ }
+
+ suspend fun saveDeployMigrationSectionExpanded(expanded: Boolean) {
+ dataStore.edit { prefs ->
+ prefs[DEPLOY_MIGRATION_SECTION_EXPANDED] = expanded
+ }
+ }
+
suspend fun saveActiveProfile(profile: Int) {
dataStore.edit { prefs ->
prefs[ACTIVE_PROFILE] = profile
@@ -629,11 +676,158 @@ class SettingsStore(context: Context) {
link = cleanLink,
targetProfile = freeProfile ?: activeProfile,
requiresConfirmation = freeProfile == null,
- storeAsLink = prefs[getProfileKey(WDTT_LINK_MODE, activeProfile)] == true
+ storeAsLink = false
)
}.first()
}
+ suspend fun connectionLinkForProfile(profileIndex: Int): String {
+ val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
+ return dataStore.data.map { prefs ->
+ val storedLink = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty()
+ val storedParts = WdttDeepLink.parse(storedLink)
+ val parts = storedParts ?: WdttLinkParts(
+ host = prefs[getProfileKey(PEER, profile)].orEmpty().trim(),
+ dtlsPort = prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000,
+ 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()
+ )
+ val link = WdttTransferCodec.buildConnectionLink(parts)
+ val validation = WdttDeepLink.validate(link)
+ require(validation.canStartVpn) {
+ "Профиль VPN ${profile + 1} заполнен не полностью. Проверьте адрес, порты, пароль и VK-хеши."
+ }
+ link
+ }.first()
+ }
+
+ suspend fun exportAdminSettings(): String = dataStore.data.map { prefs ->
+ val profiles = JSONArray()
+ repeat(VPN_PROFILE_COUNT) { profile ->
+ profiles.put(JSONObject().apply {
+ put("wdttLink", prefs[getProfileKey(WDTT_LINK, profile)].orEmpty())
+ put("wdttLinkMode", prefs[getProfileKey(WDTT_LINK_MODE, profile)] ?: false)
+ 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("protocol", prefs[getProfileKey(PROTOCOL, profile)] ?: "udp")
+ put("listenPort", prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000)
+ put("manualPortsEnabled", prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] ?: false)
+ put("serverDtlsPort", prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000)
+ put("serverWgPort", prefs[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001)
+ put("sni", prefs[getProfileKey(SNI, profile)].orEmpty())
+ put("noDtls", prefs[getProfileKey(NO_DTLS, profile)] ?: false)
+ put("noDns", prefs[getProfileKey(NO_DNS, profile)] ?: false)
+ put("userAgent", prefs[getProfileKey(USER_AGENT, profile)].orEmpty())
+ put("connectionPassword", readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile))
+ put("deployIp", prefs[getProfileKey(DEPLOY_IP, profile)].orEmpty())
+ put("deployLogin", prefs[getProfileKey(DEPLOY_LOGIN, profile)].orEmpty())
+ put("deployPassword", readSecret(prefs, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile))
+ put("deploySshPort", prefs[getProfileKey(DEPLOY_SSH_PORT, profile)].orEmpty())
+ put("deployDns1", prefs[getProfileKey(DEPLOY_DNS1, profile)] ?: "1.1.1.1")
+ put("deployDns2", prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1")
+ put("deployMainPassword", readSecret(prefs, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile))
+ put("deployAdminId", readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile))
+ put("deployBotToken", readSecret(prefs, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile))
+ put("proxyMode", prefs[getProfileKey(PROXY_MODE, profile)] ?: "tun")
+ put("proxyHost", prefs[getProfileKey(PROXY_HOST, profile)] ?: "127.0.0.1")
+ put("proxyPort", prefs[getProfileKey(PROXY_PORT, profile)] ?: 1080)
+ put("vkCallsPreflight", prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true)
+ put("captchaMode", prefs[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto")
+ put("captchaSolveMethod", prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto")
+ put("captchaWbvSolveMethod", prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] ?: "auto")
+ put("isWhitelist", prefs[getProfileKey(IS_WHITELIST, profile)] ?: false)
+ put("blacklistApps", prefs[getProfileKey(BLACKLIST_APPS, profile)].orEmpty())
+ put("whitelistApps", prefs[getProfileKey(WHITELIST_APPS, profile)].orEmpty())
+ put("detailedLogs", prefs[getProfileKey(DETAILED_LOGS, profile)] ?: false)
+ put("selectedFingerprint", prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox")
+ put("activeClientIds", prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: "6287487,8202606")
+ })
+ }
+ JSONObject().apply {
+ put("format", "wdtt-plus-admin-settings")
+ put("version", 1)
+ put("activeProfile", (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1))
+ put("themeMode", prefs[THEME_MODE] ?: "system")
+ put("dynamicColor", prefs[IS_DYNAMIC_COLOR] ?: false)
+ put("themePalette", prefs[THEME_PALETTE] ?: "indigo")
+ put("showSystemApps", prefs[SHOW_SYSTEM_APPS] ?: false)
+ put("loggingEnabled", prefs[LOGGING_ENABLED] ?: true)
+ put("updateCheckIntervalHours", prefs[UPDATE_CHECK_INTERVAL_HOURS] ?: 12)
+ put("profiles", profiles)
+ put("outbound", exportSharedPreferences("wdtt_outbound_forms"))
+ }.toString()
+ }.first()
+
+ suspend fun importAdminSettings(settingsJson: String) {
+ val root = runCatching { JSONObject(settingsJson) }
+ .getOrElse { throw IllegalArgumentException("Расшифрованные настройки повреждены.") }
+ require(root.optString("format") == "wdtt-plus-admin-settings" && root.optInt("version") == 1) {
+ "Версия настроек не поддерживается."
+ }
+ val profiles = root.optJSONArray("profiles")
+ ?: throw IllegalArgumentException("В файле нет профилей VPN.")
+ require(profiles.length() == VPN_PROFILE_COUNT) { "Файл должен содержать три профиля VPN." }
+
+ 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[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(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")
+ prefs[getProfileKey(SERVER_DTLS_PORT, profile)] = item.safePort("serverDtlsPort", 56000)
+ prefs[getProfileKey(SERVER_WG_PORT, profile)] = item.safePort("serverWgPort", 56001)
+ prefs[getProfileKey(SNI, profile)] = item.optString("sni")
+ 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[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)
+ prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] = item.optString("deploySshPort")
+ prefs[getProfileKey(DEPLOY_DNS1, profile)] = item.optString("deployDns1", "1.1.1.1")
+ prefs[getProfileKey(DEPLOY_DNS2, profile)] = item.optString("deployDns2", "1.0.0.1")
+ prefs.putSecret(DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, item.optString("deployMainPassword"), profile)
+ prefs.putSecret(DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, item.optString("deployAdminId"), profile)
+ prefs.putSecret(DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, item.optString("deployBotToken"), profile)
+ prefs[getProfileKey(PROXY_MODE, profile)] = item.optString("proxyMode", "tun")
+ prefs[getProfileKey(PROXY_HOST, profile)] = item.optString("proxyHost", "127.0.0.1")
+ prefs[getProfileKey(PROXY_PORT, profile)] = item.safePort("proxyPort", 1080)
+ prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] = item.optBoolean("vkCallsPreflight", true)
+ prefs[getProfileKey(CAPTCHA_MODE, profile)] = item.optString("captchaMode", "auto")
+ prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] = item.optString("captchaSolveMethod", "auto")
+ prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] = item.optString("captchaWbvSolveMethod", "auto")
+ prefs[getProfileKey(IS_WHITELIST, profile)] = item.optBoolean("isWhitelist")
+ prefs[getProfileKey(BLACKLIST_APPS, profile)] = item.optString("blacklistApps")
+ prefs[getProfileKey(WHITELIST_APPS, profile)] = item.optString("whitelistApps")
+ prefs[getProfileKey(DETAILED_LOGS, profile)] = item.optBoolean("detailedLogs")
+ prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] = item.optString("selectedFingerprint", "firefox")
+ prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] = item.optString("activeClientIds", "6287487,8202606")
+ }
+ prefs[ACTIVE_PROFILE] = root.optInt("activeProfile", 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
+ prefs[THEME_MODE] = root.optString("themeMode", "system")
+ prefs[IS_DYNAMIC_COLOR] = root.optBoolean("dynamicColor")
+ prefs[THEME_PALETTE] = root.optString("themePalette", "indigo")
+ prefs[SHOW_SYSTEM_APPS] = root.optBoolean("showSystemApps")
+ prefs[LOGGING_ENABLED] = root.optBoolean("loggingEnabled", true)
+ prefs[UPDATE_CHECK_INTERVAL_HOURS] = root.optInt("updateCheckIntervalHours", 12)
+ prefs[INTERFACE_ROLE] = "admin"
+ }
+ importSharedPreferences("wdtt_outbound_forms", root.optJSONObject("outbound") ?: JSONObject())
+ }
+
suspend fun applyWdttDeepLink(plan: WdttDeepLinkApplyPlan): WdttDeepLinkApplyResult? {
val parts = WdttDeepLink.parse(plan.link) ?: return null
val profile = plan.targetProfile.coerceIn(0, VPN_PROFILE_COUNT - 1)
@@ -942,10 +1136,15 @@ class SettingsStore(context: Context) {
private fun Preferences.isTunnelProfileEmpty(profile: Int): Boolean {
val hasLink = (this[getProfileKey(WDTT_LINK, profile)] ?: "").isNotBlank()
- val hasManualTunnel = (this[getProfileKey(PEER, profile)] ?: "").isNotBlank() &&
- (this[getProfileKey(VK_HASHES, profile)] ?: "").split(",").any { it.isNotBlank() } &&
- readSecret(this, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile).isNotBlank()
- return !hasLink && !hasManualTunnel
+ val hasManualData = (this[getProfileKey(PEER, profile)] ?: "").isNotBlank() ||
+ (this[getProfileKey(VK_HASHES, profile)] ?: "").split(",").any { it.isNotBlank() } ||
+ (this[getProfileKey(SECONDARY_VK_HASH, profile)] ?: "").isNotBlank() ||
+ readSecret(this, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile).isNotBlank() ||
+ (this[getProfileKey(MANUAL_PORTS_ENABLED, profile)] == true &&
+ ((this[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000) != 56000 ||
+ (this[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001) != 56001 ||
+ (this[getProfileKey(LISTEN_PORT, profile)] ?: 9000) != 9000))
+ return !hasLink && !hasManualData
}
private fun MutablePreferences.clearManualTunnelFields(profile: Int) {
@@ -973,4 +1172,38 @@ class SettingsStore(context: Context) {
}
}
}
+
+ private fun exportSharedPreferences(name: String): JSONObject {
+ val result = JSONObject()
+ appContext.getSharedPreferences(name, Context.MODE_PRIVATE).all.forEach { (key, value) ->
+ when (value) {
+ is String, is Boolean, is Int, is Long, is Float -> result.put(key, value)
+ is Set<*> -> result.put(key, JSONArray(value.filterIsInstance()))
+ }
+ }
+ return result
+ }
+
+ private fun importSharedPreferences(name: String, json: JSONObject) {
+ val editor = appContext.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear()
+ val keys = json.keys()
+ while (keys.hasNext()) {
+ val key = keys.next()
+ when (val value = json.get(key)) {
+ is String -> editor.putString(key, value)
+ is Boolean -> editor.putBoolean(key, value)
+ is Int -> editor.putInt(key, value)
+ is Long -> editor.putLong(key, value)
+ is Double -> editor.putFloat(key, value.toFloat())
+ is JSONArray -> editor.putStringSet(
+ key,
+ (0 until value.length()).mapNotNull { value.optString(it).takeIf(String::isNotBlank) }.toSet()
+ )
+ }
+ }
+ editor.apply()
+ }
+
+ 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
new file mode 100644
index 0000000..64c65a0
--- /dev/null
+++ b/app/src/main/java/com/wdtt/plus/TransferCodec.kt
@@ -0,0 +1,187 @@
+package com.wdtt.plus
+
+import org.json.JSONObject
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.net.URLDecoder
+import java.net.URLEncoder
+import java.nio.charset.StandardCharsets
+import java.security.SecureRandom
+import java.util.Base64
+import java.util.zip.GZIPInputStream
+import java.util.zip.GZIPOutputStream
+import javax.crypto.Cipher
+import javax.crypto.SecretKeyFactory
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.PBEKeySpec
+import javax.crypto.spec.SecretKeySpec
+
+private const val TRANSFER_FORMAT = "wdtt-plus-transfer"
+private const val TRANSFER_VERSION = 1
+private const val ADMIN_KIND = "admin-settings"
+private const val PBKDF2_ITERATIONS = 210_000
+private const val KEY_BITS = 256
+private const val GCM_TAG_BITS = 128
+
+data class AdminTransferPreview(
+ val createdAt: Long,
+ val profileCount: Int,
+ val sourceVersion: String
+)
+
+object WdttTransferCodec {
+ private val random = SecureRandom()
+
+ fun buildConnectionLink(parts: WdttLinkParts): String {
+ val values = linkedMapOf(
+ "v" to "1",
+ "host" to parts.host,
+ "dtls" to parts.dtlsPort.toString(),
+ "wg" to parts.wgPort.toString(),
+ "local" to parts.localPort.toString(),
+ "password" to parts.password,
+ "hashes" to parts.hashes
+ )
+ return "wdtt://connect?" + values.entries.joinToString("&") { (key, value) ->
+ "${encode(key)}=${encode(value)}"
+ }
+ }
+
+ fun parseConnectionLink(value: String): WdttLinkParts? = runCatching {
+ parseConnectionLinkUnsafe(value)
+ }.getOrNull()
+
+ private fun parseConnectionLinkUnsafe(value: String): WdttLinkParts? {
+ val clean = extractWdttLink(value) ?: return null
+ if (!clean.startsWith("wdtt://connect?", ignoreCase = true)) return null
+ val query = clean.substringAfter('?', "")
+ val values = query.split('&')
+ .mapNotNull { token ->
+ val separator = token.indexOf('=')
+ if (separator <= 0) null
+ else decode(token.substring(0, separator)) to decode(token.substring(separator + 1))
+ }
+ .toMap()
+ if (values["v"] != "1") return null
+ return WdttLinkParts(
+ host = values["host"].orEmpty(),
+ dtlsPort = values["dtls"]?.toIntOrNull() ?: return null,
+ wgPort = values["wg"]?.toIntOrNull() ?: return null,
+ localPort = values["local"]?.toIntOrNull() ?: return null,
+ password = values["password"].orEmpty(),
+ hashes = values["hashes"].orEmpty()
+ )
+ }
+
+ fun extractWdttLink(value: String): String? {
+ val start = value.indexOf("wdtt://", ignoreCase = true)
+ if (start < 0) return null
+ return value.substring(start)
+ .substringBeforeAny(charArrayOf('\n', '\r', '\t', ' '))
+ .trimEnd('.', ',', ';', ')', ']', '}', '»', '"', '\'')
+ .takeIf { it.isNotBlank() }
+ }
+
+ fun encryptAdminSettings(settingsJson: String, password: CharArray): String {
+ require(password.size >= 8) { "Пароль должен содержать не меньше 8 символов." }
+ val salt = ByteArray(16).also(random::nextBytes)
+ val iv = ByteArray(12).also(random::nextBytes)
+ val key = deriveKey(password, salt, PBKDF2_ITERATIONS)
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv))
+ val compressed = gzip(settingsJson.toByteArray(StandardCharsets.UTF_8))
+ val encrypted = cipher.doFinal(compressed)
+ key.encoded?.fill(0)
+
+ return JSONObject()
+ .put("format", TRANSFER_FORMAT)
+ .put("version", TRANSFER_VERSION)
+ .put("kind", ADMIN_KIND)
+ .put("createdAt", System.currentTimeMillis())
+ .put("sourceVersion", BuildConfig.VERSION_NAME)
+ .put("kdf", "PBKDF2-HMAC-SHA256")
+ .put("iterations", PBKDF2_ITERATIONS)
+ .put("salt", Base64.getEncoder().encodeToString(salt))
+ .put("iv", Base64.getEncoder().encodeToString(iv))
+ .put("data", Base64.getEncoder().encodeToString(encrypted))
+ .toString()
+ }
+
+ fun isAdminTransfer(value: String): Boolean = runCatching {
+ val json = JSONObject(value.trim())
+ json.optString("format") == TRANSFER_FORMAT &&
+ json.optInt("version") == TRANSFER_VERSION &&
+ json.optString("kind") == ADMIN_KIND
+ }.getOrDefault(false)
+
+ fun documentFormat(value: String): String? = runCatching {
+ JSONObject(value.trim()).optString("format").takeIf { it.isNotBlank() }
+ }.getOrNull()
+
+ fun previewAdminTransfer(value: String): AdminTransferPreview {
+ val json = requireAdminEnvelope(value)
+ return AdminTransferPreview(
+ createdAt = json.optLong("createdAt"),
+ profileCount = 3,
+ sourceVersion = json.optString("sourceVersion", "неизвестно")
+ )
+ }
+
+ fun decryptAdminSettings(value: String, password: CharArray): String {
+ require(password.isNotEmpty()) { "Введите пароль файла." }
+ val json = requireAdminEnvelope(value)
+ val iterations = json.optInt("iterations", 0)
+ require(iterations in 100_000..1_000_000) { "Некорректные параметры защиты файла." }
+ val salt = Base64.getDecoder().decode(json.getString("salt"))
+ val iv = Base64.getDecoder().decode(json.getString("iv"))
+ val encrypted = Base64.getDecoder().decode(json.getString("data"))
+ require(salt.size == 16 && iv.size == 12) { "Файл передачи повреждён." }
+ val key = deriveKey(password, salt, iterations)
+ return try {
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv))
+ ungzip(cipher.doFinal(encrypted)).toString(StandardCharsets.UTF_8)
+ } catch (_: Exception) {
+ throw IllegalArgumentException("Неверный пароль или файл повреждён.")
+ } finally {
+ key.encoded?.fill(0)
+ }
+ }
+
+ private fun requireAdminEnvelope(value: String): JSONObject {
+ val json = runCatching { JSONObject(value.trim()) }
+ .getOrElse { throw IllegalArgumentException("Файл передачи повреждён или имеет неизвестный формат.") }
+ require(json.optString("format") == TRANSFER_FORMAT) { "Это не файл передачи WDTT Plus." }
+ require(json.optInt("version") == TRANSFER_VERSION) { "Версия файла пока не поддерживается." }
+ require(json.optString("kind") == ADMIN_KIND) { "В файле нет настроек администратора." }
+ return json
+ }
+
+ private fun deriveKey(password: CharArray, salt: ByteArray, iterations: Int): SecretKeySpec {
+ val spec = PBEKeySpec(password, salt, iterations, KEY_BITS)
+ return try {
+ val bytes = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
+ SecretKeySpec(bytes, "AES")
+ } finally {
+ spec.clearPassword()
+ }
+ }
+
+ private fun gzip(value: ByteArray): ByteArray = ByteArrayOutputStream().use { output ->
+ GZIPOutputStream(output).use { it.write(value) }
+ output.toByteArray()
+ }
+
+ private fun ungzip(value: ByteArray): ByteArray =
+ GZIPInputStream(ByteArrayInputStream(value)).use { it.readBytes() }
+
+ private fun encode(value: String): String = URLEncoder.encode(value, StandardCharsets.UTF_8.name())
+ .replace("+", "%20")
+
+ private fun decode(value: String): String = URLDecoder.decode(value, StandardCharsets.UTF_8.name())
+
+ private fun String.substringBeforeAny(delimiters: CharArray): String {
+ val index = indexOfFirst { it in delimiters }
+ return if (index < 0) this else substring(0, index)
+ }
+}
diff --git a/app/src/main/java/com/wdtt/plus/TransferFiles.kt b/app/src/main/java/com/wdtt/plus/TransferFiles.kt
new file mode 100644
index 0000000..a72e758
--- /dev/null
+++ b/app/src/main/java/com/wdtt/plus/TransferFiles.kt
@@ -0,0 +1,246 @@
+package com.wdtt.plus
+
+import android.content.Context
+import android.content.ContentValues
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.ImageDecoder
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.RectF
+import android.graphics.Typeface
+import android.net.Uri
+import android.os.Build
+import android.os.Environment
+import android.provider.MediaStore
+import androidx.core.content.FileProvider
+import androidx.core.content.ContextCompat
+import com.google.zxing.BarcodeFormat
+import com.google.zxing.BinaryBitmap
+import com.google.zxing.DecodeHintType
+import com.google.zxing.InvertedLuminanceSource
+import com.google.zxing.MultiFormatReader
+import com.google.zxing.RGBLuminanceSource
+import com.google.zxing.common.HybridBinarizer
+import com.google.zxing.qrcode.QRCodeWriter
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
+import java.io.File
+import java.io.ByteArrayOutputStream
+import java.nio.charset.StandardCharsets
+
+object TransferFiles {
+ private const val MAX_TRANSFER_BYTES = 5 * 1024 * 1024
+ const val MAX_QR_TEXT_BYTES = 2_600
+
+ fun createQrBitmap(context: Context, text: String, size: Int = 900): Bitmap {
+ require(text.toByteArray(StandardCharsets.UTF_8).size <= MAX_QR_TEXT_BYTES) {
+ "Эти данные слишком велики для одного QR-кода. Передайте их файлом."
+ }
+ val icon = loadAppIcon(context)
+ val highCorrection = runCatching {
+ createQrMatrix(text, size, ErrorCorrectionLevel.H)
+ }.getOrNull()
+ if (highCorrection != null) {
+ val plain = renderQr(highCorrection, size)
+ val branded = drawCenteredIcon(plain, icon)
+ if (runCatching { decodeQrBitmap(branded) }.getOrNull() == text) return branded
+ }
+
+ val compact = renderQr(createQrMatrix(text, size, ErrorCorrectionLevel.L), size)
+ return drawFooter(compact, icon)
+ }
+
+ private fun createQrMatrix(text: String, size: Int, correction: ErrorCorrectionLevel) =
+ QRCodeWriter().encode(
+ text,
+ BarcodeFormat.QR_CODE,
+ size,
+ size,
+ mapOf(
+ com.google.zxing.EncodeHintType.CHARACTER_SET to "UTF-8",
+ com.google.zxing.EncodeHintType.ERROR_CORRECTION to correction,
+ com.google.zxing.EncodeHintType.MARGIN to 2
+ )
+ )
+
+ private fun renderQr(matrix: com.google.zxing.common.BitMatrix, size: Int): Bitmap {
+ val pixels = IntArray(size * size)
+ for (y in 0 until size) {
+ val offset = y * size
+ for (x in 0 until size) {
+ pixels[offset + x] = if (matrix[x, y]) Color.BLACK else Color.WHITE
+ }
+ }
+ return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply {
+ setPixels(pixels, 0, size, 0, 0, size, size)
+ }
+ }
+
+ private fun drawCenteredIcon(qr: Bitmap, icon: Bitmap): Bitmap {
+ val result = qr.copy(Bitmap.Config.ARGB_8888, true)
+ val canvas = Canvas(result)
+ val iconSize = (qr.width * 0.075f).toInt()
+ val plateSize = (iconSize * 1.22f).toInt()
+ val centerX = qr.width / 2f
+ val centerY = qr.height / 2f
+ canvas.drawCircle(
+ centerX,
+ centerY,
+ plateSize / 2f,
+ Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE }
+ )
+ val iconLeft = (qr.width - iconSize) / 2f
+ val iconTop = (qr.height - iconSize) / 2f
+ val iconBounds = RectF(iconLeft, iconTop, iconLeft + iconSize, iconTop + iconSize)
+ canvas.save()
+ canvas.clipPath(Path().apply { addOval(iconBounds, Path.Direction.CW) })
+ canvas.drawBitmap(icon, null, iconBounds, Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
+ canvas.restore()
+ return result
+ }
+
+ private fun loadAppIcon(context: Context): Bitmap {
+ val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_launcher)?.mutate()
+ ?: throw IllegalStateException("Не удалось загрузить иконку WDTT Plus.")
+ val size = 192
+ return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also { bitmap ->
+ val canvas = Canvas(bitmap)
+ drawable.setBounds(0, 0, size, size)
+ drawable.draw(canvas)
+ }
+ }
+
+ private fun drawFooter(qr: Bitmap, icon: Bitmap): Bitmap {
+ val footerHeight = (qr.width * 0.13f).toInt()
+ val result = Bitmap.createBitmap(qr.width, qr.height + footerHeight, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(result)
+ canvas.drawColor(Color.WHITE)
+ canvas.drawBitmap(qr, 0f, 0f, null)
+ val iconSize = (footerHeight * 0.56f).toInt()
+ val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = Color.rgb(35, 35, 45)
+ textSize = footerHeight * 0.30f
+ typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
+ }
+ val label = "WDTT Plus"
+ val spacing = footerHeight * 0.14f
+ val groupWidth = iconSize + spacing + textPaint.measureText(label)
+ val iconLeft = (qr.width - groupWidth) / 2f
+ val iconTop = qr.height + (footerHeight - iconSize) / 2f
+ canvas.drawBitmap(icon, null, RectF(iconLeft, iconTop, iconLeft + iconSize, iconTop + iconSize), Paint(Paint.ANTI_ALIAS_FLAG))
+ val textX = iconLeft + iconSize + spacing
+ val textY = qr.height + footerHeight / 2f - (textPaint.ascent() + textPaint.descent()) / 2f
+ canvas.drawText(label, textX, textY, textPaint)
+ return result
+ }
+
+ fun decodeQrImage(context: Context, uri: Uri): String {
+ val source = ImageDecoder.createSource(context.contentResolver, uri)
+ val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
+ decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
+ val width = info.size.width
+ val height = info.size.height
+ val longest = maxOf(width, height)
+ if (longest > 2400) {
+ val scale = 2400f / longest
+ decoder.setTargetSize((width * scale).toInt(), (height * scale).toInt())
+ }
+ }.copy(Bitmap.Config.ARGB_8888, false)
+ return decodeQrBitmap(bitmap)
+ }
+
+ private fun decodeQrBitmap(bitmap: Bitmap): String {
+ val pixels = IntArray(bitmap.width * bitmap.height)
+ bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
+ val sourcePixels = RGBLuminanceSource(bitmap.width, bitmap.height, pixels)
+ val hints = mapOf(
+ DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
+ DecodeHintType.TRY_HARDER to true,
+ DecodeHintType.CHARACTER_SET to "UTF-8"
+ )
+ val reader = MultiFormatReader().apply { setHints(hints) }
+ return runCatching {
+ reader.decodeWithState(BinaryBitmap(HybridBinarizer(sourcePixels))).text
+ }.recoverCatching {
+ reader.reset()
+ reader.setHints(hints)
+ reader.decodeWithState(BinaryBitmap(HybridBinarizer(InvertedLuminanceSource(sourcePixels)))).text
+ }.getOrElse {
+ throw IllegalArgumentException("На выбранном изображении не найден читаемый QR-код.")
+ }.also { reader.reset() }
+ }
+
+ fun readText(context: Context, uri: Uri): String {
+ val bytes = context.contentResolver.openInputStream(uri)?.use { input ->
+ val output = ByteArrayOutputStream()
+ val buffer = ByteArray(8192)
+ var total = 0
+ while (true) {
+ val count = input.read(buffer)
+ if (count < 0) break
+ total += count
+ require(total <= MAX_TRANSFER_BYTES) { "Файл передачи слишком большой." }
+ output.write(buffer, 0, count)
+ }
+ output.toByteArray()
+ } ?: throw IllegalArgumentException("Не удалось открыть выбранный файл.")
+ return bytes.toString(StandardCharsets.UTF_8).removePrefix("\uFEFF").trim()
+ }
+
+ fun writeTransferText(context: Context, fileName: String, text: String): Uri {
+ val directory = File(context.cacheDir, "transfers").apply { mkdirs() }
+ directory.listFiles()?.forEach { file ->
+ if (System.currentTimeMillis() - file.lastModified() > 24L * 60L * 60L * 1000L) file.delete()
+ }
+ val safeName = fileName.toSafeTransferFileName("WDTT-Plus-transfer")
+ val file = File(directory, safeName).apply { writeText(text, Charsets.UTF_8) }
+ return FileProvider.getUriForFile(context, "${context.packageName}.files", file)
+ }
+
+ fun writeQrPng(context: Context, fileName: String, bitmap: Bitmap): Uri {
+ val directory = File(context.cacheDir, "transfers").apply { mkdirs() }
+ val safeName = fileName.toSafeTransferFileName("WDTT-Plus-QR.png")
+ val file = File(directory, safeName)
+ file.outputStream().use { output ->
+ require(bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)) { "Не удалось создать изображение QR-кода." }
+ }
+ return FileProvider.getUriForFile(context, "${context.packageName}.files", file)
+ }
+
+ fun saveQrToGallery(context: Context, fileName: String, bitmap: Bitmap): Uri {
+ val values = ContentValues().apply {
+ put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
+ put(MediaStore.Images.Media.MIME_TYPE, "image/png")
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/WDTT Plus")
+ put(MediaStore.Images.Media.IS_PENDING, 1)
+ }
+ }
+ val collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
+ val uri = context.contentResolver.insert(collection, values)
+ ?: throw IllegalStateException("Не удалось создать изображение в галерее.")
+ try {
+ context.contentResolver.openOutputStream(uri)?.use { output ->
+ require(bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)) {
+ "Не удалось сохранить QR-код."
+ }
+ } ?: throw IllegalStateException("Не удалось открыть файл изображения.")
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ values.clear()
+ values.put(MediaStore.Images.Media.IS_PENDING, 0)
+ context.contentResolver.update(uri, values, null, null)
+ }
+ return uri
+ } catch (error: Exception) {
+ context.contentResolver.delete(uri, null, null)
+ throw error
+ }
+ }
+
+ private fun String.toSafeTransferFileName(fallback: String): String =
+ replace(Regex("[^\\p{L}\\p{N}._-]+"), "-")
+ .replace(Regex("-+"), "-")
+ .trim('-', '.', '_')
+ .ifBlank { fallback }
+}
diff --git a/app/src/main/java/com/wdtt/plus/TunnelManager.kt b/app/src/main/java/com/wdtt/plus/TunnelManager.kt
index 9fe4798..4c01a3f 100644
--- a/app/src/main/java/com/wdtt/plus/TunnelManager.kt
+++ b/app/src/main/java/com/wdtt/plus/TunnelManager.kt
@@ -979,6 +979,19 @@ object TunnelManager {
updateLog("dtls_ok", "[DTLS] Соединение установлено ✓", 1, false)
lineTrim.contains("Активна ✓") ->
updateLog("ready", "[READY] Туннель готов к работе ✓", 2, false)
+ lineTrim.contains("Ошибка конфига", true) &&
+ lineTrim.contains("чтение ответа конфига", true) &&
+ (lineTrim.contains("timeout", true) || lineTrim.contains("context deadline exceeded", true)) ->
+ updateLog(
+ "worker_config_timeout_active",
+ if (activeWorkers.value > 0) {
+ "[ПОТОК] Один канал не получил конфигурацию вовремя; активных=${activeWorkers.value}, работа продолжается"
+ } else {
+ "[ПОТОК] Один канал не получил конфигурацию вовремя; пробуем через другие каналы"
+ },
+ 3,
+ false
+ )
isError -> {
val errorKey = when {
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 7c8f11f..7ead243 100644
--- a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt
+++ b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt
@@ -51,15 +51,20 @@ import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import com.wdtt.plus.DeployManager
+import com.wdtt.plus.ServerAdminClient
+import com.wdtt.plus.ServerAdminProfileInfo
+import com.wdtt.plus.ServerAdminTarget
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.WDTTColors
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
+import java.security.MessageDigest
import java.security.SecureRandom
import java.text.SimpleDateFormat
import java.util.Base64
@@ -88,6 +93,11 @@ private enum class OutboundDialog {
Diagnostics
}
+private enum class OwnerProfileSource {
+ Server,
+ LocalOnly
+}
+
private enum class ProxyKind(val label: String, val protocol: String) {
Socks5("SOCKS5", "socks5"),
Http("HTTP", "http")
@@ -124,14 +134,26 @@ private data class ServerImportPlan(
private data class ExistingServerConnection(
val host: String,
val password: String,
- val vkHash: String,
val ports: Triple,
val adminId: String,
val botToken: String,
val dns1: String,
val dns2: String,
- val source: String,
- val needsVkHash: Boolean
+ val adminProfile: ServerAdminProfileInfo
+)
+
+private data class PendingExistingConnectionApply(
+ val connection: ExistingServerConnection,
+ val effectiveLogin: String,
+ val localProfile: ServerAdminProfileInfo,
+ val serverProfile: ServerAdminProfileInfo,
+ val diffLines: List
+)
+
+private data class DeployServerComparison(
+ val overwriteLines: List = emptyList(),
+ val notes: List = emptyList(),
+ val checkError: String? = null
)
private data class DeployRequest(
@@ -156,20 +178,87 @@ private data class ExistingInstallInfo(
val accessDbExists: Boolean,
val wgKeysExist: Boolean,
val active: Boolean,
- val checkError: String? = null
+ val checkError: String? = null,
+ val comparison: DeployServerComparison? = null
) {
val hasAnyTrace: Boolean
get() = serviceExists || binaryExists || configDirExists || accessDbExists || wgKeysExist
}
+private data class OutboundProfileForms(
+ val localProxyPort: String,
+ val localProxyLogin: String,
+ val localProxyPassword: String,
+ val externalProxyKindName: String,
+ val externalProxyHost: String,
+ val externalProxyPort: String,
+ val externalProxyLogin: String,
+ val externalProxyPassword: String,
+ val wireGuardExitHost: String,
+ val wireGuardExitSshPort: String,
+ val wireGuardExitUser: String,
+ val wireGuardExitPassword: String,
+ val wireGuardExitPort: String,
+ val wireGuardExitDns: String,
+ val importedWireGuardConfig: String
+)
+
+private data class OutboundServerSnapshot(
+ val mode: String,
+ val detail: String,
+ val updatedAt: String,
+ val hasProfile: Boolean,
+ val localProxyPresent: Boolean,
+ val localProxyActive: Boolean,
+ val localProxyPort: String,
+ val localProxyLogin: String,
+ val localProxyPassword: String,
+ val externalProxyPresent: Boolean,
+ val externalProxyActive: Boolean,
+ val externalProxyKindName: String,
+ val externalProxyHost: String,
+ val externalProxyPort: String,
+ val externalProxyLogin: String,
+ val externalProxyPassword: String,
+ val wireGuardPresent: Boolean,
+ val wireGuardActive: Boolean,
+ val wireGuardExitHost: String,
+ val wireGuardExitSshPort: String,
+ val wireGuardExitUser: String,
+ val wireGuardExitPassword: String,
+ val wireGuardExitPort: String,
+ val wireGuardExitDns: String,
+ val importedWireGuardConfig: String
+) {
+ val modeLabel: String
+ get() = when (mode) {
+ "direct" -> "прямой выход"
+ "external_proxy" -> "внешний TCP-прокси"
+ "imported_wg" -> "VPN/WARP-файл"
+ "wireguard_vps" -> "выход через другой сервер"
+ else -> mode.ifBlank { "не указан" }
+ }
+
+ fun preferredDialog(): OutboundDialog? = when {
+ mode == "external_proxy" -> OutboundDialog.ExternalProxy
+ mode == "wireguard_vps" -> OutboundDialog.WireGuardVps
+ mode == "imported_wg" -> OutboundDialog.ImportedWireGuard
+ localProxyPresent -> OutboundDialog.LocalProxy
+ else -> null
+ }
+}
+
@OptIn(ExperimentalMaterial3Api::class)
@Composable
-fun DeployTab() {
+fun DeployTab(
+ scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
+) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
- val deployScrollState = rememberScrollState()
+ val deployScrollState = rememberRememberedScrollState(scrollPosition)
val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() }
+ var clientsSectionY by remember { mutableStateOf(0f) }
var outboundSectionY by remember { mutableStateOf(0f) }
var migrationSectionY by remember { mutableStateOf(0f) }
@@ -178,6 +267,14 @@ fun DeployTab() {
val savedIp by settingsStore.deployIp.collectAsStateWithLifecycle(initialValue = "")
val savedLogin by settingsStore.deployLogin.collectAsStateWithLifecycle(initialValue = "")
val savedPassword by settingsStore.deployPassword.collectAsStateWithLifecycle(initialValue = "")
+ val savedPeer by settingsStore.peer.collectAsStateWithLifecycle(initialValue = "")
+ 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 savedProtocol by settingsStore.protocol.collectAsStateWithLifecycle(initialValue = "udp")
+ val savedSni by settingsStore.sni.collectAsStateWithLifecycle(initialValue = "")
+ val savedNoDns by settingsStore.noDns.collectAsStateWithLifecycle(initialValue = false)
var ip by remember { mutableStateOf("") }
var login by remember { mutableStateOf("") }
@@ -198,6 +295,15 @@ fun DeployTab() {
val savedServerDtlsPort by settingsStore.serverDtlsPort.collectAsStateWithLifecycle(initialValue = 56000)
val savedServerWgPort by settingsStore.serverWgPort.collectAsStateWithLifecycle(initialValue = 56001)
val savedListenPort by settingsStore.listenPort.collectAsStateWithLifecycle(initialValue = 9000)
+ val clientsSectionExpanded by remember(settingsStore) {
+ settingsStore.deployClientsSectionExpanded.map { it as Boolean? }
+ }.collectAsStateWithLifecycle(initialValue = null)
+ val outboundSectionExpanded by remember(settingsStore) {
+ settingsStore.deployOutboundSectionExpanded.map { it as Boolean? }
+ }.collectAsStateWithLifecycle(initialValue = null)
+ val migrationSectionExpanded by remember(settingsStore) {
+ settingsStore.deployMigrationSectionExpanded.map { it as Boolean? }
+ }.collectAsStateWithLifecycle(initialValue = null)
var showSecretsDialog by remember { mutableStateOf(false) }
var showUninstallDialog by remember { mutableStateOf(false) }
@@ -214,6 +320,7 @@ fun DeployTab() {
var migrationStatus by rememberSaveable { mutableStateOf("") }
var existingConnectBusy by remember { mutableStateOf(false) }
var existingConnectStatus by rememberSaveable { mutableStateOf("") }
+ var pendingExistingConnectionApply by remember { mutableStateOf(null) }
var outboundDialog by remember { mutableStateOf(null) }
var outboundBusy by remember { mutableStateOf(false) }
var outboundProgressActive by remember { mutableStateOf(false) }
@@ -221,8 +328,6 @@ fun DeployTab() {
var outboundStatus by rememberSaveable { mutableStateOf("") }
var outboundStatusOwner by rememberSaveable { mutableStateOf(null) }
var importedWgConfigText by rememberSaveable { mutableStateOf("") }
- var outboundExpanded by rememberSaveable { mutableStateOf(false) }
- var migrationExpanded by rememberSaveable { mutableStateOf(false) }
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 {
@@ -370,15 +475,105 @@ fun DeployTab() {
outboundStatus = ""
outboundStatusOwner = OutboundDialog.ImportedWireGuard.name
} catch (e: Exception) {
- outboundStatus = "Ошибка чтения WireGuard-файла: ${friendlyDeployError(e, "импорт WireGuard")}"
+ outboundStatus = "Ошибка чтения VPN/WARP-файла: ${friendlyDeployError(e, "импорт VPN/WARP")}"
outboundStatusOwner = OutboundDialog.ImportedWireGuard.name
}
}
}
+ fun currentOwnerProfile(): ServerAdminProfileInfo = buildOwnerProfile(
+ vkHashes = savedVkHashes,
+ secondaryVkHash = savedSecondaryVkHash,
+ workersPerHash = savedWorkersPerHash,
+ protocol = savedProtocol,
+ listenPort = savedListenPort,
+ sni = savedSni,
+ noDns = savedNoDns,
+ dtlsPort = if (savedManualPorts) savedServerDtlsPort else 56000,
+ wgPort = if (savedManualPorts) savedServerWgPort else 56001
+ )
+
+ fun currentOutboundProfileForms(): OutboundProfileForms = 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
+ )
+
+ suspend fun syncOwnerProfileToServer(
+ requestHost: String,
+ requestUser: String,
+ requestPassword: String,
+ requestSshPort: Int,
+ requestMainPassword: String,
+ profile: ServerAdminProfileInfo
+ ): Result = runCatching {
+ ServerAdminClient.updateAdminProfile(
+ ServerAdminTarget(
+ host = requestHost,
+ user = requestUser.ifBlank { "root" },
+ sshPassword = requestPassword,
+ sshPort = requestSshPort,
+ mainPassword = requestMainPassword
+ ),
+ profile
+ )
+ }.map { }
+
+ suspend fun applyExistingConnection(
+ connection: ExistingServerConnection,
+ effectiveLogin: String,
+ profile: ServerAdminProfileInfo,
+ source: OwnerProfileSource
+ ) {
+ val ports = profile.effectivePorts(connection.ports)
+ val normalizedProfile = profile.copy(
+ listenPort = ports.third,
+ ports = ports.asPortsSpec()
+ )
+ settingsStore.save(
+ peer = connection.host,
+ vkHashes = normalizedProfile.vkHashes,
+ secondaryVkHash = normalizedProfile.secondaryVkHash,
+ workersPerHash = normalizedProfile.workersPerHash,
+ protocol = normalizedProfile.protocol,
+ listenPort = normalizedProfile.listenPort,
+ sni = normalizedProfile.sni,
+ noDns = normalizedProfile.noDns
+ )
+ settingsStore.saveConnectionPassword(connection.password)
+ settingsStore.savePorts(ports.first, ports.second, ports.third)
+ settingsStore.saveManualPortsEnabled(ports != Triple(56000, 56001, 9000))
+ settingsStore.saveDeploySecrets(
+ mainPass = savedMainPass,
+ adminId = connection.adminId,
+ botToken = connection.botToken,
+ sshPort = savedSshPort.ifBlank { "22" }
+ )
+ settingsStore.saveDeploy(ip.trim(), effectiveLogin, password, savedSshPort.ifBlank { "22" }, connection.dns1, connection.dns2)
+ settingsStore.saveWdttLinkMode(false)
+
+ existingConnectStatus = when (source) {
+ OwnerProfileSource.Server -> "Готово: данные восстановлены с сервера в приложение. Сервер не изменялся. Адрес: ${connection.host}; порты: ${ports.first}, ${ports.second}, ${ports.third}."
+ OwnerProfileSource.LocalOnly -> "Готово: подключение настроено по данным сервера, но сохранённого профиля владельца на нём нет — локальные поля «Туннеля» оставлены без изменений. Сервер не изменялся."
+ }
+ }
+
fun launchDeploy(request: DeployRequest, mode: DeployMode) {
val appContext = context.applicationContext
val importPlan = selectedImportBackup?.let { ServerImportPlan(it, selectedImportMode) }
+ val outboundProfile = currentOutboundProfileForms()
DeployManager.scope.launch {
try {
DeployManager.startDeploy()
@@ -405,6 +600,44 @@ fun DeployTab() {
onProgress = { p, s -> DeployManager.updateProgress(p, s) }
)
if (success) {
+ val ownerProfile = currentOwnerProfile()
+ DeployManager.updateProgress(0.97f, "Сохраняю профиль владельца на сервере...")
+ val ownerProfileSaved = syncOwnerProfileToServer(
+ requestHost = request.host,
+ requestUser = request.user,
+ requestPassword = request.pass,
+ requestSshPort = request.sshPort,
+ requestMainPassword = request.mainPass,
+ profile = ownerProfile
+ ).onFailure {
+ DeployManager.writeError("Owner profile sync after deploy error: ${it.message}")
+ TunnelManager.addDeployErrorLog("Профиль владельца после деплоя: ${friendlyDeployError(it, "сохранение")}")
+ }
+ DeployManager.updateProgress(0.985f, "Сохраняю профиль выходного IP на сервере...")
+ val outboundProfileSaved = runCatching {
+ writeOutboundProfileToServer(
+ context = appContext,
+ target = OutboundSshTarget(
+ host = request.host,
+ user = request.user.ifBlank { "root" },
+ pass = request.pass,
+ port = request.sshPort
+ ),
+ forms = outboundProfile
+ )
+ }.onFailure {
+ DeployManager.writeError("Outbound profile sync after deploy error: ${it.message}")
+ TunnelManager.addDeployErrorLog("Профиль выходного IP после деплоя: ${friendlyDeployError(it, "сохранение")}")
+ }
+ DeployManager.updateProgress(
+ 1f,
+ when {
+ ownerProfileSaved.isSuccess && outboundProfileSaved.isSuccess -> "Сервер обновлён, профили сохранены."
+ ownerProfileSaved.isSuccess -> "Сервер обновлён, профиль владельца сохранён."
+ outboundProfileSaved.isSuccess -> "Сервер обновлён, профиль выходного IP сохранён."
+ else -> "Сервер обновлён. Дополнительные профили не сохранились автоматически."
+ }
+ )
successCountdown = 5
showSuccessBanner = true
}
@@ -415,16 +648,33 @@ fun DeployTab() {
}
fun startDeployCheck(request: DeployRequest) {
+ val localOwnerProfile = currentOwnerProfile()
+ val localOutboundProfile = currentOutboundProfileForms()
scope.launch {
isCheckingExistingInstall = true
try {
- val info = checkExistingInstall(
+ var info = checkExistingInstall(
host = request.host,
user = request.user,
pass = request.pass,
port = request.sshPort
)
if (info.hasAnyTrace) {
+ val comparison = runCatching {
+ compareDeployWithServer(
+ context = context,
+ request = request,
+ localOwnerProfile = localOwnerProfile,
+ localOutboundProfile = localOutboundProfile,
+ inspectDatabase = info.accessDbExists
+ )
+ }.getOrElse {
+ DeployManager.writeError("Pre-deploy data comparison error: ${it.message}")
+ DeployServerComparison(
+ checkError = friendlyDeployError(it, "сверка данных перед установкой")
+ )
+ }
+ info = info.copy(comparison = comparison)
pendingDeployRequest = request
existingInstallInfo = info
} else {
@@ -491,6 +741,61 @@ fun DeployTab() {
}
}
+ fun applyOutboundSnapshot(snapshot: OutboundServerSnapshot) {
+ snapshot.localProxyPort.takeIf { it.isNotBlank() }?.let { localProxyPortInput = it }
+ snapshot.localProxyLogin.takeIf { it.isNotBlank() }?.let { localProxyLoginInput = it }
+ snapshot.localProxyPassword.takeIf { it.isNotBlank() }?.let { localProxyPasswordInput = it }
+
+ snapshot.externalProxyKindName.takeIf { name -> ProxyKind.entries.any { it.name == name } }?.let {
+ externalProxyKindName = it
+ }
+ snapshot.externalProxyHost.takeIf { it.isNotBlank() }?.let { externalProxyHostInput = it }
+ snapshot.externalProxyPort.takeIf { it.isNotBlank() }?.let { externalProxyPortInput = it }
+ snapshot.externalProxyLogin.takeIf { it.isNotBlank() }?.let { externalProxyLoginInput = it }
+ snapshot.externalProxyPassword.takeIf { it.isNotBlank() }?.let { externalProxyPasswordInput = it }
+
+ snapshot.wireGuardExitHost.takeIf { it.isNotBlank() }?.let { wireGuardExitHostInput = it }
+ snapshot.wireGuardExitSshPort.takeIf { it.isNotBlank() }?.let { wireGuardExitSshPortInput = it }
+ snapshot.wireGuardExitUser.takeIf { it.isNotBlank() }?.let { wireGuardExitUserInput = it }
+ snapshot.wireGuardExitPassword.takeIf { it.isNotBlank() }?.let { wireGuardExitPasswordInput = it }
+ snapshot.wireGuardExitPort.takeIf { it.isNotBlank() }?.let { wireGuardExitPortInput = it }
+ snapshot.wireGuardExitDns.takeIf { it.isNotBlank() }?.let { wireGuardExitDnsInput = it }
+
+ if (snapshot.importedWireGuardConfig.isNotBlank()) {
+ importedWgConfigText = snapshot.importedWireGuardConfig
+ }
+
+ val restoredDialog = snapshot.preferredDialog()
+ outboundDialog = restoredDialog
+ outboundStatusOwner = restoredDialog?.name
+ }
+
+ fun restoreOutboundFromServer() {
+ val target = currentOutboundTarget() ?: return
+ outboundBusy = true
+ outboundProgressActive = true
+ outboundActionTitle = "Читаю выходной IP с сервера"
+ outboundStatus = "Читаю настройки выходного IP и прокси с сервера..."
+ outboundStatusOwner = null
+ DeployManager.updateProgress(0.02f, "Читаю настройки выходного IP и прокси с сервера...")
+ scope.launch {
+ try {
+ val snapshot = readOutboundServerSnapshot(context, target)
+ applyOutboundSnapshot(snapshot)
+ outboundStatus = outboundRestoreSummary(snapshot)
+ } catch (e: Exception) {
+ outboundStatus = "Не удалось прочитать настройки выходного IP с сервера: ${friendlyDeployError(e, "выходной IP")}"
+ outboundStatusOwner = null
+ DeployManager.writeError("Outbound profile restore failed: ${e.message}")
+ } finally {
+ outboundBusy = false
+ outboundProgressActive = false
+ outboundActionTitle = ""
+ DeployManager.updateProgress(0f, "")
+ }
+ }
+ }
+
fun openOutboundDialog(dialog: OutboundDialog) {
outboundStatus = ""
outboundStatusOwner = dialog.name
@@ -739,7 +1044,7 @@ fun DeployTab() {
color = MaterialTheme.colorScheme.onSurface
)
Text(
- "Если WDTT Plus уже установлен на сервере, приложение подключится по SSH, сверит главный пароль из «Секретов» и заполнит поля клиента данными сервера. Сервер при этом не переустанавливается, а пользовательские доступы не меняются.",
+ "Подключение без установки работает только в направлении сервер → приложение: WDTT Plus проверяет главный пароль, показывает отличия и после подтверждения заполняет локальные поля. На сервер ничего не записывается, пользовательские доступы не меняются.\n\nНаправление приложение → сервер используется при установке с сохранением данных или с нуля. Настройки выходного IP восстанавливаются отдельно кнопкой «Заполнить» в соответствующем блоке.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -762,31 +1067,31 @@ fun DeployTab() {
port = savedSshPort.toIntOrNull() ?: 22,
adminMainPassword = savedMainPass
)
- settingsStore.save(
- peer = connection.host,
- vkHashes = connection.vkHash,
- secondaryVkHash = "",
- workersPerHash = 16,
- protocol = "udp",
- listenPort = connection.ports.third,
- sni = "",
- noDns = false
+ val localProfile = currentOwnerProfile()
+ val serverProfile = connection.adminProfile
+ val diffLines = existingConnectionDiffLines(
+ connection = connection,
+ localPeer = savedPeer,
+ localConnectionPassword = savedConnectionPassword,
+ localAdminId = savedAdminId,
+ localBotToken = savedBotToken,
+ localDns1 = dns1,
+ localDns2 = dns2,
+ localProfile = localProfile
)
- settingsStore.saveConnectionPassword(connection.password)
- settingsStore.savePorts(connection.ports.first, connection.ports.second, connection.ports.third)
- settingsStore.saveManualPortsEnabled(connection.ports != Triple(56000, 56001, 9000))
- settingsStore.saveDeploySecrets(
- mainPass = savedMainPass,
- adminId = connection.adminId,
- botToken = connection.botToken,
- sshPort = savedSshPort.ifBlank { "22" }
- )
- settingsStore.saveDeploy(ip.trim(), effectiveLogin, password, savedSshPort.ifBlank { "22" }, connection.dns1, connection.dns2)
- settingsStore.saveWdttLinkMode(false)
- existingConnectStatus = if (connection.needsVkHash) {
- "Готово: поля клиента заполнены. Сервер: ${connection.host}; порты: ${connection.ports.first}, ${connection.ports.second}, ${connection.ports.third}. VK-хеш на сервере не найден, добавьте его во вкладке «Туннель»."
+ if (diffLines.isNotEmpty()) {
+ pendingExistingConnectionApply = PendingExistingConnectionApply(
+ connection = connection,
+ effectiveLogin = effectiveLogin,
+ localProfile = localProfile,
+ serverProfile = serverProfile,
+ diffLines = diffLines
+ )
+ existingConnectStatus = "Данные сервера отличаются от локальных полей. Проверьте изменения перед восстановлением."
} else {
- "Готово: поля клиента заполнены. Сервер: ${connection.host}; порты: ${connection.ports.first}, ${connection.ports.second}, ${connection.ports.third}. ${connection.source}"
+ val profile = if (serverProfile.hasSavedFields) serverProfile else localProfile
+ val source = if (serverProfile.hasSavedFields) OwnerProfileSource.Server else OwnerProfileSource.LocalOnly
+ applyExistingConnection(connection, effectiveLogin, profile, source)
}
} catch (e: Exception) {
existingConnectStatus = "Ошибка подключения к готовому серверу: ${friendlyDeployError(e, "подключение")}"
@@ -817,27 +1122,125 @@ fun DeployTab() {
}
}
- OutboundRoutingSection(
- busy = outboundBusy,
- status = if (outboundDialog == null && outboundStatusOwner == null) outboundStatus else "",
- actionTitle = outboundActionTitle,
- enabled = !isDeploying && !migrationBusy && !outboundBusy,
- expanded = outboundExpanded,
- modifier = Modifier.onGloballyPositioned { outboundSectionY = it.positionInParent().y },
- onToggleExpanded = {
- val willExpand = !outboundExpanded
- outboundExpanded = willExpand
- if (willExpand) {
+ pendingExistingConnectionApply?.let { pending ->
+ AlertDialog(
+ onDismissRequest = {
+ if (!existingConnectBusy) {
+ pendingExistingConnectionApply = null
+ existingConnectStatus = "Подключение без установки отменено: локальные данные не изменены. Сервер также не изменялся."
+ }
+ },
+ title = { Text("Данные отличаются") },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(
+ "Подключение без установки заменит перечисленные локальные значения данными сервера. На сервер ничего записано не будет.",
+ style = MaterialTheme.typography.bodyMedium
+ )
+ HorizontalDivider()
+ pending.diffLines.forEach { line ->
+ Text("• $line", style = MaterialTheme.typography.bodySmall)
+ }
+ if (!pending.serverProfile.hasSavedFields) {
+ Text(
+ "На сервере нет сохранённого профиля владельца: поля «Туннеля» останутся локальными и не будут отправлены на сервер.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+ },
+ confirmButton = {
+ Button(
+ onClick = {
+ val selected = pending
+ pendingExistingConnectionApply = null
+ existingConnectBusy = true
+ existingConnectStatus = "Восстанавливаю данные с сервера в приложение..."
+ scope.launch {
+ try {
+ val source = if (selected.serverProfile.hasSavedFields) {
+ OwnerProfileSource.Server
+ } else {
+ OwnerProfileSource.LocalOnly
+ }
+ applyExistingConnection(
+ connection = selected.connection,
+ effectiveLogin = selected.effectiveLogin,
+ profile = if (selected.serverProfile.hasSavedFields) selected.serverProfile else selected.localProfile,
+ source = source
+ )
+ } catch (e: Exception) {
+ existingConnectStatus = "Ошибка восстановления данных: ${friendlyDeployError(e, "подключение")}"
+ DeployManager.writeError("Existing server owner profile apply error: ${e.message}")
+ } finally {
+ existingConnectBusy = false
+ }
+ }
+ },
+ enabled = !existingConnectBusy
+ ) { Text("Применить с сервера") }
+ },
+ dismissButton = {
+ TextButton(
+ onClick = {
+ pendingExistingConnectionApply = null
+ existingConnectStatus = "Подключение без установки отменено: локальные данные и сервер не изменены."
+ },
+ enabled = !existingConnectBusy
+ ) { Text("Отмена") }
+ }
+ )
+ }
+
+ clientsSectionExpanded?.let { clientsExpanded ->
+ ServerClientsSection(
+ host = ip.trim(),
+ user = if (login.isBlank()) "root" else login,
+ sshPassword = password,
+ sshPort = savedSshPort.toIntOrNull() ?: 22,
+ mainPassword = savedMainPass,
+ defaultPorts = "${if (savedManualPorts) savedServerDtlsPort else 56000},${if (savedManualPorts) savedServerWgPort else 56001},${if (savedManualPorts) savedListenPort else 9000}",
+ adminProfile = currentOwnerProfile(),
+ enabled = !isDeploying && !isCheckingExistingInstall && !migrationBusy && !outboundBusy && isServerAddressValid,
+ expanded = clientsExpanded,
+ modifier = Modifier.onGloballyPositioned { clientsSectionY = it.positionInParent().y },
+ onExpandedChange = { expanded ->
+ scope.launch { settingsStore.saveDeployClientsSectionExpanded(expanded) }
+ },
+ onExpanded = {
scope.launch {
kotlinx.coroutines.delay(80)
- deployScrollState.animateScrollTo((outboundSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0))
+ deployScrollState.animateScrollTo((clientsSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0))
}
}
- },
- onOpen = { openOutboundDialog(it) },
- onStatus = { runOutboundAction("Проверяю текущий выход WDTT") { readOutboundStatus(it) } },
- onDirect = { runOutboundAction("Возвращаю прямой выход WDTT") { disableOutboundExit(it) } }
- )
+ )
+ }
+
+ outboundSectionExpanded?.let { outboundExpanded ->
+ OutboundRoutingSection(
+ busy = outboundBusy,
+ status = if (outboundDialog == null && outboundStatusOwner == null) outboundStatus else "",
+ actionTitle = outboundActionTitle,
+ enabled = !isDeploying && !migrationBusy && !outboundBusy,
+ expanded = outboundExpanded,
+ modifier = Modifier.onGloballyPositioned { outboundSectionY = it.positionInParent().y },
+ onToggleExpanded = {
+ val willExpand = !outboundExpanded
+ scope.launch { settingsStore.saveDeployOutboundSectionExpanded(willExpand) }
+ if (willExpand) {
+ scope.launch {
+ kotlinx.coroutines.delay(80)
+ deployScrollState.animateScrollTo((outboundSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0))
+ }
+ }
+ },
+ onOpen = { openOutboundDialog(it) },
+ onRestore = { restoreOutboundFromServer() },
+ onStatus = { runOutboundAction("Проверяю текущий выход WDTT") { readOutboundStatus(it) } },
+ onDirect = { runOutboundAction("Возвращаю прямой выход WDTT") { disableOutboundExit(it) } }
+ )
+ }
outboundDialog?.let { dialog ->
when (dialog) {
@@ -855,8 +1258,15 @@ fun DeployTab() {
onPasswordChanged = { localProxyPasswordInput = it },
onDismiss = { outboundDialog = null },
onInstall = { proxyPort, loginValue, passwordValue ->
+ val forms = currentOutboundProfileForms().copy(
+ localProxyPort = proxyPort.toString(),
+ localProxyLogin = loginValue,
+ localProxyPassword = passwordValue
+ )
runOutboundAction("Устанавливаю прокси на этом сервере") {
- installLocalProxy(context, it, proxyPort, loginValue, passwordValue)
+ val result = installLocalProxy(context, it, proxyPort, loginValue, passwordValue)
+ val saveMessage = saveOutboundProfileMessage(context, it, forms, "Поля прокси сохранены на сервере для восстановления.")
+ "$result\n$saveMessage"
}
},
onCheck = { proxyPort, loginValue, passwordValue ->
@@ -898,13 +1308,22 @@ fun DeployTab() {
onPasswordChanged = { externalProxyPasswordInput = it },
onDismiss = { outboundDialog = null },
onCheck = { kind, hostValue, proxyPort, loginValue, passwordValue ->
- runOutboundAction("Проверяю доступность внешнего прокси") {
+ runOutboundAction("Проверяю доступность внешнего TCP-прокси") {
checkExternalProxy(context, it, kind, hostValue, proxyPort, loginValue, passwordValue)
}
},
onEnable = { kind, hostValue, proxyPort, loginValue, passwordValue ->
- runOutboundAction("Проверяю и включаю внешний прокси") {
- enableExternalProxy(context, it, kind, hostValue, proxyPort, loginValue, passwordValue)
+ val forms = currentOutboundProfileForms().copy(
+ externalProxyKindName = kind.name,
+ externalProxyHost = hostValue,
+ externalProxyPort = proxyPort.toString(),
+ externalProxyLogin = loginValue,
+ externalProxyPassword = passwordValue
+ )
+ runOutboundAction("Проверяю и включаю внешний TCP-прокси") {
+ val result = enableExternalProxy(context, it, kind, hostValue, proxyPort, loginValue, passwordValue)
+ val saveMessage = saveOutboundProfileMessage(context, it, forms, "Поля внешнего прокси сохранены на сервере для восстановления.")
+ "$result\n$saveMessage"
}
},
onDisable = {
@@ -931,8 +1350,16 @@ fun DeployTab() {
onDnsChanged = { wireGuardExitDnsInput = it },
onDismiss = { outboundDialog = null },
onInstall = { foreignHost, foreignPort, foreignUser, foreignPassword, wgPort, dns ->
+ val forms = currentOutboundProfileForms().copy(
+ wireGuardExitHost = foreignHost,
+ wireGuardExitSshPort = foreignPort.toString(),
+ wireGuardExitUser = foreignUser,
+ wireGuardExitPassword = foreignPassword,
+ wireGuardExitPort = wgPort.toString(),
+ wireGuardExitDns = dns
+ )
runOutboundAction("Настраиваю WireGuard-выход через другой сервер") {
- installWireGuardExitVps(
+ val result = installWireGuardExitVps(
context = context,
current = it,
foreignHost = foreignHost,
@@ -942,6 +1369,13 @@ fun DeployTab() {
wgPort = wgPort,
dns = dns
)
+ val saveMessage = saveOutboundProfileMessage(context, it, forms, "Поля выхода через другой сервер сохранены на сервере для восстановления.")
+ "$result\n$saveMessage"
+ }
+ },
+ onCheck = {
+ runOutboundAction("Проверяю выход через другой сервер") {
+ checkWireGuardExit(it, expectedMode = "wireguard_vps")
}
},
onDisable = {
@@ -960,23 +1394,31 @@ fun DeployTab() {
onDismiss = { outboundDialog = null },
onValidate = { config ->
outboundStatus = validateWireGuardConfigText(config).fold(
- onSuccess = { "Файл подходит: WireGuard-выход будет применён только к WDTT-пользователям, обычный интернет сервера не изменится." },
- onFailure = { "Ошибка WireGuard-файла: ${it.message}" }
+ onSuccess = { "Файл подходит: это обычный WireGuard-конфиг. Если он выдан WARP, WDTT Plus применит его как WARP/VPN-выход только для WDTT-пользователей; обычный интернет сервера не изменится." },
+ onFailure = { "Ошибка VPN/WARP-файла: ${it.message}" }
)
outboundStatusOwner = OutboundDialog.ImportedWireGuard.name
},
onEnable = { config ->
importedWgConfigText = config
- runOutboundAction("Включаю WireGuard-выход из файла") {
- enableImportedWireGuardExit(context, it, config)
+ val forms = currentOutboundProfileForms().copy(importedWireGuardConfig = config)
+ runOutboundAction("Включаю VPN/WARP-выход из файла") {
+ val result = enableImportedWireGuardExit(context, it, config)
+ val saveMessage = saveOutboundProfileMessage(context, it, forms, "VPN/WARP-файл сохранён на сервере для восстановления.")
+ "$result\n$saveMessage"
}
},
onDisable = {
runOutboundAction("Возвращаю прямой выход WDTT") { disableOutboundExit(it) }
},
+ onServerCheck = {
+ runOutboundAction("Проверяю установленный VPN/WARP-выход") {
+ checkWireGuardExit(it, expectedMode = "imported_wg")
+ }
+ },
onDelete = {
importedWgConfigText = ""
- runOutboundAction("Удаляю WireGuard-файл и возвращаю прямой выход") { deleteImportedWireGuardExit(it) }
+ runOutboundAction("Удаляю VPN/WARP-файл и возвращаю прямой выход") { deleteImportedWireGuardExit(it) }
}
)
OutboundDialog.Diagnostics -> OutboundDiagnosticsDialog(
@@ -1012,60 +1454,61 @@ fun DeployTab() {
)
}
- val migrationArrowRotation by animateFloatAsState(
- targetValue = if (migrationExpanded) 180f else 0f,
- label = "migration_arrow_rotation"
- )
+ migrationSectionExpanded?.let { migrationExpanded ->
+ val migrationArrowRotation by animateFloatAsState(
+ targetValue = if (migrationExpanded) 180f else 0f,
+ label = "migration_arrow_rotation"
+ )
- AppSectionCard(
- modifier = Modifier.onGloballyPositioned { migrationSectionY = it.positionInParent().y },
- contentPadding = PaddingValues(16.dp),
- verticalArrangement = Arrangement.spacedBy(0.dp)
- ) {
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .clip(RoundedCornerShape(24.dp))
- .clickable {
- val willExpand = !migrationExpanded
- migrationExpanded = willExpand
- if (willExpand) {
- scope.launch {
- kotlinx.coroutines.delay(80)
- deployScrollState.animateScrollTo((migrationSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0))
+ AppSectionCard(
+ modifier = Modifier.onGloballyPositioned { migrationSectionY = it.positionInParent().y },
+ contentPadding = PaddingValues(16.dp),
+ verticalArrangement = Arrangement.spacedBy(0.dp)
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(24.dp))
+ .clickable {
+ val willExpand = !migrationExpanded
+ scope.launch { settingsStore.saveDeployMigrationSectionExpanded(willExpand) }
+ if (willExpand) {
+ scope.launch {
+ kotlinx.coroutines.delay(80)
+ deployScrollState.animateScrollTo((migrationSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0))
+ }
}
}
+ .padding(vertical = 2.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Surface(shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.primaryContainer) {
+ Box(modifier = Modifier.size(40.dp), contentAlignment = Alignment.Center) {
+ Icon(
+ imageVector = Icons.Default.CloudUpload,
+ contentDescription = null,
+ tint = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.size(18.dp)
+ )
+ }
}
- .padding(vertical = 2.dp),
- horizontalArrangement = Arrangement.spacedBy(12.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Surface(shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.primaryContainer) {
- Box(modifier = Modifier.size(40.dp), contentAlignment = Alignment.Center) {
- Icon(
- imageVector = Icons.Default.CloudUpload,
- contentDescription = null,
- tint = MaterialTheme.colorScheme.primary,
- modifier = Modifier.size(18.dp)
- )
- }
+ Text(
+ "Перенос сервера",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold,
+ color = MaterialTheme.colorScheme.onSurface,
+ modifier = Modifier.weight(1f)
+ )
+ Icon(
+ imageVector = Icons.Default.KeyboardArrowDown,
+ contentDescription = null,
+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier
+ .size(24.dp)
+ .rotate(migrationArrowRotation)
+ )
}
- Text(
- "Перенос сервера",
- style = MaterialTheme.typography.titleMedium,
- fontWeight = FontWeight.Bold,
- color = MaterialTheme.colorScheme.onSurface,
- modifier = Modifier.weight(1f)
- )
- Icon(
- imageVector = Icons.Default.KeyboardArrowDown,
- contentDescription = null,
- tint = MaterialTheme.colorScheme.onSurfaceVariant,
- modifier = Modifier
- .size(24.dp)
- .rotate(migrationArrowRotation)
- )
- }
AnimatedVisibility(
visible = migrationExpanded,
@@ -1087,6 +1530,11 @@ fun DeployTab() {
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
+ Text(
+ "Настройки выходного IP, прокси и VPN/WARP-файлы этим экспортом не переносятся. После переезда включите нужный режим выхода на новом сервере заново.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
Text(
"Файл экспорта содержит секреты доступа. Храните его как пароль от сервера.",
style = MaterialTheme.typography.bodySmall,
@@ -1275,6 +1723,7 @@ fun DeployTab() {
}
}
}
+ }
if (showUninstallDialog) {
UninstallConfirmDialog(
@@ -1519,6 +1968,7 @@ private fun OutboundRoutingSection(
modifier: Modifier = Modifier,
onToggleExpanded: () -> Unit,
onOpen: (OutboundDialog) -> Unit,
+ onRestore: () -> Unit,
onStatus: () -> Unit,
onDirect: () -> Unit
) {
@@ -1584,33 +2034,52 @@ private fun OutboundRoutingSection(
) {
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f))
Text(
- "Помогает выбрать, с какого IP будут выходить пользователи WDTT. Настройки обычного интернета на самом сервере не меняются.",
+ "Выбирает IP, который видят сайты и сервисы у пользователей WDTT. Сам адрес WDTT-сервера, входящие DTLS/SSH и ссылка подключения этим не скрываются.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
- "Раздел ещё обкатывается. При возникновении ошибок пишите в «Поднять вопрос» на вкладке «Инфо» и прикладывайте логи вместе с диагностикой выхода.",
+ "Обычная сеть самого сервера не меняется. Для маскировки выходного IP используйте внешний TCP-прокси, другой сервер или VPN/WARP-файл.",
style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.error
+ color = MaterialTheme.colorScheme.onSurfaceVariant
)
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- OutboundModeButton("Прокси на этом сервере", "Создать прокси с логином и паролем на текущем сервере.", enabled) {
+ OutboundModeButton("Прокси VPS", "Создаёт SOCKS5/HTTP на этом сервере. IP не скрывает: выход будет через тот же VPS.", enabled) {
onOpen(OutboundDialog.LocalProxy)
}
- OutboundModeButton("Внешний прокси", "Пустить обычные подключения WDTT через внешний прокси. Звонки могут использовать отдельный трафик и пройти напрямую.", enabled) {
+ OutboundModeButton("Внешний TCP-прокси", "Скрывает IP для обычного TCP-трафика. UDP, QUIC и часть звонков могут пройти напрямую.", enabled) {
onOpen(OutboundDialog.ExternalProxy)
}
- OutboundModeButton("Выход через другой сервер", "Сделать другой сервер отдельной точкой выхода для пользователей WDTT.", enabled) {
+ OutboundModeButton("Другой сервер", "Надёжно выносит выходной IP на отдельный VPS через WireGuard.", enabled) {
onOpen(OutboundDialog.WireGuardVps)
}
- OutboundModeButton("Готовый WireGuard-файл", "Подключить готовый WireGuard-профиль как отдельный выход для пользователей WDTT.", enabled) {
+ OutboundModeButton("VPN/WARP-файл", "Принимает WireGuard .conf, в том числе WARP, если он сохранён именно как WireGuard-конфиг.", enabled) {
onOpen(OutboundDialog.ImportedWireGuard)
}
}
+ Text(
+ "«Заполнить» читает сохранённые настройки с сервера и заменяет ими только локальные поля этого блока. На сервер ничего не записывается; активный режим выхода не переключается.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
+ OutlinedButton(
+ onClick = onRestore,
+ enabled = enabled,
+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
+ shape = RoundedCornerShape(16.dp),
+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp)
+ ) {
+ val restoring = busy && actionTitle.contains("Читаю выходной IP", ignoreCase = true)
+ if (restoring) {
+ CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
+ Spacer(Modifier.width(6.dp))
+ }
+ Text(if (restoring) "Читаю..." else "Заполнить", fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center)
+ }
OutlinedButton(
onClick = onStatus,
enabled = enabled,
@@ -1624,14 +2093,14 @@ private fun OutboundRoutingSection(
}
Text(if (readingStatus) "Читаю..." else "Статус", fontWeight = FontWeight.SemiBold)
}
- OutlinedButton(
- onClick = { onOpen(OutboundDialog.Diagnostics) },
- enabled = enabled,
- modifier = Modifier.weight(1f).heightIn(min = 48.dp),
- shape = RoundedCornerShape(16.dp)
- ) {
- Text("Диагностика", fontWeight = FontWeight.SemiBold)
- }
+ }
+ OutlinedButton(
+ onClick = { onOpen(OutboundDialog.Diagnostics) },
+ enabled = enabled,
+ modifier = Modifier.align(Alignment.CenterHorizontally).heightIn(min = 48.dp),
+ shape = RoundedCornerShape(16.dp)
+ ) {
+ Text("Диагностика", fontWeight = FontWeight.SemiBold)
}
Button(
onClick = onDirect,
@@ -1725,9 +2194,9 @@ private fun LocalProxyDialog(
) {
var passwordFocused by rememberSaveable { mutableStateOf(false) }
val port = portInput.toIntOrNull()?.takeIf { it in 1..65533 }
- OutboundDialogFrame("Прокси на этом сервере", status, progressTitle, progress, onDismiss) {
+ OutboundDialogFrame("Прокси VPS", status, progressTitle, progress, onDismiss) {
Text(
- "На этом сервере будут созданы два входа с одним логином и паролем: SOCKS5 и HTTP. Их можно выдать тем, кому нужен прокси-адрес этого сервера.",
+ "На этом же VPS будут созданы два входа с одним логином и паролем: SOCKS5 и HTTP. Это удобно как прокси, но IP не маскирует: наружу будет виден текущий сервер.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -1848,9 +2317,9 @@ private fun ExternalProxyDialog(
var passwordFocused by rememberSaveable { mutableStateOf(false) }
val port = portInput.toIntOrNull()?.takeIf { it in 1..65535 }
val hostValid = hostInput.isValidPublicHost()
- OutboundDialogFrame("Внешний прокси", status, progressTitle, progress, onDismiss) {
+ OutboundDialogFrame("Внешний TCP-прокси", status, progressTitle, progress, onDismiss) {
Text(
- "WDTT будет отправлять обычные подключения пользователей через выбранный прокси. Если звонок использует отдельный голосовой трафик, он может идти напрямую.",
+ "WDTT будет отправлять обычные TCP-подключения пользователей через выбранный прокси. UDP, QUIC и часть голосового/звонкового трафика могут идти напрямую.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -1902,13 +2371,13 @@ private fun ExternalProxyDialog(
shape = RoundedCornerShape(16.dp)
)
Text(
- "При включении прежний внешний выход WDTT будет выключен, затем начнёт работать этот прокси. Обычный интернет самого сервера не меняется.",
+ "При включении прежний внешний выход WDTT будет выключен, затем начнёт работать этот прокси. Это маскирует только поддерживаемый TCP-трафик пользователей; обычный интернет самого сервера не меняется.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
DialogButtons(
busy = busy,
- primaryBusy = actionTitle.contains("включаю внешний прокси", ignoreCase = true),
+ primaryBusy = actionTitle.contains("включаю внешний TCP-прокси", ignoreCase = true),
secondaryBusy = actionTitle.contains("Проверяю доступность", ignoreCase = true),
primaryText = "Включить",
primaryBusyText = "Включение...",
@@ -1950,15 +2419,16 @@ private fun WireGuardExitVpsDialog(
onDnsChanged: (String) -> Unit,
onDismiss: () -> Unit,
onInstall: (String, Int, String, String, Int, String) -> Unit,
+ onCheck: () -> Unit,
onDisable: () -> Unit
) {
var passwordFocused 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 }
- OutboundDialogFrame("Другой сервер через WireGuard", status, progressTitle, progress, onDismiss) {
+ OutboundDialogFrame("Выход через другой сервер", status, progressTitle, progress, onDismiss) {
Text(
- "WDTT Plus подключится к другому серверу, настроит WireGuard и будет выпускать пользователей WDTT в интернет через этот второй сервер.",
+ "WDTT Plus подключит текущий сервер к другому VPS по WireGuard и будет выпускать пользователей WDTT в интернет через этот второй сервер. Это самый понятный вариант для отдельного выходного IP.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -2027,15 +2497,23 @@ private fun WireGuardExitVpsDialog(
DialogButtons(
busy = busy,
primaryBusy = actionTitle.contains("Настраиваю WireGuard", ignoreCase = true),
- secondaryBusy = actionTitle.contains("Возвращаю", ignoreCase = true),
+ secondaryBusy = actionTitle.contains("Проверяю выход", ignoreCase = true),
primaryText = "Настроить выход",
primaryBusyText = "Настройка...",
primaryEnabled = hostValid && sshPort != null && wgPort != null && userInput.isNotBlank() && passwordInput.isNotBlank(),
onPrimary = { onInstall(hostInput.trim(), sshPort ?: 22, userInput, passwordInput, wgPort ?: 51820, dnsInput) },
- secondaryText = "Отключить",
- secondaryBusyText = "Отключение...",
- onSecondary = onDisable
+ secondaryText = "Проверить",
+ secondaryBusyText = "Проверка...",
+ onSecondary = onCheck
)
+ OutlinedButton(onClick = onDisable, enabled = !busy, 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))
+ }
+ Text(if (disabling) "Отключение..." else "Отключить")
+ }
}
}
@@ -2053,18 +2531,24 @@ private fun ImportedWireGuardDialog(
onValidate: (String) -> Unit,
onEnable: (String) -> Unit,
onDisable: () -> Unit,
+ onServerCheck: () -> Unit,
onDelete: () -> Unit
) {
var configText by rememberSaveable(initialConfig) { mutableStateOf(initialConfig) }
val valid = configText.isNotBlank() && validateWireGuardConfigText(configText).isSuccess
- OutboundDialogFrame("Готовый WireGuard-файл", status, progressTitle, progress, onDismiss) {
+ OutboundDialogFrame("VPN/WARP-файл", status, progressTitle, progress, onDismiss) {
Text(
- "Можно выбрать обычный WireGuard-профиль, даже если он рассчитан на весь интернет. WDTT Plus применит его только к пользователям WDTT и не поменяет обычный интернет самого сервера.",
+ "Можно выбрать обычный WireGuard .conf от VPN-провайдера или WARP. Важно: WARP подходит только как WireGuard-конфиг с [Interface] и [Peer]; профиль warp-cli напрямую сюда не вставляется.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Text(
+ "WDTT Plus применит файл только к пользователям WDTT и не поменяет обычный интернет самого сервера.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
OutlinedButton(onClick = onPickFile, enabled = !busy, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {
- Text("Выбрать файл WireGuard")
+ Text("Выбрать VPN/WARP-файл")
}
OutlinedTextField(
value = configText,
@@ -2072,7 +2556,7 @@ private fun ImportedWireGuardDialog(
configText = it
onConfigChanged(it)
},
- label = { Text("Содержимое WireGuard-файла") },
+ label = { Text("Содержимое WireGuard/WARP .conf") },
minLines = 8,
maxLines = 14,
modifier = Modifier.fillMaxWidth(),
@@ -2085,16 +2569,29 @@ private fun ImportedWireGuardDialog(
)
DialogButtons(
busy = busy,
- primaryBusy = actionTitle.contains("Включаю WireGuard", ignoreCase = true),
+ primaryBusy = actionTitle.contains("Включаю VPN/WARP", ignoreCase = true),
secondaryBusy = false,
primaryText = "Включить",
primaryBusyText = "Включение...",
primaryEnabled = valid,
onPrimary = { onEnable(configText) },
- secondaryText = "Проверить",
+ secondaryText = "Проверить файл",
secondaryBusyText = "Проверка...",
onSecondary = { onValidate(configText) }
)
+ OutlinedButton(
+ onClick = onServerCheck,
+ enabled = !busy,
+ modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
+ shape = RoundedCornerShape(16.dp)
+ ) {
+ val checkingServer = actionTitle.contains("Проверяю установленный", ignoreCase = true)
+ if (checkingServer) {
+ CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
+ Spacer(Modifier.width(6.dp))
+ }
+ Text(if (checkingServer) "Проверка..." else "Проверить на сервере", fontWeight = FontWeight.SemiBold)
+ }
Row(
modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min),
horizontalArrangement = Arrangement.spacedBy(8.dp)
@@ -2610,7 +3107,7 @@ private fun outboundShellPrelude(): String = """
test_ip="${'$'}(curl -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"
+ echo "Проверка пути через внешний TCP-прокси успешна. IP через прокси: ${'$'}test_ip"
return 0
}
wdtt_write_mode() {
@@ -2629,6 +3126,11 @@ private fun outboundShellPrelude(): String = """
}
""".trimIndent()
+private fun outboundReadPrelude(): String = """
+ set -e
+ WDTT_WG_IFACE="wg-wdtt-exit"
+""".trimIndent()
+
private fun outboundStatusScript(): String = shellScript(
outboundShellPrelude(),
"""
@@ -2639,9 +3141,9 @@ private fun outboundStatusScript(): String = shellScript(
fi
case "${'$'}MODE" in
direct) MODE_LABEL="прямой выход";;
- external_proxy) MODE_LABEL="внешний прокси";;
- imported_wg) MODE_LABEL="готовый WireGuard-файл";;
- wireguard_vps) MODE_LABEL="другой сервер через WireGuard";;
+ external_proxy) MODE_LABEL="внешний TCP-прокси";;
+ imported_wg) MODE_LABEL="VPN/WARP-файл";;
+ wireguard_vps) MODE_LABEL="выход через другой сервер";;
*) MODE_LABEL="${'$'}MODE";;
esac
SERVER_IP="${'$'}(curl -4fsS --max-time 8 https://api.ipify.org 2>/dev/null || echo 'не удалось определить')"
@@ -2649,8 +3151,27 @@ private fun outboundStatusScript(): String = shellScript(
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
- if systemctl is-active wdtt-redsocks >/dev/null 2>&1; then echo "Внешний прокси для WDTT: включён"; else echo "Внешний прокси для WDTT: выключен"; fi
+ case "${'$'}MODE" in
+ direct)
+ echo "Проверочный выход WDTT: ${'$'}SERVER_IP (прямой выход)"
+ ;;
+ imported_wg|wireguard_vps)
+ WDTT_EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}WDTT_WG_IFACE" --max-time 12 https://api.ipify.org 2>/dev/null || true)"
+ if [ -n "${'$'}WDTT_EXIT_IP" ]; then
+ echo "Проверочный выход WDTT: ${'$'}WDTT_EXIT_IP"
+ else
+ echo "Проверочный выход WDTT: не удалось проверить через ${'$'}WDTT_WG_IFACE"
+ fi
+ ;;
+ external_proxy)
+ echo "Проверочный выход WDTT: через внешний TCP-прокси; точный IP смотрите при проверке/диагностике прокси"
+ ;;
+ *)
+ 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 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(скрыт)/'
@@ -2675,6 +3196,401 @@ private suspend fun readOutboundStatus(target: OutboundSshTarget): String = with
}
}
+private fun outboundProfileSaveScript(forms: OutboundProfileForms): String {
+ val kindName = ProxyKind.entries.firstOrNull { it.name == forms.externalProxyKindName }?.name.orEmpty()
+ fun port(value: String): String = value.filter(Char::isDigit).take(5)
+ fun line(name: String, value: String): String = "$name=$value"
+ fun b64Line(name: String, value: String): String = "$name=${encodeBase64Text(value)}"
+ val profileLines = listOf(
+ line("VERSION", "1"),
+ line("LOCAL_PROXY_PORT", port(forms.localProxyPort)),
+ b64Line("LOCAL_PROXY_LOGIN_B64", forms.localProxyLogin),
+ b64Line("LOCAL_PROXY_PASSWORD_B64", forms.localProxyPassword),
+ line("EXTERNAL_PROXY_KIND", kindName),
+ b64Line("EXTERNAL_PROXY_HOST_B64", forms.externalProxyHost),
+ line("EXTERNAL_PROXY_PORT", port(forms.externalProxyPort)),
+ b64Line("EXTERNAL_PROXY_LOGIN_B64", forms.externalProxyLogin),
+ b64Line("EXTERNAL_PROXY_PASSWORD_B64", forms.externalProxyPassword),
+ 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),
+ line("WG_VPS_PORT", port(forms.wireGuardExitPort)),
+ b64Line("WG_VPS_DNS_B64", forms.wireGuardExitDns),
+ b64Line("IMPORTED_WG_CONFIG_B64", forms.importedWireGuardConfig)
+ ).joinToString("\n")
+ val profileScript = """
+ PROFILE_FILE=/etc/wdtt/outbound-profile.env
+ TMP_FILE="${'$'}PROFILE_FILE.tmp"
+ cat >"${'$'}TMP_FILE" <<'WDTT_OUTBOUND_PROFILE'
+ """.trimIndent() + "\n" + profileLines + "\n" + """
+ WDTT_OUTBOUND_PROFILE
+ printf 'UPDATED_AT=%s\n' "$(date -Is)" >>"${'$'}TMP_FILE"
+ chmod 600 "${'$'}TMP_FILE"
+ mv "${'$'}TMP_FILE" "${'$'}PROFILE_FILE"
+ echo "Профиль полей выходного IP сохранён на сервере."
+ """.trimIndent()
+ return shellScript(outboundShellPrelude(), profileScript)
+}
+
+private suspend fun writeOutboundProfileToServer(
+ context: Context,
+ target: OutboundSshTarget,
+ forms: OutboundProfileForms
+): String = runRootScript(
+ context = context,
+ target = target,
+ script = outboundProfileSaveScript(forms),
+ timeout = 30000L
+)
+
+private suspend fun saveOutboundProfileMessage(
+ context: Context,
+ target: OutboundSshTarget,
+ forms: OutboundProfileForms,
+ successMessage: String
+): String = runCatching {
+ writeOutboundProfileToServer(context, target, forms)
+}.fold(
+ onSuccess = { successMessage },
+ onFailure = {
+ DeployManager.writeError("Outbound profile save failed: ${it.message}")
+ "Режим включён, но профиль полей не сохранился на сервере: ${friendlyDeployError(it, "сохранение")}."
+ }
+)
+
+private fun outboundSnapshotScript(): String = shellScript(
+ outboundReadPrelude(),
+ """
+ PROFILE_FILE=/etc/wdtt/outbound-profile.env
+ wdtt_profile_value() {
+ key="${'$'}1"
+ [ -f "${'$'}PROFILE_FILE" ] || return 0
+ grep -E "^${'$'}key=" "${'$'}PROFILE_FILE" 2>/dev/null | tail -n 1 | sed 's/^[^=]*=//'
+ }
+ wdtt_b64() {
+ command -v base64 >/dev/null 2>&1 || return 0
+ printf '%s' "${'$'}1" | base64 | tr -d '\n'
+ }
+ wdtt_file_b64() {
+ file="${'$'}1"
+ [ -f "${'$'}file" ] || return 0
+ command -v base64 >/dev/null 2>&1 || return 0
+ base64 "${'$'}file" 2>/dev/null | tr -d '\n'
+ }
+ wdtt_json_string() {
+ file="${'$'}1"
+ key="${'$'}2"
+ [ -f "${'$'}file" ] || return 0
+ grep -o "\"${'$'}key\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" "${'$'}file" 2>/dev/null | sed "s/.*\"${'$'}key\"[[:space:]]*:[[:space:]]*\"//;s/\".*//" | head -n 1
+ }
+ wdtt_json_number() {
+ file="${'$'}1"
+ key="${'$'}2"
+ [ -f "${'$'}file" ] || return 0
+ grep -o "\"${'$'}key\"[[:space:]]*:[[:space:]]*[0-9][0-9]*" "${'$'}file" 2>/dev/null | sed "s/.*\"${'$'}key\"[[:space:]]*:[[:space:]]*//" | head -n 1
+ }
+ wdtt_redsocks_value() {
+ key="${'$'}1"
+ [ -f /etc/wdtt/redsocks.conf ] || return 0
+ sed -n "s/^[[:space:]]*${'$'}key[[:space:]]*=[[:space:]]*//Ip" /etc/wdtt/redsocks.conf 2>/dev/null | head -n 1 | sed 's/[;[:space:]]*$//;s/^"//;s/"$//'
+ }
+ wdtt_3proxy_login() {
+ [ -f /etc/wdtt/3proxy.cfg ] || return 0
+ grep -E '^[[:space:]]*users[[:space:]]+' /etc/wdtt/3proxy.cfg 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*users[[:space:]]+([^:]+):CL:.*/\1/'
+ }
+ wdtt_3proxy_password() {
+ [ -f /etc/wdtt/3proxy.cfg ] || return 0
+ grep -E '^[[:space:]]*users[[:space:]]+' /etc/wdtt/3proxy.cfg 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*users[[:space:]]+[^:]+:CL:(.*)$/\1/'
+ }
+ wdtt_3proxy_port() {
+ [ -f /etc/wdtt/3proxy.cfg ] || return 0
+ grep -E '^[[:space:]]*socks[[:space:]].*-p[0-9]+' /etc/wdtt/3proxy.cfg 2>/dev/null | head -n 1 | sed -E 's/.*-p([0-9]+).*/\1/'
+ }
+
+ MODE="${'$'}(wdtt_json_string /etc/wdtt/outbound.json outboundMode)"
+ [ -n "${'$'}MODE" ] || MODE="direct"
+ DETAIL="${'$'}(wdtt_json_string /etc/wdtt/outbound.json detail)"
+ UPDATED_AT="${'$'}(wdtt_json_string /etc/wdtt/outbound.json updatedAt)"
+ HAS_PROFILE=0
+ [ -f "${'$'}PROFILE_FILE" ] && HAS_PROFILE=1
+ PROFILE_UPDATED_AT="${'$'}(wdtt_profile_value UPDATED_AT)"
+ [ -n "${'$'}UPDATED_AT" ] || UPDATED_AT="${'$'}PROFILE_UPDATED_AT"
+
+ LOCAL_PRESENT=0
+ if [ -f /etc/wdtt/local-proxy.json ] || [ -f /etc/wdtt/3proxy.cfg ]; then
+ 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_PRESENT=1
+ else
+ LOCAL_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
+ 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
+ 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")"
+ fi
+
+ DETAIL_KIND=""
+ DETAIL_HOST=""
+ DETAIL_PORT=""
+ case "${'$'}DETAIL" in
+ socks5://*|http://*)
+ DETAIL_KIND="${'$'}{DETAIL%%://*}"
+ DETAIL_REST="${'$'}{DETAIL#*://}"
+ DETAIL_HOST="${'$'}{DETAIL_REST%:*}"
+ DETAIL_PORT="${'$'}{DETAIL_REST##*:}"
+ ;;
+ esac
+ REDSOCKS_TYPE="${'$'}(wdtt_redsocks_value type)"
+ REDSOCKS_KIND=""
+ case "${'$'}REDSOCKS_TYPE" in
+ socks5) REDSOCKS_KIND="Socks5";;
+ http|http-connect) REDSOCKS_KIND="Http";;
+ esac
+ EXTERNAL_KIND="${'$'}(wdtt_profile_value EXTERNAL_PROXY_KIND)"
+ if [ -z "${'$'}EXTERNAL_KIND" ]; then
+ 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
+ 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)")"
+ EXTERNAL_PRESENT=0
+ if [ -f /etc/wdtt/redsocks.conf ] || [ "${'$'}MODE" = "external_proxy" ] || [ -n "${'$'}EXTERNAL_HOST_B64" ] || [ -n "${'$'}EXTERNAL_PORT" ]; 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_PRESENT=1
+ else
+ EXTERNAL_ACTIVE=0
+ fi
+
+ WG_CONF=""
+ [ -f /etc/wireguard/wg-wdtt-exit.conf ] && WG_CONF=/etc/wireguard/wg-wdtt-exit.conf
+ [ -z "${'$'}WG_CONF" ] && [ -f /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf ] && WG_CONF=/etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf
+ 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_PRESENT=1
+ else
+ WG_ACTIVE=0
+ fi
+ WG_ENDPOINT=""
+ WG_DNS=""
+ if [ -n "${'$'}WG_CONF" ]; then
+ WG_ENDPOINT="${'$'}(sed -n 's/^[[:space:]]*Endpoint[[:space:]]*=[[:space:]]*//Ip' "${'$'}WG_CONF" 2>/dev/null | head -n 1 | tr -d ' ')"
+ WG_DNS="${'$'}(sed -n 's/^[[:space:]]*DNS[[:space:]]*=[[:space:]]*//Ip' "${'$'}WG_CONF" 2>/dev/null | head -n 1 | tr -d ' ')"
+ fi
+ WG_ENDPOINT_HOST=""
+ WG_ENDPOINT_PORT=""
+ if [ -n "${'$'}WG_ENDPOINT" ]; then
+ WG_ENDPOINT_HOST="${'$'}{WG_ENDPOINT%:*}"
+ WG_ENDPOINT_PORT="${'$'}{WG_ENDPOINT##*:}"
+ 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")"
+ 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
+ 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
+ IMPORTED_WG_CONFIG_B64="${'$'}(wdtt_file_b64 "${'$'}WG_CONF")"
+ fi
+ [ -n "${'$'}IMPORTED_WG_CONFIG_B64" ] && WG_PRESENT=1
+
+ printf 'WDTT_OUTBOUND_MODE=%s\n' "${'$'}MODE"
+ printf 'WDTT_OUTBOUND_DETAIL_B64=%s\n' "$(wdtt_b64 "${'$'}DETAIL")"
+ printf 'WDTT_OUTBOUND_UPDATED_AT=%s\n' "${'$'}UPDATED_AT"
+ 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_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_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"
+ printf 'WDTT_EXTERNAL_PROXY_LOGIN_B64=%s\n' "${'$'}EXTERNAL_LOGIN_B64"
+ 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_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"
+ printf 'WDTT_WG_VPS_PASSWORD_B64=%s\n' "${'$'}WG_VPS_PASSWORD_B64"
+ printf 'WDTT_WG_VPS_PORT=%s\n' "${'$'}WG_VPS_PORT"
+ printf 'WDTT_WG_VPS_DNS_B64=%s\n' "${'$'}WG_VPS_DNS_B64"
+ printf 'WDTT_IMPORTED_WG_CONFIG_B64=%s\n' "${'$'}IMPORTED_WG_CONFIG_B64"
+ """
+)
+
+private suspend fun readOutboundServerSnapshot(
+ context: Context,
+ target: OutboundSshTarget
+): OutboundServerSnapshot {
+ DeployManager.updateProgress(0.25f, "Подключаюсь к серверу и ищу профиль выходного IP...")
+ val output = runRootScript(
+ context = context,
+ target = target,
+ script = outboundSnapshotScript(),
+ timeout = 30000L
+ )
+ DeployManager.updateProgress(1f, "Настройки выходного IP прочитаны.")
+ return parseOutboundServerSnapshot(output)
+}
+
+private fun parseOutboundServerSnapshot(output: String): OutboundServerSnapshot {
+ fun value(name: String): String = markerValue(output, name).orEmpty()
+ fun decoded(name: String): String {
+ val raw = value(name)
+ if (raw.isBlank()) return ""
+ return runCatching { decodeBase64Text(raw) }.getOrDefault("")
+ }
+ fun flag(name: String): Boolean = value(name) == "1"
+ return OutboundServerSnapshot(
+ mode = value("WDTT_OUTBOUND_MODE").ifBlank { "direct" },
+ detail = decoded("WDTT_OUTBOUND_DETAIL_B64"),
+ updatedAt = value("WDTT_OUTBOUND_UPDATED_AT"),
+ hasProfile = flag("WDTT_HAS_PROFILE"),
+ localProxyPresent = flag("WDTT_LOCAL_PROXY_PRESENT"),
+ localProxyActive = flag("WDTT_LOCAL_PROXY_ACTIVE"),
+ localProxyPort = value("WDTT_LOCAL_PROXY_PORT"),
+ localProxyLogin = decoded("WDTT_LOCAL_PROXY_LOGIN_B64"),
+ localProxyPassword = decoded("WDTT_LOCAL_PROXY_PASSWORD_B64"),
+ externalProxyPresent = flag("WDTT_EXTERNAL_PROXY_PRESENT"),
+ externalProxyActive = flag("WDTT_EXTERNAL_PROXY_ACTIVE"),
+ externalProxyKindName = value("WDTT_EXTERNAL_PROXY_KIND_NAME").takeIf { name -> ProxyKind.entries.any { it.name == name } }.orEmpty(),
+ externalProxyHost = decoded("WDTT_EXTERNAL_PROXY_HOST_B64"),
+ externalProxyPort = value("WDTT_EXTERNAL_PROXY_PORT"),
+ externalProxyLogin = decoded("WDTT_EXTERNAL_PROXY_LOGIN_B64"),
+ externalProxyPassword = decoded("WDTT_EXTERNAL_PROXY_PASSWORD_B64"),
+ wireGuardPresent = flag("WDTT_WG_PRESENT"),
+ wireGuardActive = flag("WDTT_WG_ACTIVE"),
+ wireGuardExitHost = decoded("WDTT_WG_VPS_HOST_B64"),
+ wireGuardExitSshPort = value("WDTT_WG_VPS_SSH_PORT"),
+ wireGuardExitUser = decoded("WDTT_WG_VPS_USER_B64"),
+ wireGuardExitPassword = decoded("WDTT_WG_VPS_PASSWORD_B64"),
+ wireGuardExitPort = value("WDTT_WG_VPS_PORT"),
+ wireGuardExitDns = decoded("WDTT_WG_VPS_DNS_B64"),
+ importedWireGuardConfig = decoded("WDTT_IMPORTED_WG_CONFIG_B64")
+ )
+}
+
+private fun outboundRestoreSummary(snapshot: OutboundServerSnapshot): String {
+ val parts = mutableListOf()
+ parts += "Поля выходного IP прочитаны с сервера."
+ parts += "Активный режим: ${snapshot.modeLabel}."
+ if (snapshot.hasProfile) parts += "Сохранённый профиль найден."
+ if (snapshot.localProxyPresent) {
+ parts += if (snapshot.localProxyActive) "Прокси VPS найден и запущен." else "Прокси VPS найден, служба не запущена."
+ }
+ if (snapshot.externalProxyPresent) {
+ parts += if (snapshot.externalProxyActive) "Внешний TCP-прокси включён." else "Поля внешнего TCP-прокси заполнены."
+ }
+ if (snapshot.wireGuardPresent) {
+ parts += if (snapshot.wireGuardActive) "WireGuard-выход найден и запущен." else "Поля WireGuard-выхода заполнены."
+ }
+ if (snapshot.localProxyPresent && snapshot.localProxyPassword.isBlank()) {
+ parts += "Пароль прокси не найден в старом серверном конфиге; введите его вручную."
+ }
+ if (snapshot.mode == "wireguard_vps" && snapshot.wireGuardExitPassword.isBlank()) {
+ parts += "SSH-пароль второго сервера можно восстановить только из сохранённого профиля; если его нет, введите пароль вручную."
+ }
+ return parts.joinToString(" ")
+}
+
+private suspend fun checkWireGuardExit(
+ target: OutboundSshTarget,
+ expectedMode: String
+): String = withContext(Dispatchers.IO) {
+ var session: Session? = null
+ try {
+ DeployManager.updateProgress(0.25f, "Подключаюсь к серверу и проверяю WireGuard-выход...")
+ session = createSSHSession(target.host, target.user, target.pass, target.port)
+ val ssh = SSHClient(session, target.pass)
+ val expectedLabel = when (expectedMode) {
+ "wireguard_vps" -> "выход через другой сервер"
+ "imported_wg" -> "VPN/WARP-файл"
+ else -> expectedMode
+ }
+ val script = shellScript(
+ outboundShellPrelude(),
+ """
+ MODE="${'$'}(grep -o '"outboundMode"[[:space:]]*:[[:space:]]*"[^"]*"' /etc/wdtt/outbound.json 2>/dev/null | sed 's/.*"outboundMode"[[:space:]]*:[[:space:]]*"//;s/".*//' | head -n 1)"
+ [ -n "${'$'}MODE" ] || MODE="direct"
+ case "${'$'}MODE" in
+ imported_wg) MODE_LABEL="VPN/WARP-файл";;
+ wireguard_vps) MODE_LABEL="выход через другой сервер";;
+ external_proxy) MODE_LABEL="внешний TCP-прокси";;
+ direct) MODE_LABEL="прямой выход";;
+ *) MODE_LABEL="${'$'}MODE";;
+ esac
+ echo "Активный режим WDTT: ${'$'}MODE_LABEL"
+ if [ "${'$'}MODE" != ${shellQuote(expectedMode)} ]; then
+ echo "Предупреждение: сейчас включён не режим «$expectedLabel»."
+ fi
+ command -v wg >/dev/null 2>&1 || { echo WDTT_ERROR=wireguard_tools_required; exit 2; }
+ wg show "${'$'}WDTT_WG_IFACE" >/dev/null 2>&1 || { echo WDTT_ERROR=wireguard_not_active; exit 3; }
+ echo "WireGuard ${'$'}WDTT_WG_IFACE запущен."
+ EXIT_IP="${'$'}(curl -4fsS --interface "${'$'}WDTT_WG_IFACE" --max-time 12 https://api.ipify.org 2>/dev/null || true)"
+ if [ -n "${'$'}EXIT_IP" ]; then
+ echo "Проверка успешна: WDTT-пользователи выходят через WireGuard. Проверочный IP: ${'$'}EXIT_IP"
+ else
+ echo WDTT_ERROR=wireguard_exit_check_failed
+ exit 3
+ fi
+ wg show "${'$'}WDTT_WG_IFACE" | sed -E 's/(private key: ).*/\1(скрыт)/' || true
+ """
+ )
+ DeployManager.updateProgress(0.70f, "Проверяю внешний IP через WireGuard-интерфейс...")
+ val output = ssh.exec(rootCommand(script), timeout = 30000L).trim()
+ markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(it) }
+ DeployManager.updateProgress(1f, "WireGuard-выход проверен.")
+ output
+ } finally {
+ try { session?.disconnect() } catch (_: Exception) {}
+ }
+}
+
private suspend fun readOutboundDiagnostics(target: OutboundSshTarget): String = withContext(Dispatchers.IO) {
var session: Session? = null
try {
@@ -2710,7 +3626,7 @@ private suspend fun readOutboundDiagnostics(target: OutboundSshTarget): String =
echo "Правил перенаправления WDTT через прокси или WireGuard сейчас нет."
fi
echo
- echo "Служба внешнего прокси WDTT:"
+ echo "Служба внешнего TCP-прокси WDTT:"
systemctl status wdtt-redsocks --no-pager -l 2>/dev/null | sed -n '1,12p' || echo "Служба wdtt-redsocks не найдена или systemctl недоступен."
echo
echo "Локальный порт redsocks:"
@@ -2749,12 +3665,12 @@ private suspend fun disableOutboundExit(target: OutboundSshTarget): String = wit
val script = shellScript(
outboundShellPrelude(),
"""
- echo "WDTT_PROGRESS|0.25|Останавливаю внешний прокси и WireGuard-выход, если они включены..."
+ 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 "Внешний прокси или WireGuard-выход отключён. WDTT-пользователи снова идут напрямую через текущий сервер."
+ echo "Внешний TCP-прокси или WireGuard-выход отключён. WDTT-пользователи снова идут напрямую через текущий сервер."
"""
)
ssh.exec(rootCommand(script), timeout = 30000L).trim()
@@ -2904,11 +3820,13 @@ private suspend fun installLocalProxy(
"socks5Port": ${'$'}PROXY_PORT,
"httpPort": ${'$'}HTTP_PORT,
"webPort": ${'$'}ADMIN_PORT,
- "login": "${'$'}PROXY_LOGIN"
+ "login": "${'$'}PROXY_LOGIN",
+ "password": "${'$'}PROXY_PASSWORD"
}
EOF
+ chmod 600 /etc/wdtt/local-proxy.json
wdtt_progress 1.0 "Прокси установлен и проверен."
- echo "Прокси на сервере включён."
+ echo "Прокси VPS включён."
echo "SOCKS5-прокси: socks5://${'$'}PROXY_LOGIN:********@${'$'}SERVER_IP:${'$'}PROXY_PORT"
echo "HTTP-прокси: http://${'$'}PROXY_LOGIN:********@${'$'}SERVER_IP:${'$'}HTTP_PORT"
echo "Веб-страница 3proxy: http://${'$'}SERVER_IP:${'$'}ADMIN_PORT/"
@@ -2957,7 +3875,7 @@ private suspend fun stopLocalProxy(target: OutboundSshTarget): String = withCont
exit 3
fi
echo "WDTT_PROGRESS|1.0|Прокси остановлен."
- echo "Прокси на этом сервере остановлен. Настройки сохранены, его можно снова включить кнопкой «Установить»."
+ echo "Прокси VPS остановлен. Настройки сохранены, его можно снова включить кнопкой «Установить»."
""".trimIndent()
ssh.exec(rootCommand(script), timeout = 20000L).trim()
} finally {
@@ -2982,7 +3900,7 @@ private suspend fun removeLocalProxy(target: OutboundSshTarget): String = withCo
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 "Прокси на этом сервере удалён: служба, настройки и правила доступа к портам очищены."
+ echo "Прокси VPS удалён: служба, настройки и правила доступа к портам очищены."
"""
)
ssh.exec(rootCommand(script), timeout = 30000L).trim()
@@ -3010,7 +3928,7 @@ private suspend fun checkExternalProxy(
PROXY_URI=${shellQuote(proxyUri)}
IP="${'$'}(curl --proxy "${'$'}PROXY_URI" -4fsS --max-time 15 https://api.ipify.org 2>/dev/null || true)"
[ -n "${'$'}IP" ] || { echo WDTT_ERROR=external_proxy_check_failed; exit 3; }
- echo "WDTT_PROGRESS|1.0|Внешний прокси отвечает."
+ echo "WDTT_PROGRESS|1.0|Внешний TCP-прокси отвечает."
echo "Проверка успешна: ${kind.label} отвечает, сервер смог открыть проверочный сайт через него. IP через прокси: ${'$'}IP"
""".trimIndent()
return runRootScript(context, target, script, timeout = 30000L)
@@ -3036,7 +3954,7 @@ private suspend fun enableExternalProxy(
PROXY_LOGIN=${shellQuote(login)}
PROXY_PASSWORD=${shellQuote(proxyPassword)}
wdtt_progress() { echo "WDTT_PROGRESS|${'$'}1|${'$'}2"; }
- wdtt_progress 0.12 "Готовлю компонент перенаправления через внешний прокси..."
+ wdtt_progress 0.12 "Готовлю компонент перенаправления через внешний TCP-прокси..."
wdtt_install_redsocks_tools || true
REDSOCKS_BIN="${'$'}(command -v redsocks || true)"
[ -n "${'$'}REDSOCKS_BIN" ] || { echo WDTT_ERROR=redsocks_not_installed; exit 2; }
@@ -3089,24 +4007,24 @@ private suspend fun enableExternalProxy(
WantedBy=multi-user.target
EOF
systemctl daemon-reload
- wdtt_progress 0.84 "Запускаю службу внешнего прокси..."
+ wdtt_progress 0.84 "Запускаю службу внешнего TCP-прокси..."
systemctl enable --now wdtt-redsocks >/dev/null
systemctl is-active --quiet wdtt-redsocks || { echo WDTT_ERROR=external_proxy_service_inactive; journalctl -u wdtt-redsocks -n 30 --no-pager 2>/dev/null || true; exit 3; }
- wdtt_progress 0.92 "Направляю обычные подключения WDTT через внешний прокси..."
+ 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
- wdtt_progress 0.96 "Проверяю путь WDTT через внешний прокси..."
+ wdtt_progress 0.96 "Проверяю путь WDTT через внешний TCP-прокси..."
if ! wdtt_test_redsocks_path "${'$'}PROXY_IP"; then
wdtt_clear_external_out
wdtt_write_mode "direct" "rollback after external proxy error"
exit 3
fi
wdtt_write_mode "external_proxy" "${'$'}PROXY_KIND://${'$'}PROXY_HOST:${'$'}PROXY_PORT"
- wdtt_progress 1.0 "Внешний прокси включён."
- echo "Внешний прокси включён для обычных подключений WDTT-пользователей. Голосовой UDP-трафик через него не перенаправляется."
+ wdtt_progress 1.0 "Внешний TCP-прокси включён."
+ echo "Внешний TCP-прокси включён для обычных TCP-подключений WDTT-пользователей. UDP, QUIC и голосовой трафик через него не перенаправляются."
echo "Подсеть клиентов WDTT: ${'$'}WDTT_SUBNET"
echo "Прокси: ${'$'}PROXY_KIND://${'$'}PROXY_HOST:${'$'}PROXY_PORT"
"""
@@ -3205,13 +4123,13 @@ private suspend fun enableImportedWireGuardExit(
"""
echo "WDTT_PROGRESS|0.18|Готовлю инструменты WireGuard на текущем сервере..."
wdtt_install_wireguard_tools || true
- echo "WDTT_PROGRESS|0.45|Сохраняю выбранный WireGuard-файл без опасных команд..."
+ echo "WDTT_PROGRESS|0.45|Сохраняю выбранный VPN/WARP-файл без опасных команд..."
mkdir -p /etc/wdtt-plus/wg-exit /etc/wireguard
install -m 600 /tmp/wdtt-imported-wg.conf /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf
install -m 600 /tmp/wdtt-imported-wg.conf /etc/wireguard/wg-wdtt-exit.conf
rm -f /tmp/wdtt-imported-wg.conf
""",
- wireGuardPolicyScript("imported_wg", "готовый WireGuard-файл")
+ wireGuardPolicyScript("imported_wg", "VPN/WARP-файл")
)
val output = ssh.exec(rootCommand(script), timeout = CMD_TIMEOUT)
markerValue(output, "WDTT_ERROR")?.let { throw IllegalStateException(it) }
@@ -3232,12 +4150,12 @@ private suspend fun deleteImportedWireGuardExit(target: OutboundSshTarget): Stri
"""
echo "WDTT_PROGRESS|0.25|Отключаю WireGuard-выход, если он запущен..."
wdtt_clear_external_out
- echo "WDTT_PROGRESS|0.60|Удаляю сохранённый WireGuard-файл..."
+ echo "WDTT_PROGRESS|0.60|Удаляю сохранённый VPN/WARP-файл..."
rm -f /etc/wdtt-plus/wg-exit/wg-wdtt-exit.conf /etc/wireguard/wg-wdtt-exit.conf
echo "WDTT_PROGRESS|0.85|Возвращаю прямой выход через текущий сервер..."
wdtt_write_mode "direct" "прямой выход"
- echo "WDTT_PROGRESS|1.0|WireGuard-файл удалён."
- echo "Готовый WireGuard-файл удалён, выход WDTT возвращён напрямую через текущий сервер."
+ echo "WDTT_PROGRESS|1.0|VPN/WARP-файл удалён."
+ echo "VPN/WARP-файл удалён, выход WDTT возвращён напрямую через текущий сервер."
"""
)
ssh.exec(rootCommand(script), timeout = 30000L).trim()
@@ -3489,19 +4407,23 @@ private fun friendlyDeployError(error: Throwable, operation: String): String {
"local_proxy_service_still_active" in lower ->
"приложение отправило команду остановки, но служба wdtt-3proxy всё ещё запущена. Проверьте права пользователя SSH или остановите службу вручную."
"external_proxy_check_failed" in lower ->
- "внешний прокси не ответил на проверку. Проверьте адрес, порт, логин и пароль."
+ "внешний TCP-прокси не ответил на проверку. Проверьте адрес, порт, логин и пароль."
"external_proxy_service_inactive" in lower ->
- "служба перенаправления через внешний прокси не запустилась. Приложение откатило правила и вернуло прямой выход, чтобы интернет через VPN не остался сломанным."
+ "служба перенаправления через внешний TCP-прокси не запустилась. Приложение откатило правила и вернуло прямой выход, чтобы интернет через VPN не остался сломанным."
"external_proxy_apply_failed" in lower ->
- withTail("внешний прокси отвечает напрямую, но путь WDTT через redsocks не заработал. Приложение откатило правила и вернуло прямой выход, чтобы VPN-интернет не пропал.")
+ withTail("внешний TCP-прокси отвечает напрямую, но путь WDTT через redsocks не заработал. Приложение откатило правила и вернуло прямой выход, чтобы VPN-интернет не пропал.")
"redsocks_not_installed" in lower ->
- "не удалось установить компонент перенаправления через внешний прокси. Проверьте пакетный менеджер и доступ сервера к интернету."
+ "не удалось установить компонент перенаправления через внешний TCP-прокси. Проверьте пакетный менеджер и доступ сервера к интернету."
"iptables_required" in lower ->
"на сервере не найдены правила межсетевого экрана iptables, без них этот режим не включить."
"wdtt_iface_not_found" in lower ->
"на сервере не найден интерфейс WDTT. Сначала запустите сервер WDTT Plus и проверьте подключение."
"wireguard_tools_required" in lower ->
"на сервере не найдены инструменты WireGuard, без них этот режим не включить."
+ "wireguard_not_active" in lower ->
+ "WireGuard-выход wdtt сейчас не запущен. Включите режим «Другой сервер» или «VPN/WARP-файл», затем повторите проверку."
+ "wireguard_exit_check_failed" in lower ->
+ "WireGuard-интерфейс запущен, но проверочный сайт через него не открылся. Проверьте конфиг, endpoint, NAT и доступ второго сервера/VPN к интернету."
"foreign_ext_iface_not_found" in lower ->
"на другом сервере не удалось определить основной сетевой интерфейс."
"root privileges required" in lower ||
@@ -3828,6 +4750,306 @@ private fun parsePortsTriple(value: String): Triple {
return Triple(parts[0] ?: 56000, parts[1] ?: 56001, parts[2] ?: 9000)
}
+private fun parsePortsTripleOrNull(value: String): Triple? {
+ val parts = value.split(",").map { it.trim().toIntOrNull() }
+ if (parts.size != 3 || parts.any { it == null || it !in 1..65535 }) return null
+ return Triple(parts[0] ?: return null, parts[1] ?: return null, parts[2] ?: return null)
+}
+
+private fun Triple.asPortsSpec(): String = "$first,$second,$third"
+
+private fun buildOwnerProfile(
+ vkHashes: String,
+ secondaryVkHash: String,
+ workersPerHash: Int,
+ protocol: String,
+ listenPort: Int,
+ sni: String,
+ noDns: Boolean,
+ dtlsPort: Int,
+ wgPort: Int
+): ServerAdminProfileInfo {
+ val safeListenPort = listenPort.coerceIn(1, 65535)
+ val ports = Triple(
+ dtlsPort.coerceIn(1, 65535),
+ wgPort.coerceIn(1, 65535),
+ safeListenPort
+ )
+ return ServerAdminProfileInfo(
+ vkHashes = vkHashes.trim(),
+ secondaryVkHash = secondaryVkHash.trim(),
+ workersPerHash = workersPerHash.coerceIn(1, 128),
+ protocol = protocol.trim().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
+ listenPort = safeListenPort,
+ sni = sni.trim(),
+ noDns = noDns,
+ ports = ports.asPortsSpec()
+ )
+}
+
+private fun parseOwnerProfileFromDb(json: JSONObject?, defaultPorts: String): ServerAdminProfileInfo {
+ val fallbackPorts = parsePortsTripleOrNull(defaultPorts) ?: Triple(56000, 56001, 9000)
+ val ports = parsePortsTripleOrNull(json?.optString("ports", defaultPorts).orEmpty())
+ ?: fallbackPorts
+ val listenPort = json?.optInt("listen_port", 0)
+ ?.takeIf { it in 1..65535 }
+ ?: ports.third
+ val deviceIds = buildList {
+ val raw = json?.optJSONArray("device_ids") ?: return@buildList
+ for (i in 0 until raw.length()) {
+ raw.optString(i).trim().takeIf { it.isNotBlank() }?.let(::add)
+ }
+ }
+ return ServerAdminProfileInfo(
+ vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(),
+ secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(),
+ workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128),
+ protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
+ listenPort = listenPort,
+ sni = json?.optString("sni", "").orEmpty().trim(),
+ noDns = json?.optBoolean("no_dns", false) ?: false,
+ ports = Triple(ports.first, ports.second, listenPort).asPortsSpec(),
+ deviceIds = deviceIds,
+ updatedAt = json?.optLong("updated_at", 0L) ?: 0L
+ )
+}
+
+private fun ServerAdminProfileInfo.effectivePorts(fallback: Triple): Triple {
+ val parsed = parsePortsTripleOrNull(ports) ?: fallback
+ val safeListenPort = listenPort.takeIf { it in 1..65535 } ?: parsed.third
+ return Triple(parsed.first, parsed.second, safeListenPort)
+}
+
+private data class OwnerProfileComparable(
+ val vkHashes: String,
+ val secondaryVkHash: String,
+ val workersPerHash: Int,
+ val protocol: String,
+ val listenPort: Int,
+ val sni: String,
+ val noDns: Boolean,
+ val ports: String
+)
+
+private fun ServerAdminProfileInfo.comparableOwnerProfile(): OwnerProfileComparable {
+ val ports = effectivePorts(Triple(56000, 56001, 9000))
+ return OwnerProfileComparable(
+ vkHashes = vkHashes.trim(),
+ secondaryVkHash = secondaryVkHash.trim(),
+ workersPerHash = workersPerHash.coerceIn(1, 128),
+ protocol = protocol.trim().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
+ listenPort = ports.third,
+ sni = sni.trim(),
+ noDns = noDns,
+ ports = ports.asPortsSpec()
+ )
+}
+
+private fun ownerProfilesDiffer(server: ServerAdminProfileInfo, local: ServerAdminProfileInfo): Boolean =
+ server.comparableOwnerProfile() != local.comparableOwnerProfile()
+
+private fun ownerProfileDiffLines(server: ServerAdminProfileInfo, local: ServerAdminProfileInfo): List {
+ val serverComparable = server.comparableOwnerProfile()
+ val localComparable = local.comparableOwnerProfile()
+ val lines = mutableListOf()
+ if (serverComparable.vkHashes != localComparable.vkHashes) {
+ lines += "VK-хеши: сервер — ${secretPresenceLabel(serverComparable.vkHashes)}, приложение — ${secretPresenceLabel(localComparable.vkHashes)}"
+ }
+ if (serverComparable.secondaryVkHash != localComparable.secondaryVkHash) {
+ lines += "Резервный VK-хеш: сервер — ${secretPresenceLabel(serverComparable.secondaryVkHash)}, приложение — ${secretPresenceLabel(localComparable.secondaryVkHash)}"
+ }
+ if (serverComparable.workersPerHash != localComparable.workersPerHash) {
+ lines += "Потоки на хеш: сервер — ${serverComparable.workersPerHash}, приложение — ${localComparable.workersPerHash}"
+ }
+ if (serverComparable.protocol != localComparable.protocol) {
+ lines += "Протокол: сервер — ${serverComparable.protocol}, приложение — ${localComparable.protocol}"
+ }
+ if (serverComparable.listenPort != localComparable.listenPort) {
+ lines += "Локальный порт: сервер — ${serverComparable.listenPort}, приложение — ${localComparable.listenPort}"
+ }
+ if (serverComparable.ports != localComparable.ports) {
+ lines += "Порты ссылки: сервер — ${serverComparable.ports}, приложение — ${localComparable.ports}"
+ }
+ if (serverComparable.sni != localComparable.sni) {
+ lines += "SNI: сервер — ${serverComparable.sni.ifBlank { "не задан" }}, приложение — ${localComparable.sni.ifBlank { "не задан" }}"
+ }
+ if (serverComparable.noDns != localComparable.noDns) {
+ lines += "No DNS: сервер — ${if (serverComparable.noDns) "включено" else "выключено"}, приложение — ${if (localComparable.noDns) "включено" else "выключено"}"
+ }
+ return lines.ifEmpty { listOf("Отличия есть только в служебных данных профиля.") }
+}
+
+private fun existingConnectionDiffLines(
+ connection: ExistingServerConnection,
+ localPeer: String,
+ localConnectionPassword: String,
+ localAdminId: String,
+ localBotToken: String,
+ localDns1: String,
+ localDns2: String,
+ localProfile: ServerAdminProfileInfo
+): List = buildList {
+ if (!connection.host.equals(localPeer.trim(), ignoreCase = true)) {
+ add("Адрес подключения: локальное значение будет заменено адресом сервера ${connection.host}")
+ }
+ if (connection.password != localConnectionPassword) {
+ add("Пароль VPN-подключения будет заменён главным паролем владельца с сервера")
+ }
+ if (connection.adminId != localAdminId.trim()) {
+ add("Telegram Admin ID отличается")
+ }
+ if (connection.botToken != localBotToken.trim()) {
+ add("Telegram Bot Token отличается")
+ }
+ if (normalizeDnsValues(connection.dns1, connection.dns2) != normalizeDnsValues(localDns1, localDns2)) {
+ add("DNS: сервер — ${normalizeDnsValues(connection.dns1, connection.dns2)}, приложение — ${normalizeDnsValues(localDns1, localDns2)}")
+ }
+ if (connection.adminProfile.hasSavedFields && ownerProfilesDiffer(connection.adminProfile, localProfile)) {
+ addAll(ownerProfileDiffLines(connection.adminProfile, localProfile))
+ }
+}
+
+private fun normalizeDnsValues(first: String, second: String = ""): String =
+ listOf(first, second)
+ .flatMap { it.split(',') }
+ .map { it.trim() }
+ .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
+}
+
+private suspend fun compareDeployWithServer(
+ context: Context,
+ request: DeployRequest,
+ localOwnerProfile: ServerAdminProfileInfo,
+ localOutboundProfile: OutboundProfileForms,
+ inspectDatabase: Boolean
+): DeployServerComparison {
+ val overwriteLines = mutableListOf()
+ val notes = mutableListOf()
+ val errors = mutableListOf()
+
+ if (inspectDatabase) {
+ runCatching {
+ withContext(Dispatchers.IO) {
+ var session: Session? = null
+ try {
+ session = createSSHSession(request.host, request.user, request.pass, request.sshPort)
+ val ssh = SSHClient(session, request.pass)
+ val raw = readRemotePasswordsJson(ssh)
+ ?: throw IllegalStateException("на сервере не найдена база доступа")
+ val db = JSONObject(raw)
+ validatePasswordsDbStructure(db)
+
+ if (db.optString("main_password") != request.mainPass) {
+ overwriteLines += "Главный пароль владельца"
+ }
+ if (request.adminId.isNotBlank() && db.optString("admin_id") != request.adminId) {
+ overwriteLines += "Telegram Admin ID"
+ }
+ if (request.botToken.isNotBlank() && db.optString("bot_token") != request.botToken) {
+ overwriteLines += "Telegram Bot Token"
+ }
+ val serverDns = normalizeDnsValues(db.optString("dns"))
+ val localDns = normalizeDnsValues(
+ request.dns1.ifBlank { "1.1.1.1" },
+ request.dns2
+ )
+ if (serverDns != localDns) {
+ overwriteLines += "DNS: сервер — ${serverDns.ifBlank { "не задан" }}, приложение — $localDns"
+ }
+
+ val defaultPorts = db.optString("default_ports").ifBlank { "56000,56001,9000" }
+ val serverProfile = parseOwnerProfileFromDb(db.optJSONObject("admin_profile"), defaultPorts)
+ if (serverProfile.hasSavedFields && ownerProfilesDiffer(serverProfile, localOwnerProfile)) {
+ overwriteLines += "Профиль владельца («Туннель» и порты)"
+ overwriteLines += ownerProfileDiffLines(serverProfile, localOwnerProfile).map { " $it" }
+ } else if (!serverProfile.hasSavedFields) {
+ notes += "На сервере ещё нет профиля владельца; установка создаст его из текущих полей приложения."
+ }
+ } finally {
+ try { session?.disconnect() } catch (_: Exception) {}
+ }
+ }
+ }.onFailure {
+ errors += friendlyDeployError(it, "сверка профиля сервера")
+ }
+ }
+
+ runCatching {
+ val target = OutboundSshTarget(
+ host = request.host,
+ user = request.user.ifBlank { "root" },
+ pass = request.pass,
+ port = request.sshPort
+ )
+ val output = runRootScript(
+ context = context,
+ target = target,
+ script = outboundSnapshotScript(),
+ timeout = 30000L
+ )
+ val snapshot = parseOutboundServerSnapshot(output)
+ if (snapshot.hasProfile && outboundProfilesDiffer(snapshot, localOutboundProfile)) {
+ overwriteLines += "Сохранённые поля «Выходной IP и прокси»"
+ } else if (!snapshot.hasProfile) {
+ notes += "На сервере нет профиля полей выходного IP; установка создаст его из текущих полей приложения."
+ }
+ }.onFailure {
+ errors += friendlyDeployError(it, "сверка выходного IP")
+ }
+
+ return DeployServerComparison(
+ overwriteLines = overwriteLines.distinct(),
+ notes = notes.distinct(),
+ checkError = errors.takeIf { it.isNotEmpty() }?.joinToString(" ")
+ )
+}
+
+private fun secretPresenceLabel(value: String): String {
+ val count = value.split(',', ' ', '\n', '\t')
+ .map { it.trim() }
+ .count { it.isNotBlank() }
+ return if (count == 0) "не заданы" else "заданы ($count)"
+}
+
private fun selectExistingServerConnection(
dbJson: String,
fallbackHost: String,
@@ -3849,61 +5071,15 @@ private fun selectExistingServerConnection(
val serverDns2 = dnsParts.getOrNull(1) ?: "1.0.0.1"
val publicHost = db.optString("public_ip").ifBlank { fallbackHost }
val defaultPorts = db.optString("default_ports").ifBlank { "56000,56001,9000" }
- val passwords = db.optJSONObject("passwords") ?: JSONObject()
- val now = System.currentTimeMillis() / 1000L
-
- data class Candidate(
- val entry: JSONObject,
- val label: String,
- val hasVkHash: Boolean
- )
-
- val candidates = mutableListOf()
- passwords.keys().forEach { pass ->
- val entry = passwords.optJSONObject(pass) ?: return@forEach
- val expiresAt = entry.optLong("expires_at", 0)
- val active = !entry.optBoolean("is_deactivated", false) && (expiresAt == 0L || expiresAt > now)
- if (active) {
- val label = entry.optString("label").ifBlank { "пользовательский пароль" }
- candidates += Candidate(
- entry = entry,
- label = label,
- hasVkHash = entry.optString("vk_hash").isNotBlank()
- )
- }
- }
-
- val selected = candidates
- .sortedWith(compareByDescending { it.hasVkHash }.thenBy { it.label.lowercase() })
- .firstOrNull()
-
- if (selected != null) {
- val ports = selected.entry.optString("ports").ifBlank { defaultPorts }
- return ExistingServerConnection(
- host = publicHost,
- password = mainPassword,
- vkHash = selected.entry.optString("vk_hash"),
- ports = parsePortsTriple(ports),
- adminId = serverAdminId,
- botToken = serverBotToken,
- dns1 = serverDns1,
- dns2 = serverDns2,
- source = "VK-хеш взят из пароля «${selected.label}».",
- needsVkHash = selected.entry.optString("vk_hash").isBlank()
- )
- }
-
return ExistingServerConnection(
host = publicHost,
password = mainPassword,
- vkHash = "",
ports = parsePortsTriple(defaultPorts),
adminId = serverAdminId,
botToken = serverBotToken,
dns1 = serverDns1,
dns2 = serverDns2,
- source = "Используется главный пароль администратора.",
- needsVkHash = true
+ adminProfile = parseOwnerProfileFromDb(db.optJSONObject("admin_profile"), defaultPorts)
)
}
@@ -4060,6 +5236,95 @@ private suspend fun performServerImportNow(
// ==================== Deploy ====================
+private const val SERVER_UPDATE_BACKUP_DIR = "/var/tmp/wdtt-plus-update-backup"
+
+private fun sha256File(file: File): String {
+ val digest = MessageDigest.getInstance("SHA-256")
+ file.inputStream().use { input ->
+ val buffer = ByteArray(64 * 1024)
+ while (true) {
+ val read = input.read(buffer)
+ if (read <= 0) break
+ digest.update(buffer, 0, read)
+ }
+ }
+ return digest.digest().joinToString("") { "%02x".format(it) }
+}
+
+private fun prepareServerUpdateRollback(ssh: SSHClient) {
+ val command = """
+ set -e
+ BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)}
+ rm -rf "${'$'}BACKUP"
+ install -d -m 700 "${'$'}BACKUP"
+ if [ -d /etc/wdtt ]; then cp -a /etc/wdtt "${'$'}BACKUP/config"; touch "${'$'}BACKUP/had_config"; fi
+ if [ -f /usr/local/bin/wdtt-server ]; then cp -a /usr/local/bin/wdtt-server "${'$'}BACKUP/wdtt-server"; touch "${'$'}BACKUP/had_binary"; fi
+ if [ -f /etc/systemd/system/wdtt.service ]; then cp -a /etc/systemd/system/wdtt.service "${'$'}BACKUP/wdtt.service"; touch "${'$'}BACKUP/had_service"; fi
+ if systemctl is-active --quiet wdtt; then touch "${'$'}BACKUP/was_active"; fi
+ echo WDTT_UPDATE_BACKUP=ready
+ """.trimIndent()
+ val output = ssh.exec(rootCommand(command), timeout = 30000L)
+ require(Regex("^WDTT_UPDATE_BACKUP=ready$", RegexOption.MULTILINE).containsMatchIn(output)) {
+ "не удалось подготовить страховочную копию обновления"
+ }
+}
+
+private fun cleanupServerUpdateRollback(ssh: SSHClient) {
+ ssh.exec(rootCommand("rm -rf ${shellQuote(SERVER_UPDATE_BACKUP_DIR)}"), timeout = 10000L)
+}
+
+private fun rollbackServerUpdate(ssh: SSHClient) {
+ val command = """
+ set -e
+ BACKUP=${shellQuote(SERVER_UPDATE_BACKUP_DIR)}
+ [ -d "${'$'}BACKUP" ] || { echo WDTT_ROLLBACK=missing; exit 2; }
+ systemctl stop wdtt 2>/dev/null || true
+ if [ -f "${'$'}BACKUP/had_binary" ]; then install -m 755 "${'$'}BACKUP/wdtt-server" /usr/local/bin/wdtt-server; else rm -f /usr/local/bin/wdtt-server; fi
+ if [ -f "${'$'}BACKUP/had_service" ]; then install -m 644 "${'$'}BACKUP/wdtt.service" /etc/systemd/system/wdtt.service; else rm -f /etc/systemd/system/wdtt.service; fi
+ if [ -f "${'$'}BACKUP/had_config" ]; then rm -rf /etc/wdtt; cp -a "${'$'}BACKUP/config" /etc/wdtt; else rm -rf /etc/wdtt; fi
+ systemctl daemon-reload
+ if [ -f "${'$'}BACKUP/was_active" ]; then systemctl restart wdtt; sleep 2; systemctl is-active --quiet wdtt; fi
+ rm -rf "${'$'}BACKUP"
+ echo WDTT_ROLLBACK=ok
+ """.trimIndent()
+ val output = ssh.exec(rootCommand(command), timeout = 60000L)
+ require(Regex("^WDTT_ROLLBACK=ok$", RegexOption.MULTILINE).containsMatchIn(output)) {
+ "сервер не подтвердил откат обновления"
+ }
+}
+
+private fun validatePreservedServerState(beforeJson: String, afterJson: String) {
+ val before = JSONObject(beforeJson)
+ val after = JSONObject(afterJson)
+ validatePasswordsDbStructure(after)
+ val beforePasswords = before.optJSONObject("passwords") ?: JSONObject()
+ val afterPasswords = after.optJSONObject("passwords") ?: JSONObject()
+ val afterDevices = after.optJSONObject("devices") ?: JSONObject()
+ 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
+ val newEntry = afterPasswords.optJSONObject(password)
+ ?: throw IllegalStateException("после обновления пропал действующий клиент ${password.take(4)}…")
+ listOf("device_id", "label", "vk_hash", "ports").forEach { field ->
+ require(oldEntry.optString(field, "") == newEntry.optString(field, "")) {
+ "после обновления изменилось поле $field у клиента ${password.take(4)}…"
+ }
+ }
+ require(oldEntry.optLong("expires_at", 0) == newEntry.optLong("expires_at", 0)) {
+ "после обновления изменился срок клиента ${password.take(4)}…"
+ }
+ require(oldEntry.optBoolean("is_deactivated", false) == newEntry.optBoolean("is_deactivated", false)) {
+ "после обновления изменился статус клиента ${password.take(4)}…"
+ }
+ val deviceId = oldEntry.optString("device_id", "")
+ if (deviceId.isNotBlank()) {
+ require(afterDevices.has(deviceId)) { "после обновления пропала привязка устройства клиента ${password.take(4)}…" }
+ }
+ }
+}
+
private suspend fun performDeploy(
context: Context,
host: String, user: String, pass: String, port: Int,
@@ -4070,11 +5335,15 @@ private suspend fun performDeploy(
onProgress: (Float, String) -> Unit
): Boolean = withContext(Dispatchers.IO) {
var session: Session? = null
+ var sshClient: SSHClient? = null
+ var rollbackPrepared = false
+ var preservedDbJson: String? = null
try {
onProgress(0.02f, "Подключение...")
session = createSSHSession(host, user, pass, port)
DeployManager.activeSession = session
val ssh = SSHClient(session, pass)
+ sshClient = ssh
onProgress(0.05f, "Подготовка файлов...")
val passArg = if (mainPass.isNotBlank()) "-password $mainPass " else ""
@@ -4100,6 +5369,16 @@ private suspend fun performDeploy(
DeployManager.failDeploy("server asset выглядит устаревшим. Соберите APK заново.")
return@withContext false
}
+ val expectedServerSha256 = sha256File(serverFile)
+ if (mode == DeployMode.PreserveData) {
+ onProgress(0.055f, "Проверка сохранённых данных...")
+ val currentDbJson = readRemotePasswordsJson(ssh)?.also {
+ validatePasswordsDbStructure(JSONObject(it))
+ }
+ if (importPlan == null) preservedDbJson = currentDbJson
+ prepareServerUpdateRollback(ssh)
+ rollbackPrepared = true
+ }
onProgress(0.06f, "Загрузка на сервер...")
ssh.upload(scriptFile, "/tmp/deploy.sh")
@@ -4146,47 +5425,65 @@ private suspend fun performDeploy(
)
}
val output = ssh.exec(
- rootCommand("env WDTT_ARGS=${shellQuote(args)} WDTT_DTLS_PORT=$dtlsPort WDTT_WG_PORT=$wgPort WDTT_SSH_PORT=$port bash /tmp/deploy.sh"),
+ rootCommand("env WDTT_ARGS=${shellQuote(args)} WDTT_DTLS_PORT=$dtlsPort WDTT_WG_PORT=$wgPort WDTT_SSH_PORT=$port WDTT_PRESERVE_DATA=${if (mode == DeployMode.PreserveData) 1 else 0} bash /tmp/deploy.sh"),
timeout = CMD_TIMEOUT
)
if (output.contains("✅") || output.contains("Деплой успешно") || output.contains("active")) {
- val verifyOutput = ssh.exec(
- rootCommand(
- "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)\""
- ),
+ 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}')\""
+ ),
timeout = 20000L
)
val binaryOk = Regex("^BINARY=1$", RegexOption.MULTILINE).containsMatchIn(verifyOutput)
- val configOk = Regex("^CONFIG=1$", RegexOption.MULTILINE).containsMatchIn(verifyOutput)
- val serviceActive = Regex("^SERVICE=active$", RegexOption.MULTILINE).containsMatchIn(verifyOutput)
- if (!binaryOk || !configOk || !serviceActive) {
- DeployManager.writeError("Deploy verify failed: ${verifyOutput.take(500)}")
- val missing = buildList {
- if (!binaryOk) add("бинарник")
- if (!configOk) add("конфиг /etc/wdtt")
- if (!serviceActive) add("служба wdtt")
- }.joinToString(", ")
- DeployManager.failDeploy("скрипт завершился, но проверка не прошла: $missing")
- return@withContext false
- }
+ val configOk = Regex("^CONFIG=1$", RegexOption.MULTILINE).containsMatchIn(verifyOutput)
+ val serviceActive = Regex("^SERVICE=active$", RegexOption.MULTILINE).containsMatchIn(verifyOutput)
+ 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 binaryCurrent = installedSha256 == expectedServerSha256
+ if (!binaryOk || !configOk || !serviceActive || !adminSocketOk || !binaryCurrent) {
+ DeployManager.writeError("Deploy verify failed: ${verifyOutput.take(500)}")
+ val missing = buildList {
+ if (!binaryOk) add("бинарник")
+ if (!configOk) add("конфиг /etc/wdtt")
+ if (!serviceActive) add("служба wdtt")
+ if (!adminSocketOk) add("admin-сокет новой версии")
+ if (!binaryCurrent) add("актуальная версия бинарника")
+ }.joinToString(", ")
+ throw IllegalStateException("скрипт завершился, но проверка не прошла: $missing")
+ }
+ val updatedDbJson = readRemotePasswordsJson(ssh)
+ ?: throw IllegalStateException("после обновления не найдена база passwords.json")
+ validatePasswordsDbStructure(JSONObject(updatedDbJson))
+ preservedDbJson?.let { validatePreservedServerState(it, updatedDbJson) }
+ if (rollbackPrepared) {
+ cleanupServerUpdateRollback(ssh)
+ rollbackPrepared = false
+ }
DeployManager.stopDeploy("success")
TunnelManager.addDeploySuccessLog("Деплой успешно завершён. Сервис активен.")
return@withContext true
} else if (output.contains("error:")) {
DeployManager.writeError("Deploy script output contains error")
- DeployManager.failDeploy("скрипт установки вернул ошибку. Подробности сохранены в errors.log.")
- return@withContext false
+ throw IllegalStateException("скрипт установки вернул ошибку; подробности сохранены в errors.log")
} else {
DeployManager.writeError("Deploy unclear output: ${output.take(500)}")
- DeployManager.failDeploy("не удалось подтвердить установку: нет признака active/успеха от скрипта.")
- return@withContext false
+ throw IllegalStateException("не удалось подтвердить установку: нет признака active/успеха от скрипта")
}
- } catch (e: Exception) {
- DeployManager.writeError("Deploy critical: ${e.message}\n${e.stackTraceToString().take(500)}")
+ } catch (e: Exception) {
+ if (rollbackPrepared) {
+ runCatching { sshClient?.let(::rollbackServerUpdate) }
+ .onFailure { rollbackError -> DeployManager.writeError("Update rollback failed: ${rollbackError.message}") }
+ rollbackPrepared = false
+ }
+ DeployManager.writeError("Deploy critical: ${e.message}\n${e.stackTraceToString().take(500)}")
DeployManager.failDeploy(e.message?.take(120) ?: "неизвестная ошибка")
return@withContext false
} finally {
@@ -4358,7 +5655,7 @@ private fun ServerImportConfirmDialog(
ConfirmLine("Режим", modeText)
ConfirmLine("Бэкап", "${backup.sourceHost}, ${backup.createdAt}")
ConfirmLine("Данные", "${backup.passwordCount} паролей, ${backup.deviceCount} устройств")
- ConfirmLine("Публичный адрес ссылок", request.host)
+ ConfirmLine("Адрес сервера для ссылок", request.host)
ConfirmLine("Порты быстрых ссылок", portsSpec)
ConfirmLine("Главный пароль", mainPasswordText)
ConfirmLine("Telegram-админ/бот", adminText)
@@ -4811,8 +6108,61 @@ private fun ExistingInstallDialog(
InstallTraceLine("Сервис активен", info.active)
}
}
+ Surface(
+ shape = RoundedCornerShape(14.dp),
+ color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.45f),
+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.25f))
+ ) {
+ Text(
+ "Направление установки: приложение → сервер. После подтверждения текущие поля приложения будут записаны на сервер; подключение без установки действует в обратном направлении и здесь не выполняется.",
+ modifier = Modifier.fillMaxWidth().padding(12.dp),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onPrimaryContainer
+ )
+ }
+ info.comparison?.let { comparison ->
+ when {
+ comparison.checkError != null -> Surface(
+ shape = RoundedCornerShape(14.dp),
+ color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.55f),
+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.35f))
+ ) {
+ Text(
+ "Не удалось сравнить сохранённые поля сервера с приложением. При продолжении они могут быть заменены локальными значениями: ${comparison.checkError.take(180)}",
+ modifier = Modifier.fillMaxWidth().padding(12.dp),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onErrorContainer
+ )
+ }
+ comparison.overwriteLines.isNotEmpty() -> Surface(
+ shape = RoundedCornerShape(14.dp),
+ color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.55f),
+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.35f))
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(12.dp),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ Text("Будут заменены серверные значения:", fontWeight = FontWeight.SemiBold)
+ comparison.overwriteLines.forEach { Text("• $it", style = MaterialTheme.typography.bodySmall) }
+ Text(
+ "Если нужны значения сервера, отмените установку и сначала выполните «Подключиться (без установки)». Для выходного IP используйте «Заполнить».",
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ }
+ else -> Text(
+ "Сверка завершена: конфликтующих сохранённых значений не найдено.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ comparison.notes.forEach {
+ Text("• $it", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ }
Text(
- "С сохранением данных: обновится бинарник и настройки из текущих полей деплоя. Существующие пользовательские пароли, привязки устройств, история и ключи сохранятся.\n\nС нуля: данные WDTT Plus на сервере будут удалены, все выданные ссылки и привязки пропадут.",
+ "С сохранением данных: обновится бинарник, серверные настройки будут взяты из приложения, а клиентские пароли, привязки устройств, история и ключи сохранятся. Перед изменением создаётся страховочная копия.\n\nС нуля: данные WDTT Plus на сервере будут удалены, все выданные ссылки и привязки пропадут; затем сервер получит текущие поля приложения.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
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 08cfa39..797ae7e 100644
--- a/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt
+++ b/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt
@@ -7,7 +7,6 @@ import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
-import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
@@ -122,7 +121,10 @@ private fun AppItem.matchesVpnDetectionApp(): Boolean {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
-fun ExceptionsTab() {
+fun ExceptionsTab(
+ firstVisibleItemIndex: MutableIntState = rememberSaveable { mutableIntStateOf(0) },
+ firstVisibleItemScrollOffset: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
+) {
val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
@@ -350,7 +352,10 @@ fun ExceptionsTab() {
CircularProgressIndicator()
}
} else {
- val listState = rememberLazyListState()
+ val listState = rememberRememberedLazyListState(
+ firstVisibleItemIndex,
+ firstVisibleItemScrollOffset
+ )
if (filteredApps.isEmpty()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
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 d0a3416..6f220a6 100644
--- a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt
+++ b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt
@@ -1,13 +1,16 @@
package com.wdtt.plus.ui
import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
+import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
+import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -45,6 +48,7 @@ import kotlin.math.roundToInt
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.Share
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
@@ -65,6 +69,7 @@ fun FloatingToolbar(
onFingerprintChange: (String) -> Unit,
activeClientIds: String,
onClientIdsChange: (String) -> Unit,
+ onTransferRequested: () -> Unit,
modifier: Modifier = Modifier
) {
val configuration = LocalConfiguration.current
@@ -185,6 +190,7 @@ fun FloatingToolbar(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
+ .animateContentSize(animationSpec = spring(stiffness = Spring.StiffnessMediumLow))
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
@@ -241,6 +247,17 @@ fun FloatingToolbar(
}
}
+ OutlinedButton(
+ onClick = {
+ onTransferRequested()
+ },
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
+ shape = RoundedCornerShape(12.dp)
+ ) {
+ Icon(Icons.Filled.Share, contentDescription = null, modifier = Modifier.size(18.dp))
+ Text(" Передать или получить", fontSize = 12.sp)
+ }
+
HorizontalDivider(
modifier = Modifier.padding(vertical = 4.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
@@ -339,8 +356,12 @@ fun FloatingToolbar(
)
}
- AnimatedVisibility(visible = showPalettes) {
- Column {
+ AnimatedVisibility(
+ visible = showPalettes,
+ enter = expandVertically(animationSpec = spring(stiffness = Spring.StiffnessMediumLow)) + fadeIn(),
+ exit = shrinkVertically(animationSpec = spring(stiffness = Spring.StiffnessMediumLow)) + fadeOut()
+ ) {
+ Column(modifier = Modifier.fillMaxWidth()) {
HorizontalDivider(
modifier = Modifier.padding(vertical = 4.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
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 35a524c..a3f7b44 100644
--- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt
+++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt
@@ -60,7 +60,9 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -104,6 +106,7 @@ private const val ReleasesUrl = "https://github.com/Ivan4537/WDTT-Plus/releases"
private const val IssuesUrl = "https://github.com/Ivan4537/WDTT-Plus/issues/new/choose"
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 OriginalDonateUrl = "https://yoomoney.ru/to/4100119505530465/"
private val DonateActionButtonColor = Color(0xFF00AEA5)
@@ -165,12 +168,13 @@ private fun openUrlInBrowser(context: Context, url: String) {
@Composable
fun InfoTab(
actionsExpandedState: MutableState = rememberSaveable { mutableStateOf(true) },
- projectExpandedState: MutableState = rememberSaveable { mutableStateOf(true) }
+ projectExpandedState: MutableState = rememberSaveable { mutableStateOf(true) },
+ scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
- val infoScrollState = rememberScrollState()
+ val infoScrollState = rememberRememberedScrollState(scrollPosition)
val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() }
var actionsSectionY by remember { mutableStateOf(0f) }
var projectSectionY by remember { mutableStateOf(0f) }
@@ -377,7 +381,7 @@ fun InfoTab(
ExpandableSectionCard(
title = "О проекте",
- itemCount = "3 ссылки",
+ itemCount = "4 ссылки",
expanded = projectExpanded,
modifier = Modifier.onGloballyPositioned { projectSectionY = it.positionInParent().y },
onToggle = {
@@ -440,6 +444,20 @@ fun InfoTab(
)
}
)
+
+ ProjectLinkRow(
+ title = "История изменений",
+ subtitle = "Что менялось в версиях WDTT Plus",
+ onClick = { openUrlInBrowser(context, ChangelogUrl) },
+ icon = {
+ Icon(
+ imageVector = Icons.Default.Update,
+ contentDescription = null,
+ tint = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.size(18.dp)
+ )
+ }
+ )
}
Spacer(modifier = Modifier.height(20.dp))
diff --git a/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt b/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt
index 23f7a45..38162c7 100644
--- a/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt
+++ b/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt
@@ -9,7 +9,6 @@ import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
-import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
@@ -17,6 +16,7 @@ import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
@@ -34,13 +34,19 @@ import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
-fun LogsTab() {
+fun LogsTab(
+ firstVisibleItemIndex: MutableIntState = rememberSaveable { mutableIntStateOf(0) },
+ firstVisibleItemScrollOffset: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
+) {
val context = LocalContext.current
val settingsStore = remember { SettingsStore(context) }
val loggingEnabled by settingsStore.loggingEnabled.collectAsStateWithLifecycle(initialValue = true)
val scope = rememberCoroutineScope()
val currentLogs by TunnelManager.logs.collectAsStateWithLifecycle()
- val listState = rememberLazyListState()
+ val listState = rememberRememberedLazyListState(
+ firstVisibleItemIndex,
+ firstVisibleItemScrollOffset
+ )
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
// Toolbar
diff --git a/app/src/main/java/com/wdtt/plus/ui/RememberedScroll.kt b/app/src/main/java/com/wdtt/plus/ui/RememberedScroll.kt
new file mode 100644
index 0000000..0563397
--- /dev/null
+++ b/app/src/main/java/com/wdtt/plus/ui/RememberedScroll.kt
@@ -0,0 +1,82 @@
+package com.wdtt.plus.ui
+
+import androidx.compose.foundation.ScrollState
+import androidx.compose.foundation.lazy.LazyListState
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.MutableIntState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshotFlow
+import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.withTimeoutOrNull
+
+@Composable
+fun rememberRememberedScrollState(savedPosition: MutableIntState): ScrollState {
+ val scrollState = rememberScrollState(initial = savedPosition.intValue)
+ var restored by remember { mutableStateOf(false) }
+
+ LaunchedEffect(scrollState) {
+ val target = savedPosition.intValue
+ if (target > 0) {
+ withTimeoutOrNull(900) {
+ snapshotFlow { scrollState.maxValue }
+ .filter { maxValue -> maxValue >= target }
+ .first()
+ }
+ scrollState.scrollTo(target.coerceIn(0, scrollState.maxValue))
+ }
+ restored = true
+ }
+
+ LaunchedEffect(scrollState, restored) {
+ if (!restored) return@LaunchedEffect
+ snapshotFlow { scrollState.value }.collect { position ->
+ savedPosition.intValue = position
+ }
+ }
+
+ return scrollState
+}
+
+@Composable
+fun rememberRememberedLazyListState(
+ savedFirstVisibleItemIndex: MutableIntState,
+ savedFirstVisibleItemScrollOffset: MutableIntState
+): LazyListState {
+ val listState = rememberLazyListState(
+ initialFirstVisibleItemIndex = savedFirstVisibleItemIndex.intValue,
+ initialFirstVisibleItemScrollOffset = savedFirstVisibleItemScrollOffset.intValue
+ )
+ var restored by remember { mutableStateOf(false) }
+
+ LaunchedEffect(listState) {
+ val targetIndex = savedFirstVisibleItemIndex.intValue
+ val targetOffset = savedFirstVisibleItemScrollOffset.intValue
+ if (targetIndex > 0 || targetOffset > 0) {
+ snapshotFlow { listState.layoutInfo.totalItemsCount }
+ .filter { itemCount -> itemCount > 0 }
+ .first()
+ val itemCount = listState.layoutInfo.totalItemsCount
+ listState.scrollToItem(targetIndex.coerceAtMost(itemCount - 1), targetOffset)
+ }
+ restored = true
+ }
+
+ LaunchedEffect(listState, restored) {
+ if (!restored) return@LaunchedEffect
+ snapshotFlow {
+ listState.firstVisibleItemIndex to listState.firstVisibleItemScrollOffset
+ }.collect { (index, offset) ->
+ savedFirstVisibleItemIndex.intValue = index
+ savedFirstVisibleItemScrollOffset.intValue = offset
+ }
+ }
+
+ return listState
+}
diff --git a/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt
new file mode 100644
index 0000000..0b75fe6
--- /dev/null
+++ b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt
@@ -0,0 +1,2281 @@
+package com.wdtt.plus.ui
+
+import android.Manifest
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.graphics.Bitmap
+import android.net.Uri
+import android.os.Build
+import android.widget.Toast
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.animateContentSize
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.expandVertically
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.foundation.pager.HorizontalPager
+import androidx.compose.foundation.pager.rememberPagerState
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.shrinkVertically
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.requiredHeight
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
+import androidx.compose.material.icons.filled.Add
+import androidx.compose.material.icons.filled.CheckCircle
+import androidx.compose.material.icons.filled.ChevronLeft
+import androidx.compose.material.icons.filled.ChevronRight
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.Delete
+import androidx.compose.material.icons.filled.ExpandLess
+import androidx.compose.material.icons.filled.ExpandMore
+import androidx.compose.material.icons.filled.FilterList
+import androidx.compose.material.icons.filled.Link
+import androidx.compose.material.icons.filled.LockOpen
+import androidx.compose.material.icons.filled.PauseCircle
+import androidx.compose.material.icons.filled.QrCode2
+import androidx.compose.material.icons.filled.Refresh
+import androidx.compose.material.icons.filled.SaveAlt
+import androidx.compose.material.icons.filled.Share
+import androidx.compose.material.icons.filled.Smartphone
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.FilterChip
+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.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+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.runtime.snapshotFlow
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.viewmodel.compose.viewModel
+import com.wdtt.plus.ServerAdminActionResult
+import com.wdtt.plus.ServerAdminClient
+import com.wdtt.plus.ServerAdminProfileInfo
+import com.wdtt.plus.ServerAdminState
+import com.wdtt.plus.ServerAdminTarget
+import com.wdtt.plus.ServerClientCreateRequest
+import com.wdtt.plus.ServerClientInfo
+import com.wdtt.plus.ServerTrafficPeriod
+import com.wdtt.plus.TransferFiles
+import com.wdtt.plus.connectionLink
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+private enum class ClientWizardStep {
+ Days,
+ Label,
+ Hash,
+ Ports,
+ Confirm
+}
+
+private enum class ClientDetailsStep { Overview, Device, History, Edit }
+
+private enum class ServerToolsStep { Overview, Owner, Network, Maintenance }
+
+private enum class ClientActionCategory { Connection, Client, Access }
+
+private enum class ClientStatusFilter { All, Active, Disabled }
+
+private enum class ClientBindingFilter { All, Bound, Unbound }
+
+private enum class ClientExpiryFilter { All, Valid, Expired, Unlimited }
+
+private enum class ClientVkHashFilter { All, Present, Missing }
+
+private data class PendingClientAction(
+ val title: String,
+ val message: String,
+ val confirmLabel: String,
+ val danger: Boolean,
+ val onConfirm: () -> Unit = {},
+ val run: suspend () -> ServerAdminActionResult
+)
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+fun ServerClientsSection(
+ host: String,
+ user: String,
+ sshPassword: String,
+ sshPort: Int,
+ mainPassword: String,
+ defaultPorts: String,
+ adminProfile: ServerAdminProfileInfo,
+ enabled: Boolean,
+ expanded: Boolean = true,
+ modifier: Modifier = Modifier,
+ onExpandedChange: (Boolean) -> Unit = {},
+ onExpanded: () -> Unit = {}
+) {
+ val context = LocalContext.current
+ val scope = rememberCoroutineScope()
+ val clientsViewModel: ServerClientsViewModel = viewModel()
+ var state by clientsViewModel.serverState
+ var busy by remember { mutableStateOf(false) }
+ var status by rememberSaveable { mutableStateOf("") }
+ var showCreateWizard by rememberSaveable { mutableStateOf(false) }
+ var pendingAction by remember { mutableStateOf(null) }
+ var expiryClient 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) }
+ var filtersExpanded by rememberSaveable { mutableStateOf(false) }
+ var statusFilter by rememberSaveable { mutableStateOf(ClientStatusFilter.All) }
+ var bindingFilter by rememberSaveable { mutableStateOf(ClientBindingFilter.All) }
+ var expiryFilter by rememberSaveable { mutableStateOf(ClientExpiryFilter.All) }
+ var vkHashFilter by rememberSaveable { mutableStateOf(ClientVkHashFilter.All) }
+ var clientSearchFocused by remember { mutableStateOf(false) }
+ var clientSearch by clientsViewModel.clientSearch
+ var selectedClientIndex by clientsViewModel.selectedClientIndex
+ val arrowRotation by animateFloatAsState(
+ targetValue = if (expanded) 180f else 0f,
+ label = "server_clients_arrow_rotation"
+ )
+
+ val targetReady = host.isNotBlank() && sshPassword.isNotBlank() && mainPassword.isNotBlank()
+ val targetKey = remember(host, user, sshPort, mainPassword) {
+ listOf(host.trim(), user.ifBlank { "root" }, sshPort.toString(), mainPassword.hashCode().toString()).joinToString("\u0000")
+ }
+ LaunchedEffect(targetKey, targetReady) {
+ if (targetReady && clientsViewModel.targetKey != targetKey) {
+ clientsViewModel.targetKey = targetKey
+ state = null
+ status = ""
+ detailsClient = null
+ showServerTools = false
+ clientSearch = ""
+ selectedClientIndex = 0
+ }
+ }
+
+ LaunchedEffect(status, busy) {
+ if (status.isBlank() || busy) return@LaunchedEffect
+ delay(if (status.startsWith("Ошибка")) 8_000L else 4_500L)
+ if (!busy) status = ""
+ }
+
+ val canUse = enabled && targetReady && !busy
+ val effectiveUser = user.ifBlank { "root" }
+ val target = ServerAdminTarget(
+ host = host.trim(),
+ user = effectiveUser,
+ sshPassword = sshPassword,
+ sshPort = sshPort,
+ mainPassword = mainPassword
+ )
+
+ fun refreshClients() {
+ if (!targetReady || busy) return
+ busy = true
+ status = "Читаю клиентов на сервере..."
+ scope.launch {
+ runCatching { ServerAdminClient.list(target) }
+ .onSuccess {
+ state = it
+ status = "Готово: клиентов ${it.passwordCount}, устройств ${it.deviceCount}."
+ }
+ .onFailure { status = "Ошибка: ${it.message ?: "не удалось прочитать клиентов"}" }
+ busy = false
+ }
+ }
+
+ fun runAction(action: PendingClientAction) {
+ pendingAction = null
+ action.onConfirm()
+ busy = true
+ status = action.title
+ scope.launch {
+ runCatching { action.run() }
+ .onSuccess { result ->
+ status = buildString {
+ append(result.message)
+ if (result.restarted) append(". Сервис перезапущен.")
+ }
+ runCatching { ServerAdminClient.list(target) }.onSuccess { state = it }
+ }
+ .onFailure { status = "Ошибка: ${it.message ?: "операция не выполнена"}" }
+ busy = false
+ }
+ }
+
+ fun runDirect(title: String, action: suspend () -> ServerAdminActionResult) {
+ busy = true
+ status = title
+ scope.launch {
+ runCatching { action() }
+ .onSuccess { result ->
+ status = result.message + if (result.restarted) ". Сервис перезапущен." else ""
+ runCatching { ServerAdminClient.list(target) }.onSuccess { state = it }
+ }
+ .onFailure { status = "Ошибка: ${it.message ?: "операция не выполнена"}" }
+ busy = false
+ }
+ }
+
+ AppSectionCard(
+ modifier = modifier,
+ contentPadding = PaddingValues(16.dp),
+ verticalArrangement = Arrangement.spacedBy(0.dp)
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(24.dp))
+ .clickable {
+ val willExpand = !expanded
+ onExpandedChange(willExpand)
+ if (willExpand) onExpanded()
+ }
+ .padding(vertical = 2.dp)
+ ) {
+ Surface(shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.primaryContainer) {
+ Box(modifier = Modifier.size(40.dp), contentAlignment = Alignment.Center) {
+ Icon(
+ imageVector = Icons.Default.Smartphone,
+ contentDescription = null,
+ tint = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.size(18.dp)
+ )
+ }
+ }
+ Column(modifier = Modifier.weight(1f)) {
+ Text("Клиенты и сервер", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
+ }
+ Icon(
+ imageVector = Icons.Default.ExpandMore,
+ contentDescription = if (expanded) "Свернуть" else "Раскрыть",
+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier
+ .size(24.dp)
+ .rotate(arrowRotation)
+ )
+ }
+
+ AnimatedVisibility(
+ visible = expanded,
+ enter = expandVertically() + fadeIn(),
+ exit = shrinkVertically() + fadeOut()
+ ) {
+ Column(
+ modifier = Modifier.padding(top = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f))
+ Text(
+ "Создание доступов, управление подключениями и серверные инструменты без Telegram-бота.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+
+ if (!targetReady) {
+ Text(
+ "Укажите IP/домен, SSH-пароль и главный пароль в «Секретах». После деплоя нажмите «Обновить».",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ OutlinedButton(onClick = { refreshClients() }, enabled = canUse) {
+ Icon(Icons.Default.Refresh, null, Modifier.size(18.dp))
+ Text(" Обновить")
+ }
+ Button(onClick = { showCreateWizard = true }, enabled = canUse) {
+ Icon(Icons.Default.Add, null, Modifier.size(18.dp))
+ Text(" Создать")
+ }
+ OutlinedButton(onClick = { showServerTools = true }, enabled = canUse && state != null) {
+ Text("Сервер")
+ }
+ }
+
+ if (status.isNotBlank() && state == null) {
+ ClientStatusBanner(status = status, busy = busy)
+ }
+
+ AnimatedVisibility(state != null) {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ val current = state ?: return@AnimatedVisibility
+ val activeFilterCount = activeClientFilterCount(statusFilter, bindingFilter, expiryFilter, vkHashFilter)
+ ClientPanel {
+ Text(
+ "Лимит: ${current.passwordCount}/${current.maxPasswords}\nАдрес сервера для ссылок: ${if (current.publicHost.isBlank()) "определён автоматически: ${current.effectivePublicHost.ifBlank { host }}" else "задан вручную: ${current.publicHost}"}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.Top
+ ) {
+ Surface(
+ shape = RoundedCornerShape(18.dp),
+ color = MaterialTheme.colorScheme.surface,
+ border = BorderStroke(
+ 1.dp,
+ if (clientSearchFocused) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline
+ ),
+ modifier = Modifier
+ .weight(1f)
+ .requiredHeight(56.dp)
+ ) {
+ BasicTextField(
+ value = clientSearch,
+ onValueChange = { clientSearch = it.take(80); selectedClientIndex = 0 },
+ singleLine = true,
+ textStyle = MaterialTheme.typography.bodyLarge.copy(color = MaterialTheme.colorScheme.onSurface),
+ cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
+ modifier = Modifier
+ .fillMaxSize()
+ .onFocusChanged { clientSearchFocused = it.isFocused },
+ decorationBox = { innerTextField ->
+ Box(
+ modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),
+ contentAlignment = Alignment.CenterStart
+ ) {
+ if (clientSearch.isBlank()) {
+ Text(
+ "Поиск по клиентам",
+ style = MaterialTheme.typography.bodyLarge,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ innerTextField()
+ }
+ }
+ )
+ }
+ Surface(
+ onClick = { filtersExpanded = true },
+ shape = RoundedCornerShape(18.dp),
+ color = MaterialTheme.colorScheme.surface,
+ contentColor = MaterialTheme.colorScheme.primary,
+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
+ modifier = Modifier
+ .width(if (activeFilterCount > 0) 72.dp else 56.dp)
+ .requiredHeight(56.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxSize(),
+ horizontalArrangement = Arrangement.Center,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Icon(Icons.Default.FilterList, contentDescription = "Фильтры", modifier = Modifier.size(20.dp))
+ if (activeFilterCount > 0) Text(" $activeFilterCount")
+ }
+ }
+ }
+ }
+ val filteredClients = remember(current.clients, clientSearch, statusFilter, bindingFilter, expiryFilter, vkHashFilter) {
+ current.clients
+ .filterByQuery(clientSearch)
+ .filterByClientFilters(statusFilter, bindingFilter, expiryFilter, vkHashFilter)
+ }
+ LaunchedEffect(filteredClients.size) {
+ selectedClientIndex = selectedClientIndex.coerceIn(0, (filteredClients.size - 1).coerceAtLeast(0))
+ }
+ if (filteredClients.isEmpty()) {
+ Text(
+ when {
+ current.clients.isEmpty() -> "Клиенты не загружены."
+ clientSearch.isBlank() && activeFilterCount > 0 -> "По фильтрам ничего не найдено."
+ else -> "Ничего не найдено."
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ } else {
+ val publicHost = current.publicHost.ifBlank { current.effectivePublicHost }
+ val selectedClient = filteredClients[selectedClientIndex.coerceIn(0, filteredClients.lastIndex)]
+ ClientPanel(contentPadding = PaddingValues(vertical = 12.dp)) {
+ ClientsPager(
+ clients = filteredClients,
+ selectedIndex = selectedClientIndex,
+ onSelectedIndexChange = { selectedClientIndex = it },
+ fallbackHost = host,
+ publicHost = publicHost
+ )
+ SwipeHint(
+ selectedIndex = selectedClientIndex,
+ count = filteredClients.size,
+ modifier = Modifier.align(Alignment.CenterHorizontally)
+ )
+ }
+ ClientPanel {
+ Text(
+ "Действия для ${selectedClient.displayName()}",
+ style = MaterialTheme.typography.labelLarge,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.align(Alignment.CenterHorizontally)
+ )
+ ServerClientActions(
+ client = selectedClient,
+ fallbackHost = host,
+ publicHost = publicHost,
+ busy = busy,
+ onShareLink = { link -> shareText(context, link) },
+ onFile = { link ->
+ scope.launch {
+ runCatching {
+ withContext(Dispatchers.IO) {
+ TransferFiles.writeTransferText(context, "WDTT-Plus-${selectedClient.safeFileName()}.wdtt", link)
+ }
+ }.onSuccess {
+ shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus")
+ }.onFailure {
+ Toast.makeText(context, it.message ?: "Не удалось создать файл.", Toast.LENGTH_LONG).show()
+ }
+ }
+ },
+ onQr = { link ->
+ scope.launch {
+ runCatching {
+ withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) }
+ }.onSuccess { qrData = selectedClient.displayName() to it }
+ .onFailure { Toast.makeText(context, it.message ?: "Не удалось создать QR.", Toast.LENGTH_LONG).show() }
+ }
+ },
+ onExtend = { expiryClient = selectedClient },
+ onDetails = {
+ busy = true
+ status = "Читаю данные клиента..."
+ scope.launch {
+ runCatching { ServerAdminClient.details(target, selectedClient.password) }
+ .onSuccess {
+ detailsClient = it
+ status = "Данные клиента загружены."
+ }
+ .onFailure { status = "Ошибка: ${it.message ?: "не удалось прочитать клиента"}" }
+ busy = false
+ }
+ },
+ onUnbind = {
+ pendingAction = PendingClientAction(
+ title = "Отвязываю устройство...",
+ message = "Отвязать устройство от «${selectedClient.displayName()}»? Его текущее подключение завершится сразу, остальные клиенты продолжат работать.",
+ confirmLabel = "Отвязать",
+ danger = false,
+ run = { ServerAdminClient.unbind(target, selectedClient.password) }
+ )
+ },
+ onToggle = {
+ pendingAction = if (selectedClient.status == "deactivated") {
+ PendingClientAction(
+ title = "Включаю клиента...",
+ message = "Включить доступ «${selectedClient.displayName()}»?",
+ confirmLabel = "Включить",
+ danger = false,
+ run = { ServerAdminClient.activate(target, selectedClient.password) }
+ )
+ } else {
+ PendingClientAction(
+ title = "Отключаю клиента...",
+ message = "Отключить доступ «${selectedClient.displayName()}»? Текущее соединение завершится, но привязка устройства сохранится.",
+ confirmLabel = "Откл.",
+ danger = true,
+ run = { ServerAdminClient.deactivate(target, selectedClient.password) }
+ )
+ }
+ },
+ onDelete = {
+ pendingAction = PendingClientAction(
+ title = "Удаляю клиента...",
+ message = "Удалить «${selectedClient.displayName()}» без восстановления? Устройство тоже будет отвязано.",
+ confirmLabel = "Удалить",
+ danger = true,
+ run = { ServerAdminClient.delete(target, selectedClient.password) }
+ )
+ }
+ )
+ }
+ if (status.isNotBlank()) {
+ ClientStatusBanner(status = status, busy = busy)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (filtersExpanded) {
+ ClientFiltersDialog(
+ statusFilter = statusFilter,
+ onStatusFilterChange = { statusFilter = it; selectedClientIndex = 0 },
+ bindingFilter = bindingFilter,
+ onBindingFilterChange = { bindingFilter = it; selectedClientIndex = 0 },
+ expiryFilter = expiryFilter,
+ onExpiryFilterChange = { expiryFilter = it; selectedClientIndex = 0 },
+ vkHashFilter = vkHashFilter,
+ onVkHashFilterChange = { vkHashFilter = it; selectedClientIndex = 0 },
+ onClear = {
+ statusFilter = ClientStatusFilter.All
+ bindingFilter = ClientBindingFilter.All
+ expiryFilter = ClientExpiryFilter.All
+ vkHashFilter = ClientVkHashFilter.All
+ selectedClientIndex = 0
+ },
+ onDismiss = { filtersExpanded = false }
+ )
+ }
+
+ if (showCreateWizard) {
+ CreateClientWizardDialog(
+ defaultPorts = state?.defaultPorts ?: defaultPorts.ifBlank { "56000,56001,9000" },
+ busy = busy,
+ onDismiss = { if (!busy) showCreateWizard = false },
+ onCreate = { request ->
+ showCreateWizard = false
+ busy = true
+ status = "Создаю клиента..."
+ scope.launch {
+ runCatching { ServerAdminClient.create(target, request) }
+ .onSuccess { result ->
+ status = buildString {
+ append(result.message)
+ if (result.restarted) append(". Сервис перезапущен.")
+ }
+ createdClient = result.createdClient
+ runCatching { ServerAdminClient.list(target) }.onSuccess { state = it }
+ }
+ .onFailure { status = "Ошибка: ${it.message ?: "клиент не создан"}" }
+ busy = false
+ }
+ }
+ )
+ }
+
+ pendingAction?.let { action ->
+ ConfirmClientActionDialog(
+ action = action,
+ onDismiss = { pendingAction = null },
+ onConfirm = { runAction(action) }
+ )
+ }
+
+ expiryClient?.let { client ->
+ ExtendClientDialog(
+ client = client,
+ onDismiss = { expiryClient = null },
+ onSelect = { days ->
+ pendingAction = PendingClientAction(
+ title = "Обновляю срок...",
+ message = "Продлить «${client.displayName()}» ${formatExtensionPeriod(days)}?",
+ confirmLabel = "Продлить",
+ danger = false,
+ onConfirm = { expiryClient = null },
+ run = { ServerAdminClient.setExpiry(target, client.password, days) }
+ )
+ }
+ )
+ }
+
+ createdClient?.let { client ->
+ val link = client.connectionLink(host, state?.publicHost?.ifBlank { state?.effectivePublicHost.orEmpty() }.orEmpty())
+ AccessResultDialog(
+ title = "Клиент создан",
+ password = client.password,
+ link = link,
+ noLinkText = "VK-хеш не задан. Пароль уже работает; ссылку, QR и файл можно создать после добавления хеша в «Подробнее».",
+ onDismiss = { createdClient = null },
+ onCopyPassword = { copyText(context, "Пароль WDTT", client.password) },
+ onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } },
+ onShare = { link?.let { shareText(context, it) } },
+ onQr = {
+ link?.let { value ->
+ createdClient = null
+ scope.launch {
+ runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
+ .onSuccess { qrData = client.displayName() to it }
+ .onFailure { Toast.makeText(context, it.message ?: "Не удалось создать QR.", Toast.LENGTH_LONG).show() }
+ }
+ }
+ },
+ onFile = {
+ 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") }
+ .onFailure { Toast.makeText(context, it.message ?: "Не удалось создать файл.", Toast.LENGTH_LONG).show() }
+ }
+ }
+ }
+ )
+ }
+
+ detailsClient?.let { client ->
+ ClientDetailsDialog(
+ client = client,
+ defaultPorts = state?.defaultPorts ?: defaultPorts.ifBlank { "56000,56001,9000" },
+ fallbackHost = host,
+ publicHost = state?.publicHost?.ifBlank { state?.effectivePublicHost.orEmpty() }.orEmpty(),
+ busy = busy,
+ onDismiss = { detailsClient = null },
+ onSave = { label, hash, ports ->
+ detailsClient = null
+ runDirect("Обновляю клиента...") {
+ ServerAdminClient.updateClient(target, client.password, label, hash, ports)
+ }
+ }
+ )
+ }
+
+ if (showServerTools) {
+ state?.let { current ->
+ ServerToolsDialog(
+ state = current,
+ localAdminProfile = adminProfile,
+ busy = busy,
+ onDismiss = { showServerTools = false },
+ onSaveNetwork = { dns, limit, ports, publicHost ->
+ showServerTools = false
+ runDirect("Обновляю настройки сервера...") {
+ ServerAdminClient.updateSettings(target, dns, limit, ports, publicHost)
+ }
+ },
+ onRefreshIp = {
+ runDirect("Определяю публичный IP сервера...") { ServerAdminClient.refreshPublicHost(target) }
+ },
+ onCleanupExpired = {
+ pendingAction = PendingClientAction(
+ "Удаляю истёкшие доступы...",
+ "Удалить ${current.expiredCount} истёкших доступов?",
+ "Удалить", true
+ ) { ServerAdminClient.cleanupExpired(target) }
+ },
+ onCleanupOrphans = {
+ pendingAction = PendingClientAction(
+ "Удаляю забытые устройства...",
+ "Удалить ${current.orphanDeviceCount} ${current.orphanDeviceCount.pluralRu("запись", "записи", "записей")} устройств, не связанных с клиентами?",
+ "Удалить", true
+ ) { ServerAdminClient.cleanupOrphans(target) }
+ },
+ onResetTraffic = {
+ pendingAction = PendingClientAction(
+ "Сбрасываю статистику...",
+ "Обнулить счётчики трафика? Доступы и устройства сохранятся.",
+ "Сбросить", true
+ ) { ServerAdminClient.resetTraffic(target) }
+ },
+ onRestart = {
+ pendingAction = PendingClientAction(
+ "Перезапускаю WDTT...",
+ "Перезапустить wdtt.service? Все клиенты кратко отключатся.",
+ "Перезапуск", true
+ ) { ServerAdminClient.restart(target) }
+ }
+ )
+ }
+ }
+
+ qrData?.let { (title, bitmap) ->
+ ClientQrDialog(
+ title = title,
+ bitmap = bitmap,
+ onDismiss = { qrData = null },
+ onShare = {
+ 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.writeQrPng(context, fileName, bitmap) }
+ }.onSuccess { shareUri(context, it, "image/png", "Передать QR-код WDTT Plus") }
+ .onFailure { Toast.makeText(context, it.message ?: "Не удалось поделиться QR.", Toast.LENGTH_LONG).show() }
+ }
+ },
+ onSave = {
+ scope.launch {
+ val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
+ runCatching {
+ withContext(Dispatchers.IO) { TransferFiles.saveQrToGallery(context, "WDTT-Plus-client-$stamp.png", bitmap) }
+ }.onSuccess {
+ Toast.makeText(context, "QR-код сохранён.", Toast.LENGTH_SHORT).show()
+ }.onFailure {
+ Toast.makeText(context, it.message ?: "Не удалось сохранить QR.", Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+ )
+ }
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun ClientsPager(
+ clients: List,
+ selectedIndex: Int,
+ onSelectedIndexChange: (Int) -> Unit,
+ fallbackHost: String,
+ publicHost: String
+) {
+ val pagerState = rememberPagerState(
+ initialPage = selectedIndex.coerceIn(0, clients.lastIndex),
+ pageCount = { clients.size }
+ )
+ LaunchedEffect(selectedIndex, clients.size) {
+ val target = selectedIndex.coerceIn(0, clients.lastIndex)
+ if (pagerState.currentPage != target) pagerState.scrollToPage(target)
+ }
+ LaunchedEffect(pagerState, clients.size) {
+ snapshotFlow { pagerState.currentPage }.collect { page ->
+ if (page in clients.indices) onSelectedIndexChange(page)
+ }
+ }
+ HorizontalPager(
+ state = pagerState,
+ key = { index -> clients[index].password },
+ beyondViewportPageCount = 1,
+ contentPadding = PaddingValues(horizontal = 18.dp),
+ pageSpacing = 12.dp,
+ modifier = Modifier.fillMaxWidth()
+ ) { page ->
+ ServerClientCard(
+ client = clients[page],
+ fallbackHost = fallbackHost,
+ publicHost = publicHost,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+}
+
+@Composable
+private fun ServerClientCard(
+ client: ServerClientInfo,
+ fallbackHost: String,
+ publicHost: String,
+ modifier: Modifier = Modifier
+) {
+ Card(
+ modifier = modifier,
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.55f)),
+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.16f)),
+ shape = RoundedCornerShape(18.dp)
+ ) {
+ Column(modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(client.displayName(), fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(
+ client.maskedPassword(),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ StatusChip(client.status)
+ }
+ Text(
+ buildString {
+ append("Срок: ${formatExpiry(client.expiresAt)}")
+ append(" · Трафик: ${formatBytes(client.downBytes + client.upBytes)}")
+ if (client.deviceId.isNotBlank()) append(" · Устройство: ${client.deviceName.ifBlank { client.deviceId.take(8) }}")
+ else append(" · Не привязан")
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ if (client.vkHash.isBlank()) {
+ Text(
+ "VK-хеш не задан: быструю ссылку/QR создать нельзя, пока не обновить хеш.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun ClientFiltersDialog(
+ statusFilter: ClientStatusFilter,
+ onStatusFilterChange: (ClientStatusFilter) -> Unit,
+ bindingFilter: ClientBindingFilter,
+ onBindingFilterChange: (ClientBindingFilter) -> Unit,
+ expiryFilter: ClientExpiryFilter,
+ onExpiryFilterChange: (ClientExpiryFilter) -> Unit,
+ vkHashFilter: ClientVkHashFilter,
+ onVkHashFilterChange: (ClientVkHashFilter) -> Unit,
+ onClear: () -> Unit,
+ onDismiss: () -> Unit
+) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { DialogTitle("Фильтры клиентов", onDismiss) },
+ text = {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .verticalScroll(rememberScrollState())
+ ) {
+ ClientFiltersPanel(
+ statusFilter = statusFilter,
+ onStatusFilterChange = onStatusFilterChange,
+ bindingFilter = bindingFilter,
+ onBindingFilterChange = onBindingFilterChange,
+ expiryFilter = expiryFilter,
+ onExpiryFilterChange = onExpiryFilterChange,
+ vkHashFilter = vkHashFilter,
+ onVkHashFilterChange = onVkHashFilterChange,
+ onClear = onClear
+ )
+ }
+ },
+ confirmButton = {}
+ )
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun ClientFiltersPanel(
+ statusFilter: ClientStatusFilter,
+ onStatusFilterChange: (ClientStatusFilter) -> Unit,
+ bindingFilter: ClientBindingFilter,
+ onBindingFilterChange: (ClientBindingFilter) -> Unit,
+ expiryFilter: ClientExpiryFilter,
+ onExpiryFilterChange: (ClientExpiryFilter) -> Unit,
+ vkHashFilter: ClientVkHashFilter,
+ onVkHashFilterChange: (ClientVkHashFilter) -> Unit,
+ onClear: () -> Unit
+) {
+ val activeCount = activeClientFilterCount(statusFilter, bindingFilter, expiryFilter, vkHashFilter)
+ Surface(
+ modifier = Modifier.fillMaxWidth().padding(top = 10.dp),
+ shape = RoundedCornerShape(18.dp),
+ color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.24f),
+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.16f))
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(12.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ FilterGroupTitle("Статус")
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ ClientFilterChip("Все", statusFilter == ClientStatusFilter.All) { onStatusFilterChange(ClientStatusFilter.All) }
+ ClientFilterChip("Активные", statusFilter == ClientStatusFilter.Active) { onStatusFilterChange(ClientStatusFilter.Active) }
+ ClientFilterChip("Отключённые", statusFilter == ClientStatusFilter.Disabled) { onStatusFilterChange(ClientStatusFilter.Disabled) }
+ }
+
+ FilterGroupTitle("Устройство")
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ ClientFilterChip("Все", bindingFilter == ClientBindingFilter.All) { onBindingFilterChange(ClientBindingFilter.All) }
+ ClientFilterChip("Привязанные", bindingFilter == ClientBindingFilter.Bound) { onBindingFilterChange(ClientBindingFilter.Bound) }
+ ClientFilterChip("Без устройства", bindingFilter == ClientBindingFilter.Unbound) { onBindingFilterChange(ClientBindingFilter.Unbound) }
+ }
+
+ FilterGroupTitle("Срок")
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ ClientFilterChip("Все", expiryFilter == ClientExpiryFilter.All) { onExpiryFilterChange(ClientExpiryFilter.All) }
+ ClientFilterChip("Действующие", expiryFilter == ClientExpiryFilter.Valid) { onExpiryFilterChange(ClientExpiryFilter.Valid) }
+ ClientFilterChip("Истёкшие", expiryFilter == ClientExpiryFilter.Expired) { onExpiryFilterChange(ClientExpiryFilter.Expired) }
+ ClientFilterChip("Бессрочные", expiryFilter == ClientExpiryFilter.Unlimited) { onExpiryFilterChange(ClientExpiryFilter.Unlimited) }
+ }
+
+ FilterGroupTitle("VK-хеш")
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ ClientFilterChip("Все", vkHashFilter == ClientVkHashFilter.All) { onVkHashFilterChange(ClientVkHashFilter.All) }
+ ClientFilterChip("С хешем", vkHashFilter == ClientVkHashFilter.Present) { onVkHashFilterChange(ClientVkHashFilter.Present) }
+ ClientFilterChip("Без хеша", vkHashFilter == ClientVkHashFilter.Missing) { onVkHashFilterChange(ClientVkHashFilter.Missing) }
+ }
+
+ if (activeCount > 0) {
+ TextButton(onClick = onClear, modifier = Modifier.align(Alignment.End)) {
+ Text("Сбросить фильтры")
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun FilterGroupTitle(text: String) {
+ Text(
+ text,
+ style = MaterialTheme.typography.labelMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+}
+
+@Composable
+private fun ClientFilterChip(
+ text: String,
+ selected: Boolean,
+ onClick: () -> Unit
+) {
+ FilterChip(
+ selected = selected,
+ onClick = onClick,
+ label = { Text(text) }
+ )
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun ServerClientActions(
+ client: ServerClientInfo,
+ fallbackHost: String,
+ publicHost: String,
+ busy: Boolean,
+ onShareLink: (String) -> Unit,
+ onFile: (String) -> Unit,
+ onQr: (String) -> Unit,
+ onExtend: () -> Unit,
+ onDetails: () -> Unit,
+ onUnbind: () -> Unit,
+ onToggle: () -> Unit,
+ onDelete: () -> Unit
+) {
+ val link = remember(client, fallbackHost, publicHost) { client.connectionLink(fallbackHost, publicHost) }
+ var category by remember(client.password) { mutableStateOf(null) }
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ ClientActionCategoryBlock(
+ title = "Подключение",
+ expanded = category == ClientActionCategory.Connection,
+ enabled = !busy,
+ onClick = {
+ category = ClientActionCategory.Connection.takeUnless { category == it }
+ }
+ ) {
+ OutlinedButton(onClick = { link?.let(onShareLink) }, enabled = !busy && link != null) {
+ Icon(Icons.Default.Link, null, Modifier.size(16.dp))
+ Text(" Ссылка")
+ }
+ OutlinedButton(onClick = { link?.let(onQr) }, enabled = !busy && link != null) {
+ Icon(Icons.Default.QrCode2, null, Modifier.size(16.dp))
+ Text(" QR-код")
+ }
+ OutlinedButton(onClick = { link?.let(onFile) }, enabled = !busy && link != null) {
+ Icon(Icons.AutoMirrored.Filled.InsertDriveFile, null, Modifier.size(16.dp))
+ Text(" Файл")
+ }
+ }
+
+ ClientActionCategoryBlock(
+ title = "Клиент",
+ expanded = category == ClientActionCategory.Client,
+ enabled = !busy,
+ onClick = {
+ category = ClientActionCategory.Client.takeUnless { category == it }
+ }
+ ) {
+ OutlinedButton(onClick = onExtend, enabled = !busy) { Text("Продлить") }
+ OutlinedButton(onClick = onDetails, enabled = !busy) { Text("Подробнее") }
+ }
+
+ ClientActionCategoryBlock(
+ title = "Доступ",
+ expanded = category == ClientActionCategory.Access,
+ enabled = !busy,
+ onClick = {
+ category = ClientActionCategory.Access.takeUnless { category == it }
+ }
+ ) {
+ OutlinedButton(onClick = onUnbind, enabled = !busy && client.isBound) {
+ Icon(Icons.Default.Smartphone, null, Modifier.size(16.dp))
+ Text(" Отвязать")
+ }
+ OutlinedButton(onClick = onToggle, enabled = !busy) {
+ Icon(
+ if (client.status == "deactivated") Icons.Default.LockOpen else Icons.Default.PauseCircle,
+ null,
+ Modifier.size(16.dp)
+ )
+ Text(if (client.status == "deactivated") " Включить" else " Отключить")
+ }
+ OutlinedButton(
+ onClick = onDelete,
+ enabled = !busy,
+ colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error)
+ ) {
+ Icon(Icons.Default.Delete, null, Modifier.size(16.dp))
+ Text(" Удалить")
+ }
+ }
+ }
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun ClientActionCategoryBlock(
+ title: String,
+ expanded: Boolean,
+ enabled: Boolean,
+ onClick: () -> Unit,
+ content: @Composable () -> Unit
+) {
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth()
+ .animateContentSize(animationSpec = tween(durationMillis = 220)),
+ shape = RoundedCornerShape(12.dp),
+ color = if (expanded) MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.18f) else Color.Transparent,
+ border = BorderStroke(
+ 1.dp,
+ MaterialTheme.colorScheme.outline.copy(alpha = if (expanded) 0.34f else 0.18f)
+ )
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(8.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ OutlinedButton(
+ onClick = onClick,
+ enabled = enabled,
+ colors = ButtonDefaults.outlinedButtonColors()
+ ) {
+ Text(title)
+ Spacer(Modifier.width(4.dp))
+ Icon(
+ if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
+ contentDescription = if (expanded) "Свернуть" else "Раскрыть",
+ modifier = Modifier.size(18.dp)
+ )
+ }
+ }
+ if (expanded) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.14f))
+ FlowRow(
+ modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ content()
+ }
+ }
+ }
+ }
+ }
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun AccessResultDialog(
+ title: String,
+ password: String,
+ link: String?,
+ noLinkText: String,
+ onDismiss: () -> Unit,
+ onCopyPassword: () -> Unit,
+ onCopyLink: () -> Unit,
+ onShare: () -> Unit,
+ onQr: () -> Unit,
+ onFile: () -> Unit
+) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { DialogTitle(title, onDismiss) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Card(
+ shape = RoundedCornerShape(18.dp),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f))
+ ) {
+ Column(modifier = Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Пароль", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text(password, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
+ OutlinedButton(onClick = onCopyPassword, modifier = Modifier.fillMaxWidth()) { Text("Копировать пароль") }
+ }
+ }
+ if (link == null) {
+ Text(noLinkText, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ } else {
+ Text("Ссылка содержит пароль и VK-хеш. Не публикуйте её.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ OutlinedButton(onClick = onCopyLink) { Text("Копировать") }
+ OutlinedButton(onClick = onShare) { Text("Поделиться") }
+ OutlinedButton(onClick = onQr) { Text("QR") }
+ OutlinedButton(onClick = onFile) { Text("Файл") }
+ }
+ }
+ }
+ },
+ confirmButton = {}
+ )
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun ClientDetailsDialog(
+ client: ServerClientInfo,
+ defaultPorts: String,
+ fallbackHost: String,
+ publicHost: String,
+ busy: Boolean,
+ onDismiss: () -> Unit,
+ onSave: (String, String, String) -> Unit
+) {
+ val context = LocalContext.current
+ var step by rememberSaveable(client.password) { mutableStateOf(ClientDetailsStep.Overview) }
+ var label by rememberSaveable(client.password) { mutableStateOf(client.label) }
+ var hash by rememberSaveable(client.password) { mutableStateOf(client.vkHash) }
+ var ports by rememberSaveable(client.password) { mutableStateOf(client.ports) }
+ val portsValid = ports.isPortsSpec()
+ val link = remember(client, fallbackHost, publicHost) { client.connectionLink(fallbackHost, publicHost) }
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { DialogTitle(client.displayName(), onDismiss, enabled = !busy) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text(
+ when (step) {
+ ClientDetailsStep.Overview -> "Доступ и трафик"
+ ClientDetailsStep.Device -> "Устройство"
+ ClientDetailsStep.History -> "История привязок"
+ ClientDetailsStep.Edit -> "Редактирование"
+ },
+ style = MaterialTheme.typography.titleSmall,
+ fontWeight = FontWeight.Bold
+ )
+ Card(
+ modifier = Modifier.fillMaxWidth().heightIn(max = 430.dp),
+ shape = RoundedCornerShape(18.dp),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f))
+ ) {
+ Column(
+ modifier = Modifier.padding(14.dp).verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(9.dp)
+ ) {
+ when (step) {
+ ClientDetailsStep.Overview -> {
+ InfoLine("Пароль", client.maskedPassword().removePrefix("Пароль: "))
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ OutlinedButton(onClick = { copyText(context, "Пароль WDTT", client.password) }) { Text("Копировать пароль") }
+ OutlinedButton(onClick = { link?.let { copyText(context, "Ссылка WDTT", it) } }, enabled = link != null) { Text("Копировать ссылку") }
+ }
+ InfoLine("Статус", when (client.status) { "active" -> "активен"; "deactivated" -> "отключён"; "expired" -> "истёк"; else -> client.status })
+ InfoLine("Срок", formatExpiry(client.expiresAt))
+ InfoLine("Порты", client.ports)
+ InfoLine("VK-хеш", client.vkHash.ifBlank { "не задан" })
+ HorizontalDivider()
+ TrafficPeriodBlock(client.traffic)
+ }
+ ClientDetailsStep.Device -> {
+ val device = client.device
+ if (device == null) {
+ Text("Устройство ещё не привязано.")
+ } else {
+ InfoLine("Название", device.name.ifBlank { device.deviceId })
+ InfoLine("ID", device.deviceId)
+ InfoLine("WG IP", device.ip)
+ InfoLine("Модель", listOf(device.manufacturer, device.model).filter { it.isNotBlank() }.joinToString(" ").ifBlank { "неизвестно" })
+ InfoLine("Android", buildString {
+ append(device.androidVersion.ifBlank { "неизвестно" })
+ if (device.sdk > 0) append(" · SDK ${device.sdk}")
+ })
+ InfoLine("Приложение", device.appVersion.ifBlank { "неизвестно" })
+ InfoLine("ABI", device.abi.ifBlank { "неизвестно" })
+ InfoLine("Регион", listOf(device.country, device.locale).filter { it.isNotBlank() }.joinToString(" · ").ifBlank { "неизвестно" })
+ InfoLine("Внешний IP", device.remoteIp.ifBlank { "неизвестно" })
+ InfoLine("Последняя связь", formatDateTime(device.lastSeenAt))
+ }
+ }
+ ClientDetailsStep.History -> {
+ if (client.bindHistory.isEmpty()) {
+ Text("История пока пуста.")
+ } else {
+ client.bindHistory.takeLast(15).asReversed().forEachIndexed { index, event ->
+ if (index > 0) HorizontalDivider()
+ Text(
+ when (event.status) {
+ "active" -> "Подключено"
+ "unbound" -> "Отвязано"
+ "denied_mismatch" -> "Отклонено другое устройство"
+ else -> event.status
+ },
+ fontWeight = FontWeight.Bold
+ )
+ InfoLine("Когда", formatDateTime(event.eventAt.takeIf { it > 0 } ?: event.boundAt))
+ InfoLine("Устройство", event.deviceName.ifBlank { event.deviceId })
+ if (event.deviceIp.isNotBlank()) InfoLine("WG IP", event.deviceIp)
+ if (event.remoteIp.isNotBlank()) InfoLine("Внешний IP", event.remoteIp)
+ if (event.country.isNotBlank()) InfoLine("Регион", event.country)
+ if (event.note.isNotBlank()) Text(event.note, style = MaterialTheme.typography.bodySmall)
+ }
+ }
+ }
+ ClientDetailsStep.Edit -> {
+ OutlinedTextField(
+ value = label,
+ onValueChange = { label = it.take(40) },
+ label = { Text("Название") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = hash,
+ onValueChange = { hash = it },
+ label = { Text("VK-хеш или ссылка") },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = ports,
+ onValueChange = { ports = it.filter { ch -> ch.isDigit() || ch == ',' }.take(32) },
+ label = { Text("DTLS,WG,TUN") },
+ singleLine = true,
+ isError = !portsValid,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedButton(onClick = { ports = defaultPorts }, modifier = Modifier.fillMaxWidth()) {
+ Text("Стандартные порты")
+ }
+ if (!portsValid) Text("Формат: 56000,56001,9000", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
+ }
+ }
+ }
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ SelectButton("Обзор", step == ClientDetailsStep.Overview, modifier = Modifier.weight(1f)) {
+ step = ClientDetailsStep.Overview
+ }
+ SelectButton("Устройство", step == ClientDetailsStep.Device, modifier = Modifier.weight(1f)) {
+ step = ClientDetailsStep.Device
+ }
+ }
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ SelectButton("История", step == ClientDetailsStep.History, modifier = Modifier.weight(1f)) {
+ step = ClientDetailsStep.History
+ }
+ SelectButton("Изменить", step == ClientDetailsStep.Edit, modifier = Modifier.weight(1f)) {
+ step = ClientDetailsStep.Edit
+ }
+ }
+ }
+ }
+ },
+ confirmButton = {
+ if (step == ClientDetailsStep.Edit) {
+ Button(onClick = { onSave(label, hash, ports) }, enabled = !busy && portsValid) { Text("Сохранить") }
+ }
+ }
+ )
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun ServerToolsDialog(
+ state: ServerAdminState,
+ localAdminProfile: ServerAdminProfileInfo,
+ busy: Boolean,
+ onDismiss: () -> Unit,
+ onSaveNetwork: (String, Int, String, String) -> Unit,
+ onRefreshIp: () -> Unit,
+ onCleanupExpired: () -> Unit,
+ onCleanupOrphans: () -> Unit,
+ onResetTraffic: () -> Unit,
+ onRestart: () -> Unit
+) {
+ var step by rememberSaveable { mutableStateOf(ServerToolsStep.Overview) }
+ var dns by rememberSaveable(state.dns) { mutableStateOf(state.dns) }
+ var limitText by rememberSaveable(state.maxPasswords) { mutableStateOf(state.maxPasswords.toString()) }
+ var ports by rememberSaveable(state.defaultPorts) { mutableStateOf(state.defaultPorts) }
+ var publicHost by rememberSaveable(state.publicHost) { mutableStateOf(state.publicHost) }
+ val limit = limitText.toIntOrNull()
+ val networkValid = dns.isNotBlank() && limit != null && limit in 1..500 && ports.isPortsSpec()
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { DialogTitle("Управление сервером", onDismiss, enabled = !busy) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Card(
+ modifier = Modifier.fillMaxWidth().heightIn(max = 440.dp),
+ shape = RoundedCornerShape(18.dp),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f))
+ ) {
+ Column(
+ modifier = Modifier.padding(14.dp).verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ when (step) {
+ ServerToolsStep.Overview -> {
+ Text("Состояние", fontWeight = FontWeight.Bold)
+ InfoLine("Клиенты", "${state.passwordCount}/${state.maxPasswords}")
+ InfoLine("Устройства", state.deviceCount.toString())
+ InfoLine("Истёкшие", state.expiredCount.toString())
+ InfoLine("Забытые устройства", state.orphanDeviceCount.toString())
+ InfoLine(
+ "Адрес сервера для ссылок",
+ if (state.publicHost.isBlank()) "Определён автоматически: ${state.effectivePublicHost.ifBlank { "ещё не определён" }}"
+ else "Задан вручную: ${state.publicHost}"
+ )
+ HorizontalDivider()
+ Text("Весь трафик", fontWeight = FontWeight.Bold)
+ TrafficPeriodBlock(state.traffic)
+ HorizontalDivider()
+ Text("Главный пароль", fontWeight = FontWeight.Bold)
+ TrafficPeriodBlock(state.adminTraffic)
+ }
+ ServerToolsStep.Owner -> {
+ Text("Профиль владельца", fontWeight = FontWeight.Bold)
+ Text(
+ "Поля владельца хранятся отдельно от клиентов. Главный пароль не появляется в списке клиентов, не занимает лимит и не удаляется вместе с клиентскими доступами.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ HorizontalDivider()
+ Text("Сохранено на сервере", fontWeight = FontWeight.Bold)
+ InfoLine("Состояние", if (state.adminProfile.hasSavedFields) "сохранён ${formatDateTime(state.adminProfile.updatedAt)}" else "ещё не сохранён")
+ InfoLine("VK-хеши", secretPresenceLabel(state.adminProfile.vkHashes))
+ InfoLine("Резервный VK-хеш", secretPresenceLabel(state.adminProfile.secondaryVkHash))
+ InfoLine("Порты", state.adminProfile.ports)
+ InfoLine("Потоки", state.adminProfile.workersPerHash.toString())
+ InfoLine("Протокол", state.adminProfile.protocol)
+ InfoLine("SNI", state.adminProfile.sni.ifBlank { "не задан" })
+ InfoLine("No DNS", if (state.adminProfile.noDns) "включено" else "выключено")
+ HorizontalDivider()
+ Text("Будет записано при установке", fontWeight = FontWeight.Bold)
+ InfoLine("VK-хеши", secretPresenceLabel(localAdminProfile.vkHashes))
+ InfoLine("Резервный VK-хеш", secretPresenceLabel(localAdminProfile.secondaryVkHash))
+ InfoLine("Порты", localAdminProfile.ports)
+ InfoLine("Потоки", localAdminProfile.workersPerHash.toString())
+ InfoLine("Протокол", localAdminProfile.protocol)
+ InfoLine("SNI", localAdminProfile.sni.ifBlank { "не задан" })
+ InfoLine("No DNS", if (localAdminProfile.noDns) "включено" else "выключено")
+ Text(
+ "Это обзор без редактирования и отдельного сохранения. Чтобы изменить профиль владельца, заполните поля во вкладках «Туннель» и «Деплой», затем нажмите «Установить» и подтвердите установку с сохранением данных или с нуля.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ ServerToolsStep.Network -> {
+ Text("Настройки ссылок и клиентов", fontWeight = FontWeight.Bold)
+ OutlinedTextField(
+ value = dns,
+ onValueChange = { dns = it.take(260) },
+ label = { Text("DNS") },
+ supportingText = { Text("Применится к новым конфигам клиентов") },
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = limitText,
+ onValueChange = { limitText = it.filter(Char::isDigit).take(3) },
+ label = { Text("Лимит клиентов") },
+ singleLine = true,
+ isError = limit == null || limit !in 1..500,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = ports,
+ onValueChange = { ports = it.filter { ch -> ch.isDigit() || ch == ',' }.take(32) },
+ label = { Text("Порты новых ссылок") },
+ supportingText = { Text("Реальные порты службы не меняются") },
+ singleLine = true,
+ isError = !ports.isPortsSpec(),
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = publicHost,
+ onValueChange = { publicHost = it.trim().take(253) },
+ label = { Text("Адрес сервера для ссылок") },
+ supportingText = { Text("Укажите домен или IP. Пустое поле означает автоматическое определение публичного IP") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ if (publicHost.isNotBlank() || state.publicHost.isBlank()) {
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ if (publicHost.isNotBlank()) {
+ OutlinedButton(onClick = { publicHost = "" }, enabled = !busy) {
+ Text("Определять автоматически")
+ }
+ } else {
+ OutlinedButton(onClick = onRefreshIp, enabled = !busy) {
+ Icon(Icons.Default.Refresh, null, Modifier.size(18.dp))
+ Text(" Проверить текущий IP")
+ }
+ }
+ }
+ }
+ if (publicHost.isBlank() && state.publicHost.isNotBlank()) {
+ Text(
+ "Нажмите «Сохранить», чтобы включить автоматическое определение.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+ ServerToolsStep.Maintenance -> {
+ Text("Обслуживание", fontWeight = FontWeight.Bold)
+ if (state.expiredCount > 0) {
+ Text("Истёкшие доступы", fontWeight = FontWeight.Bold)
+ state.clients.filter { it.status == "expired" }.take(12).forEach { client ->
+ Text("• ${client.title} · ${client.maskedPassword().removePrefix("Пароль: ")}", style = MaterialTheme.typography.bodySmall)
+ }
+ if (state.expiredCount > 12) Text("…и ещё ${state.expiredCount - 12}", style = MaterialTheme.typography.bodySmall)
+ }
+ OutlinedButton(onClick = onCleanupExpired, enabled = !busy && state.expiredCount > 0, modifier = Modifier.fillMaxWidth()) { Text("Истёкшие · ${state.expiredCount}") }
+ if (state.orphanDeviceCount > 0) {
+ Text("Забытые устройства", fontWeight = FontWeight.Bold)
+ state.orphanDevices.take(12).forEach { device ->
+ Text("• ${device.name.ifBlank { device.deviceId }} · ${device.ip.ifBlank { "без IP" }}", style = MaterialTheme.typography.bodySmall)
+ }
+ if (state.orphanDeviceCount > 12) Text("…и ещё ${state.orphanDeviceCount - 12}", style = MaterialTheme.typography.bodySmall)
+ }
+ OutlinedButton(onClick = onCleanupOrphans, enabled = !busy && state.orphanDeviceCount > 0, modifier = Modifier.fillMaxWidth()) { Text("Забытые устройства · ${state.orphanDeviceCount}") }
+ OutlinedButton(onClick = onResetTraffic, enabled = !busy, modifier = Modifier.fillMaxWidth()) { Text("Сбросить трафик") }
+ OutlinedButton(
+ onClick = onRestart,
+ enabled = !busy,
+ modifier = Modifier.fillMaxWidth(),
+ colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error)
+ ) { Text("Перезапустить WDTT") }
+ Text("Перезапуск нужен только после обновления бинарника или системных параметров. Управление клиентами работает без него.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ }
+ }
+ }
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ ServerToolsStep.entries.forEach { page ->
+ SelectButton(
+ text = when (page) {
+ ServerToolsStep.Overview -> "Обзор"
+ ServerToolsStep.Owner -> "Владелец"
+ ServerToolsStep.Network -> "Настройки"
+ ServerToolsStep.Maintenance -> "Сервис"
+ },
+ selected = step == page,
+ onClick = { step = page }
+ )
+ }
+ }
+ }
+ },
+ confirmButton = {
+ when (step) {
+ ServerToolsStep.Network -> {
+ Button(onClick = { onSaveNetwork(dns, limit ?: 0, ports, publicHost) }, enabled = !busy && networkValid) { Text("Сохранить") }
+ }
+ else -> Unit
+ }
+ }
+ )
+}
+
+@Composable
+private fun InfoLine(label: String, value: String) {
+ Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ Text(label, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text(value, style = MaterialTheme.typography.bodyMedium)
+ }
+}
+
+@Composable
+private fun TrafficPeriodBlock(traffic: ServerTrafficPeriod) {
+ InfoLine("Сегодня", formatTrafficPair(traffic.today.down, traffic.today.up))
+ InfoLine("7 дней", formatTrafficPair(traffic.week.down, traffic.week.up))
+ InfoLine("30 дней", formatTrafficPair(traffic.month.down, traffic.month.up))
+ InfoLine("Всего", formatTrafficPair(traffic.all.down, traffic.all.up))
+}
+
+@Composable
+private fun StatusChip(status: String) {
+ val context = LocalContext.current
+ val label = when (status) {
+ "active" -> "Активен"
+ "expired" -> "Истёк"
+ "deactivated" -> "Откл."
+ else -> status.ifBlank { "?" }
+ }
+ Surface(
+ onClick = { Toast.makeText(context, "Статус: $label", Toast.LENGTH_SHORT).show() },
+ shape = CircleShape,
+ color = when (status) {
+ "active" -> MaterialTheme.colorScheme.primaryContainer
+ "deactivated" -> MaterialTheme.colorScheme.tertiaryContainer
+ "expired" -> MaterialTheme.colorScheme.errorContainer
+ else -> MaterialTheme.colorScheme.surfaceVariant
+ },
+ contentColor = when (status) {
+ "active" -> MaterialTheme.colorScheme.onPrimaryContainer
+ "deactivated" -> MaterialTheme.colorScheme.onTertiaryContainer
+ "expired" -> MaterialTheme.colorScheme.onErrorContainer
+ else -> MaterialTheme.colorScheme.onSurfaceVariant
+ },
+ modifier = Modifier.size(30.dp)
+ ) {
+ Box(contentAlignment = Alignment.Center) {
+ Icon(
+ imageVector = when (status) {
+ "active" -> Icons.Default.CheckCircle
+ "deactivated" -> Icons.Default.PauseCircle
+ "expired" -> Icons.Default.Close
+ else -> Icons.Default.CheckCircle
+ },
+ contentDescription = "Статус: $label",
+ modifier = Modifier.size(17.dp)
+ )
+ }
+ }
+}
+
+@Composable
+private fun ClientStatusBanner(status: String, busy: Boolean) {
+ val isError = status.startsWith("Ошибка")
+ val containerColor = when {
+ isError -> MaterialTheme.colorScheme.errorContainer
+ busy -> MaterialTheme.colorScheme.secondaryContainer
+ else -> MaterialTheme.colorScheme.primaryContainer
+ }
+ val contentColor = when {
+ isError -> MaterialTheme.colorScheme.onErrorContainer
+ busy -> MaterialTheme.colorScheme.onSecondaryContainer
+ else -> MaterialTheme.colorScheme.onPrimaryContainer
+ }
+ Surface(
+ modifier = Modifier.fillMaxWidth(),
+ shape = RoundedCornerShape(18.dp),
+ color = containerColor,
+ contentColor = contentColor,
+ tonalElevation = 1.dp,
+ shadowElevation = 0.dp
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 10.dp),
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ if (busy) {
+ CircularProgressIndicator(
+ modifier = Modifier.size(16.dp),
+ color = contentColor,
+ strokeWidth = 2.dp
+ )
+ }
+ Text(
+ status,
+ style = MaterialTheme.typography.bodySmall,
+ fontWeight = FontWeight.SemiBold,
+ modifier = Modifier.weight(1f)
+ )
+ }
+ }
+}
+
+@Composable
+private fun ClientPanel(
+ modifier: Modifier = Modifier,
+ contentPadding: PaddingValues = PaddingValues(12.dp),
+ content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit
+) {
+ Surface(
+ modifier = modifier.fillMaxWidth(),
+ shape = RoundedCornerShape(22.dp),
+ color = MaterialTheme.colorScheme.surface.copy(alpha = 0.48f),
+ contentColor = MaterialTheme.colorScheme.onSurface,
+ border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.14f)),
+ tonalElevation = 0.dp,
+ shadowElevation = 0.dp
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(contentPadding),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ content = content
+ )
+ }
+}
+
+@Composable
+private fun SwipeHint(
+ selectedIndex: Int,
+ count: Int,
+ modifier: Modifier = Modifier
+) {
+ Row(
+ modifier = modifier,
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Icon(
+ Icons.Default.ChevronLeft,
+ contentDescription = null,
+ modifier = Modifier.size(18.dp),
+ tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = if (selectedIndex > 0) 0.9f else 0.28f)
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
+ repeat(count.coerceAtMost(7)) { dot ->
+ val active = when {
+ count <= 7 -> dot == selectedIndex
+ selectedIndex <= 3 -> dot == selectedIndex
+ selectedIndex >= count - 4 -> dot == 7 - (count - selectedIndex)
+ else -> dot == 3
+ }
+ Box(
+ modifier = Modifier
+ .size(if (active) 8.dp else 6.dp)
+ .background(
+ color = if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.42f),
+ shape = CircleShape
+ )
+ )
+ }
+ }
+ Text(
+ "${selectedIndex + 1}/$count",
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Icon(
+ Icons.Default.ChevronRight,
+ contentDescription = null,
+ modifier = Modifier.size(18.dp),
+ tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = if (selectedIndex < count - 1) 0.9f else 0.28f)
+ )
+ }
+}
+
+@Composable
+private fun DialogTitle(
+ title: String,
+ onDismiss: () -> Unit,
+ enabled: Boolean = true
+) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text(
+ title,
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f)
+ )
+ IconButton(onClick = onDismiss, enabled = enabled, modifier = Modifier.size(32.dp)) {
+ Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
+ }
+ }
+}
+
+@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
+@Composable
+private fun CreateClientWizardDialog(
+ defaultPorts: String,
+ busy: Boolean,
+ onDismiss: () -> Unit,
+ onCreate: (ServerClientCreateRequest) -> Unit
+) {
+ var step by rememberSaveable { mutableStateOf(ClientWizardStep.Days) }
+ var days by rememberSaveable { mutableStateOf(30) }
+ var label by rememberSaveable { mutableStateOf("") }
+ var vkHash by rememberSaveable { mutableStateOf("") }
+ var useDefaultPorts by rememberSaveable { mutableStateOf(true) }
+ var customPorts by rememberSaveable { mutableStateOf(defaultPorts) }
+ val effectivePorts = if (useDefaultPorts) defaultPorts else customPorts
+ val portsValid = effectivePorts.isPortsSpec()
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { DialogTitle("Новый клиент", onDismiss, enabled = !busy) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Text(
+ "Шаг ${step.ordinal + 1} из ${ClientWizardStep.entries.size}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Card(
+ modifier = Modifier.fillMaxWidth(),
+ shape = RoundedCornerShape(18.dp),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f))
+ ) {
+ Column(modifier = Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ when (step) {
+ ClientWizardStep.Days -> {
+ Text("Срок доступа", fontWeight = FontWeight.Bold)
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ listOf(7, 30, 90, 365).forEach { value ->
+ SelectButton(
+ text = "${value}д",
+ selected = days == value,
+ onClick = { days = value }
+ )
+ }
+ SelectButton(text = "∞", selected = days == 0, onClick = { days = 0 })
+ }
+ OutlinedTextField(
+ value = if (days == 0) "" else days.toString(),
+ onValueChange = { input ->
+ val parsed = input.filter { it.isDigit() }.take(3).toIntOrNull()
+ if (parsed != null) days = parsed.coerceIn(1, 365)
+ },
+ label = { Text("Свои дни") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ ClientWizardStep.Label -> {
+ Text("Название", fontWeight = FontWeight.Bold)
+ Text("Короткая метка для списка: друг, дом, ноутбук. Можно оставить пустой.", style = MaterialTheme.typography.bodySmall)
+ OutlinedTextField(
+ value = label,
+ onValueChange = { label = it.take(40) },
+ label = { Text("Название") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ ClientWizardStep.Hash -> {
+ Text("VK-хеш", fontWeight = FontWeight.Bold)
+ Text("Нужен для быстрой ссылки, QR и файла. Можно вставить сам хеш или ссылку приглашения.", style = MaterialTheme.typography.bodySmall)
+ OutlinedTextField(
+ value = vkHash,
+ onValueChange = { vkHash = it },
+ label = { Text("Хеш или ссылка") },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ ClientWizardStep.Ports -> {
+ Text("Порты ссылки", fontWeight = FontWeight.Bold)
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ SelectButton("Стандарт", useDefaultPorts) { useDefaultPorts = true }
+ SelectButton("Свои", !useDefaultPorts) { useDefaultPorts = false }
+ }
+ OutlinedTextField(
+ value = customPorts,
+ onValueChange = { customPorts = it.filter { ch -> ch.isDigit() || ch == ',' }.take(32) },
+ label = { Text("DTLS,WG,TUN") },
+ singleLine = true,
+ enabled = !useDefaultPorts,
+ isError = !portsValid,
+ modifier = Modifier.fillMaxWidth()
+ )
+ if (!portsValid) Text("Формат: 56000,56001,9000", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
+ }
+ ClientWizardStep.Confirm -> {
+ Text("Проверка", fontWeight = FontWeight.Bold)
+ Text("Срок: ${if (days == 0) "бессрочно" else "$days дн."}")
+ Text("Название: ${label.ifBlank { "без имени" }}")
+ Text("VK-хеш: ${if (vkHash.isBlank()) "не задан" else "задан"}")
+ Text("Порты: $effectivePorts")
+ Text(
+ "Новый доступ начнёт работать сразу, текущие подключения не прервутся.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+ }
+ }
+ }
+ },
+ confirmButton = {
+ Button(
+ enabled = !busy && (step != ClientWizardStep.Ports || portsValid),
+ onClick = {
+ if (step == ClientWizardStep.Confirm) {
+ onCreate(
+ ServerClientCreateRequest(
+ days = days.coerceIn(0, 365),
+ label = label,
+ vkHash = vkHash,
+ ports = effectivePorts
+ )
+ )
+ } else {
+ step = ClientWizardStep.entries[step.ordinal + 1]
+ }
+ }
+ ) {
+ Text(if (step == ClientWizardStep.Confirm) "Создать" else "Далее")
+ }
+ },
+ dismissButton = {
+ Row {
+ if (step != ClientWizardStep.Days) {
+ TextButton(onClick = { step = ClientWizardStep.entries[step.ordinal - 1] }, enabled = !busy) {
+ Text("Назад")
+ }
+ }
+ }
+ }
+ )
+}
+
+@Composable
+private fun SelectButton(
+ text: String,
+ selected: Boolean,
+ enabled: Boolean = true,
+ modifier: Modifier = Modifier,
+ onClick: () -> Unit
+) {
+ if (selected) {
+ Button(onClick = onClick, enabled = enabled, modifier = modifier, contentPadding = PaddingValues(horizontal = 14.dp)) { Text(text) }
+ } else {
+ OutlinedButton(onClick = onClick, enabled = enabled, modifier = modifier, contentPadding = PaddingValues(horizontal = 14.dp)) { Text(text) }
+ }
+}
+
+@Composable
+private fun ConfirmClientActionDialog(
+ action: PendingClientAction,
+ onDismiss: () -> Unit,
+ onConfirm: () -> Unit
+) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { DialogTitle(action.confirmLabel, onDismiss) },
+ text = { Text(action.message) },
+ confirmButton = {
+ Button(
+ onClick = onConfirm,
+ colors = if (action.danger) {
+ ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error, contentColor = MaterialTheme.colorScheme.onError)
+ } else {
+ ButtonDefaults.buttonColors()
+ }
+ ) { Text(action.confirmLabel) }
+ },
+ dismissButton = { TextButton(onClick = onDismiss) { Text("Нет") } }
+ )
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun ExtendClientDialog(
+ client: ServerClientInfo,
+ onDismiss: () -> Unit,
+ onSelect: (Int) -> Unit
+) {
+ var customDays by rememberSaveable { mutableStateOf("") }
+ val parsedDays = customDays.toIntOrNull()?.takeIf { it in 1..365 }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { DialogTitle("Продлить", onDismiss) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text("Новый срок для «${client.displayName()}» от текущего момента.")
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ listOf(7, 30, 90, 365).forEach { days ->
+ OutlinedButton(onClick = { onSelect(days) }) { Text("${days}д") }
+ }
+ OutlinedButton(onClick = { onSelect(0) }) { Text("∞") }
+ }
+ OutlinedTextField(
+ value = customDays,
+ onValueChange = { customDays = it.filter(Char::isDigit).take(3) },
+ label = { Text("Свой срок, 1–365 дней") },
+ singleLine = true,
+ isError = customDays.isNotEmpty() && parsedDays == null,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ },
+ confirmButton = { Button(onClick = { parsedDays?.let(onSelect) }, enabled = parsedDays != null) { Text("Применить") } }
+ )
+}
+
+@Composable
+private fun ClientQrDialog(
+ title: String,
+ bitmap: Bitmap,
+ onDismiss: () -> Unit,
+ onShare: () -> Unit,
+ onSave: () -> Unit
+) {
+ val context = LocalContext.current
+ val permissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
+ if (granted) onSave()
+ else Toast.makeText(context, "Без разрешения Android 9 не может сохранить QR-код.", Toast.LENGTH_LONG).show()
+ }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
+ IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) {
+ Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
+ }
+ }
+ 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)
+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedButton(
+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
+ contentPadding = PaddingValues(horizontal = 8.dp),
+ onClick = {
+ if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P &&
+ ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
+ ) {
+ permissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ } else {
+ onSave()
+ }
+ }
+ ) {
+ Icon(Icons.Default.SaveAlt, null, Modifier.size(18.dp))
+ Text(" Сохранить", maxLines = 1)
+ }
+ Button(
+ onClick = onShare,
+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
+ contentPadding = PaddingValues(horizontal = 8.dp)
+ ) {
+ Icon(Icons.Default.Share, null, Modifier.size(18.dp))
+ Text(" Поделиться", maxLines = 1)
+ }
+ }
+ }
+ },
+ confirmButton = {}
+ )
+}
+
+private fun ServerClientInfo.maskedPassword(): String =
+ if (password.length <= 8) "Пароль: ••••" else "Пароль: ${password.take(3)}••••${password.takeLast(3)}"
+
+private fun ServerClientInfo.displayName(): String =
+ label.ifBlank { "Без имени" }
+
+private fun ServerClientInfo.safeFileName(): String =
+ listOf(
+ label,
+ deviceName,
+ device?.name.orEmpty(),
+ listOf(device?.manufacturer.orEmpty(), device?.model.orEmpty()).filter { it.isNotBlank() }.joinToString(" ")
+ ).firstOrNull { it.isNotBlank() }.orEmpty().toSafeFilePart("client")
+
+private fun String.safeQrFileName(): String =
+ toSafeFilePart("qr")
+
+private fun String.toSafeFilePart(fallback: String): String =
+ replace(Regex("[^\\p{L}\\p{N}._-]+"), "-")
+ .replace(Regex("-+"), "-")
+ .trim('_', '.', '-')
+ .take(48)
+ .trim('_', '.', '-')
+ .ifBlank { fallback }
+
+private fun formatExtensionPeriod(days: Int): String =
+ if (days <= 0) {
+ "бессрочно"
+ } else {
+ "на $days ${days.pluralRu("день", "дня", "дней")}"
+ }
+
+private fun Int.pluralRu(one: String, few: String, many: String): String {
+ val mod100 = this % 100
+ val mod10 = this % 10
+ return when {
+ mod100 in 11..14 -> many
+ mod10 == 1 -> one
+ mod10 in 2..4 -> few
+ else -> many
+ }
+}
+
+private data class ClientSearchResult(
+ val client: ServerClientInfo,
+ val score: Int,
+ val index: Int
+)
+
+private fun List.filterByQuery(query: String): List {
+ val normalized = query.searchNormalize()
+ val compact = query.searchCompact()
+ if (normalized.isBlank()) return this
+ return mapIndexedNotNull { index, client ->
+ client.searchScore(normalized, compact)?.let { score ->
+ ClientSearchResult(client = client, score = score, index = index)
+ }
+ }.sortedWith(
+ compareByDescending { it.score }
+ .thenBy { it.index }
+ ).map { it.client }
+}
+
+private fun List.filterByClientFilters(
+ statusFilter: ClientStatusFilter,
+ bindingFilter: ClientBindingFilter,
+ expiryFilter: ClientExpiryFilter,
+ vkHashFilter: ClientVkHashFilter
+): List {
+ val now = System.currentTimeMillis() / 1000L
+ return filter { client ->
+ client.matchesStatusFilter(statusFilter) &&
+ client.matchesBindingFilter(bindingFilter) &&
+ client.matchesExpiryFilter(expiryFilter, now) &&
+ client.matchesVkHashFilter(vkHashFilter)
+ }
+}
+
+private fun activeClientFilterCount(
+ statusFilter: ClientStatusFilter,
+ bindingFilter: ClientBindingFilter,
+ expiryFilter: ClientExpiryFilter,
+ vkHashFilter: ClientVkHashFilter
+): Int =
+ listOf(
+ statusFilter != ClientStatusFilter.All,
+ bindingFilter != ClientBindingFilter.All,
+ expiryFilter != ClientExpiryFilter.All,
+ vkHashFilter != ClientVkHashFilter.All
+ ).count { it }
+
+private fun ServerClientInfo.matchesStatusFilter(filter: ClientStatusFilter): Boolean =
+ when (filter) {
+ ClientStatusFilter.All -> true
+ ClientStatusFilter.Active -> isActive
+ ClientStatusFilter.Disabled -> !isActive
+ }
+
+private fun ServerClientInfo.matchesBindingFilter(filter: ClientBindingFilter): Boolean =
+ when (filter) {
+ ClientBindingFilter.All -> true
+ ClientBindingFilter.Bound -> isBound
+ ClientBindingFilter.Unbound -> !isBound
+ }
+
+private fun ServerClientInfo.matchesExpiryFilter(filter: ClientExpiryFilter, now: Long): Boolean =
+ when (filter) {
+ ClientExpiryFilter.All -> true
+ ClientExpiryFilter.Valid -> expiresAt <= 0 || expiresAt >= now
+ ClientExpiryFilter.Expired -> expiresAt > 0 && expiresAt < now
+ ClientExpiryFilter.Unlimited -> expiresAt <= 0
+ }
+
+private fun ServerClientInfo.matchesVkHashFilter(filter: ClientVkHashFilter): Boolean =
+ when (filter) {
+ ClientVkHashFilter.All -> true
+ ClientVkHashFilter.Present -> vkHash.isNotBlank()
+ ClientVkHashFilter.Missing -> vkHash.isBlank()
+ }
+
+private fun ServerClientInfo.searchScore(query: String, compactQuery: String): Int? {
+ val device = device
+ val fields = buildList {
+ addSearchField(label, weight = 1_000)
+ addSearchField(title, weight = 980)
+ addSearchField(displayName(), weight = 940)
+ addSearchField(deviceName, weight = 820)
+ addSearchField(device?.name.orEmpty(), weight = 800)
+ addSearchField(device?.model.orEmpty(), weight = 760)
+ addSearchField(device?.brand.orEmpty(), weight = 740)
+ addSearchField(device?.manufacturer.orEmpty(), weight = 720)
+ addSearchField(password, weight = 620, minQueryLength = 2)
+ addSearchField(vkHash, weight = 560, minQueryLength = 3)
+ addSearchField(ports, weight = 520, minQueryLength = 2)
+ addSearchField(device?.appVersion.orEmpty(), weight = 420, minQueryLength = 2)
+ addSearchField(device?.androidVersion.orEmpty(), weight = 380, minQueryLength = 2)
+ addSearchField(device?.locale.orEmpty(), weight = 340, minQueryLength = 2)
+ addSearchField(device?.country.orEmpty(), weight = 320, minQueryLength = 2)
+ addSearchField(deviceId, weight = 90, minQueryLength = 4)
+ addSearchField(deviceIp, weight = 80, minQueryLength = 4)
+ addSearchField(device?.timeZone.orEmpty(), weight = 70, minQueryLength = 4)
+ addSearchField(device?.remoteIp.orEmpty(), weight = 60, minQueryLength = 4)
+ }
+ return fields.maxOfOrNull { it.matchScore(query, compactQuery) ?: 0 }?.takeIf { it > 0 }
+}
+
+private data class ClientSearchField(
+ val value: String,
+ val weight: Int,
+ val minQueryLength: Int
+)
+
+private fun MutableList.addSearchField(
+ value: String,
+ weight: Int,
+ minQueryLength: Int = 1
+) {
+ if (value.isNotBlank()) add(ClientSearchField(value, weight, minQueryLength))
+}
+
+private fun ClientSearchField.matchScore(query: String, compactQuery: String): Int? {
+ if (query.length < minQueryLength) return null
+ val normalized = value.searchNormalize()
+ if (normalized.isBlank()) return null
+ val compact = value.searchCompact()
+ return when {
+ normalized == query -> weight + 500
+ normalized.startsWith(query) -> weight + 420
+ normalized.wordStartsWith(query) -> weight + 360
+ normalized.contains(query) -> weight + 220
+ compactQuery.isNotBlank() && compact == compactQuery -> weight + 180
+ compactQuery.isNotBlank() && compact.startsWith(compactQuery) -> weight + 130
+ compactQuery.isNotBlank() && compact.contains(compactQuery) -> weight + 80
+ else -> null
+ }
+}
+
+private fun String.wordStartsWith(query: String): Boolean =
+ split(Regex("[\\s_.,;:()\\[\\]{}<>/\\\\|+\\-]+")).any { it.startsWith(query) }
+
+private fun String.searchNormalize(): String =
+ trim().lowercase(Locale.getDefault()).replace('ё', 'е')
+
+private fun String.searchCompact(): String =
+ searchNormalize().filter { it.isLetterOrDigit() }
+
+private fun formatExpiry(ts: Long): String {
+ if (ts <= 0) return "бессрочно"
+ val now = System.currentTimeMillis() / 1000L
+ val date = SimpleDateFormat("dd.MM.yyyy", Locale.getDefault()).format(Date(ts * 1000L))
+ if (ts < now) return "истёк $date"
+ val days = ((ts - now) / 86_400L).coerceAtLeast(0)
+ return "$date · ${days}д"
+}
+
+private fun formatBytes(value: Long): String {
+ val mb = value / 1024.0 / 1024.0
+ return if (mb < 1024) String.format(Locale.US, "%.1f МБ", mb) else String.format(Locale.US, "%.2f ГБ", mb / 1024.0)
+}
+
+private fun formatTrafficPair(down: Long, up: Long): String =
+ "↓ ${formatBytes(down)} · ↑ ${formatBytes(up)}"
+
+private fun formatDateTime(ts: Long): String {
+ if (ts <= 0) return "неизвестно"
+ return SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault()).format(Date(ts * 1000L))
+}
+
+private fun secretPresenceLabel(value: String): String {
+ val count = value.split(',', ' ', '\n', '\t')
+ .map { it.trim() }
+ .count { it.isNotBlank() }
+ return if (count == 0) "не заданы" else "заданы ($count)"
+}
+
+private fun String.isPortsSpec(): Boolean {
+ val parts = split(",").map { it.trim().toIntOrNull() }
+ return parts.size == 3 && parts.all { it != null && it in 1..65535 }
+}
+
+private fun shareText(context: Context, text: String) {
+ val intent = Intent(Intent.ACTION_SEND).apply {
+ type = "text/plain"
+ putExtra(Intent.EXTRA_TEXT, text)
+ }
+ context.startActivity(Intent.createChooser(intent, "Передать подключение WDTT Plus"))
+}
+
+private fun copyText(context: Context, label: String, text: String) {
+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
+ clipboard.setPrimaryClip(ClipData.newPlainText(label, text))
+ Toast.makeText(context, "Скопировано.", Toast.LENGTH_SHORT).show()
+}
+
+private fun shareUri(context: Context, uri: Uri, mimeType: String, title: String) {
+ val intent = Intent(Intent.ACTION_SEND).apply {
+ type = mimeType
+ putExtra(Intent.EXTRA_STREAM, uri)
+ clipData = ClipData.newUri(context.contentResolver, title, uri)
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ context.startActivity(Intent.createChooser(intent, title))
+}
diff --git a/app/src/main/java/com/wdtt/plus/ui/ServerClientsViewModel.kt b/app/src/main/java/com/wdtt/plus/ui/ServerClientsViewModel.kt
new file mode 100644
index 0000000..99b08ea
--- /dev/null
+++ b/app/src/main/java/com/wdtt/plus/ui/ServerClientsViewModel.kt
@@ -0,0 +1,13 @@
+package com.wdtt.plus.ui
+
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.lifecycle.ViewModel
+import com.wdtt.plus.ServerAdminState
+
+class ServerClientsViewModel : ViewModel() {
+ val serverState = mutableStateOf(null)
+ val clientSearch = mutableStateOf("")
+ val selectedClientIndex = mutableIntStateOf(0)
+ var targetKey: String = ""
+}
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 4395cd1..9504941 100644
--- a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt
+++ b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt
@@ -90,7 +90,9 @@ private fun isValidTunnelHost(value: String): Boolean {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
-fun SettingsTab() {
+fun SettingsTab(
+ scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
+) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
@@ -99,13 +101,18 @@ fun SettingsTab() {
CompositionLocalProvider(
LocalDensity provides Density(currentDensity.density, fontScale = 1f)
) {
- SettingsTabContent(context, scope, settingsStore)
+ SettingsTabContent(context, scope, settingsStore, scrollPosition)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
-fun SettingsTabContent(context: android.content.Context, scope: kotlinx.coroutines.CoroutineScope, settingsStore: SettingsStore) {
+fun SettingsTabContent(
+ context: android.content.Context,
+ scope: kotlinx.coroutines.CoroutineScope,
+ settingsStore: SettingsStore,
+ scrollPosition: MutableIntState
+) {
val savedConnectionPassword by settingsStore.connectionPassword.collectAsStateWithLifecycle(initialValue = "")
val savedManualPortsEnabled by settingsStore.manualPortsEnabled.collectAsStateWithLifecycle(initialValue = false)
val savedServerDtlsPort by settingsStore.serverDtlsPort.collectAsStateWithLifecycle(initialValue = 56000)
@@ -288,7 +295,7 @@ fun SettingsTabContent(context: android.content.Context, scope: kotlinx.coroutin
}
}
- val scrollState = rememberScrollState()
+ val scrollState = rememberRememberedScrollState(scrollPosition)
val isPeerValid = isValidTunnelHost(peerInput)
val isHashesValid = combinedHashes.isNotBlank()
diff --git a/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt b/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt
new file mode 100644
index 0000000..62c2c7a
--- /dev/null
+++ b/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt
@@ -0,0 +1,506 @@
+package com.wdtt.plus.ui
+
+import android.Manifest
+import android.content.ClipData
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.graphics.Bitmap
+import android.net.Uri
+import android.os.Build
+import android.widget.Toast
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
+import androidx.compose.material.icons.filled.CameraAlt
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.FileOpen
+import androidx.compose.material.icons.filled.Image
+import androidx.compose.material.icons.filled.QrCode2
+import androidx.compose.material.icons.filled.SaveAlt
+import androidx.compose.material.icons.filled.Share
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+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.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.text.input.VisualTransformation
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.window.DialogProperties
+import androidx.core.content.ContextCompat
+import com.journeyapps.barcodescanner.ScanContract
+import com.journeyapps.barcodescanner.ScanOptions
+import com.wdtt.plus.SettingsStore
+import com.wdtt.plus.TransferFiles
+import com.wdtt.plus.WdttTransferCodec
+import com.wdtt.plus.QrCaptureActivity
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+private enum class AdminExportAction { Qr, File }
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+fun TransferCenterDialog(
+ settingsStore: SettingsStore,
+ activeProfile: Int,
+ isAdmin: Boolean,
+ onIncomingContent: (String) -> Unit,
+ onDismiss: () -> Unit
+) {
+ val context = androidx.compose.ui.platform.LocalContext.current
+ val scope = rememberCoroutineScope()
+ var busy by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf(null) }
+ var qrData by remember { mutableStateOf?>(null) }
+ var adminAction by remember { mutableStateOf(null) }
+
+ fun runCatchingUi(block: suspend () -> Unit) {
+ busy = true
+ error = null
+ scope.launch {
+ runCatching { block() }
+ .onFailure { error = it.message ?: "Не удалось выполнить передачу." }
+ busy = false
+ }
+ }
+
+ val cameraLauncher = rememberLauncherForActivityResult(ScanContract()) { result ->
+ result.contents?.takeIf { it.isNotBlank() }?.let(onIncomingContent)
+ }
+ val galleryLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
+ if (uri != null) runCatchingUi {
+ val text = withContext(Dispatchers.IO) { TransferFiles.decodeQrImage(context, uri) }
+ onIncomingContent(text)
+ }
+ }
+ val fileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
+ if (uri != null) runCatchingUi {
+ val text = withContext(Dispatchers.IO) { TransferFiles.readText(context, uri) }
+ onIncomingContent(text)
+ }
+ }
+
+ AlertDialog(
+ onDismissRequest = { if (!busy) onDismiss() },
+ properties = DialogProperties(usePlatformDefaultWidth = false),
+ modifier = Modifier.fillMaxWidth(0.94f),
+ text = {
+ Column(
+ modifier = Modifier.verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Box(modifier = Modifier.fillMaxWidth()) {
+ IconButton(
+ onClick = onDismiss,
+ enabled = !busy,
+ modifier = Modifier.align(androidx.compose.ui.Alignment.CenterEnd).size(32.dp)
+ ) {
+ Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
+ }
+ }
+ Text("Получение VPN", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ TransferButton("Камера", Icons.Default.CameraAlt, busy) {
+ cameraLauncher.launch(
+ ScanOptions()
+ .setDesiredBarcodeFormats(ScanOptions.QR_CODE)
+ .setPrompt("Наведите камеру на QR-код WDTT Plus")
+ .setBeepEnabled(false)
+ .setCaptureActivity(QrCaptureActivity::class.java)
+ .setOrientationLocked(false)
+ )
+ }
+ TransferButton("Галерея", Icons.Default.Image, busy) { galleryLauncher.launch("image/*") }
+ TransferButton("Файл", Icons.Default.FileOpen, busy) { fileLauncher.launch("*/*") }
+ }
+
+ HorizontalDivider()
+ Text("Передача VPN ${activeProfile + 1}", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
+ Text(
+ "Ссылка содержит пароль подключения и VK-хеши. Передавайте её только тому, кому доверяете.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ TransferButton("QR", Icons.Default.QrCode2, busy) {
+ runCatchingUi {
+ val link = settingsStore.connectionLinkForProfile(activeProfile)
+ val bitmap = withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) }
+ qrData = "VPN ${activeProfile + 1}" to bitmap
+ }
+ }
+ TransferButton("Ссылка", Icons.Default.Share, busy) {
+ runCatchingUi {
+ shareText(context, settingsStore.connectionLinkForProfile(activeProfile))
+ }
+ }
+ TransferButton("Файл", Icons.AutoMirrored.Filled.InsertDriveFile, busy) {
+ runCatchingUi {
+ val link = settingsStore.connectionLinkForProfile(activeProfile)
+ val uri = withContext(Dispatchers.IO) {
+ TransferFiles.writeTransferText(context, "WDTT-Plus-VPN-${activeProfile + 1}.wdtt", link)
+ }
+ shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus")
+ }
+ }
+ }
+
+ if (isAdmin) {
+ HorizontalDivider()
+ Text("Настройки администратора", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
+ Text(
+ "Все три VPN-профиля, параметры деплоя, пароли, токен бота, исключения и настройки выхода. Данные шифруются указанным паролем.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedButton(
+ onClick = { adminAction = AdminExportAction.Qr },
+ enabled = !busy,
+ modifier = Modifier.weight(1f)
+ ) {
+ Icon(Icons.Default.QrCode2, null, Modifier.size(18.dp))
+ Text(" QR")
+ }
+ OutlinedButton(
+ onClick = { adminAction = AdminExportAction.File },
+ enabled = !busy,
+ modifier = Modifier.weight(1f)
+ ) {
+ Icon(Icons.AutoMirrored.Filled.InsertDriveFile, null, Modifier.size(18.dp))
+ Text(" Файл")
+ }
+ }
+ }
+
+ error?.let {
+ Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
+ }
+ if (busy) Text("Подготавливаю…", style = MaterialTheme.typography.bodySmall)
+ }
+ },
+ confirmButton = {}
+ )
+
+ adminAction?.let { action ->
+ AdminExportPasswordDialog(
+ onDismiss = { adminAction = null },
+ onConfirm = { password ->
+ adminAction = null
+ runCatchingUi {
+ val plain = settingsStore.exportAdminSettings()
+ val encrypted = try {
+ withContext(Dispatchers.Default) {
+ WdttTransferCodec.encryptAdminSettings(plain, password)
+ }
+ } finally {
+ password.fill('\u0000')
+ }
+ when (action) {
+ AdminExportAction.Qr -> {
+ val bitmap = withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, encrypted) }
+ qrData = "Настройки администратора" to bitmap
+ }
+ AdminExportAction.File -> {
+ val stamp = SimpleDateFormat("yyyyMMdd-HHmm", Locale.US).format(Date())
+ 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")
+ }
+ }
+ }
+ }
+ )
+ }
+
+ qrData?.let { (title, bitmap) ->
+ QrDisplayDialog(
+ title = title,
+ bitmap = bitmap,
+ onDismiss = { qrData = null },
+ onShare = {
+ runCatchingUi {
+ val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
+ val fileName = "WDTT-Plus-QR-${title.safeQrFileName()}-$stamp.png"
+ val uri = withContext(Dispatchers.IO) {
+ TransferFiles.writeQrPng(context, fileName, bitmap)
+ }
+ shareUri(context, uri, "image/png", "Передать QR-код WDTT Plus")
+ }
+ },
+ onSave = {
+ scope.launch {
+ val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
+ runCatching {
+ withContext(Dispatchers.IO) {
+ TransferFiles.saveQrToGallery(context, "WDTT-Plus-QR-$stamp.png", bitmap)
+ }
+ }.onSuccess {
+ Toast.makeText(context, "QR-код сохранён в галерею.", Toast.LENGTH_SHORT).show()
+ }.onFailure {
+ Toast.makeText(context, it.message ?: "Не удалось сохранить QR-код.", Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+ )
+ }
+}
+
+@Composable
+fun AdminImportDialog(
+ settingsStore: SettingsStore,
+ encryptedDocument: String,
+ onFinished: (String) -> Unit,
+ onDismiss: () -> Unit
+) {
+ val scope = rememberCoroutineScope()
+ val preview = remember(encryptedDocument) { runCatching { WdttTransferCodec.previewAdminTransfer(encryptedDocument) }.getOrNull() }
+ var password by remember { mutableStateOf("") }
+ var passwordFocused by remember { mutableStateOf(false) }
+ var decrypted by remember { mutableStateOf(null) }
+ var busy by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf(null) }
+
+ AlertDialog(
+ onDismissRequest = { if (!busy) onDismiss() },
+ title = { Text(if (decrypted == null) "Защищённые настройки" else "Заменить настройки?") },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ if (decrypted == null) {
+ Text("Источник: WDTT Plus ${preview?.sourceVersion ?: "?"}. Для расшифровки введите пароль, заданный при передаче.")
+ OutlinedTextField(
+ value = password,
+ onValueChange = { password = it; error = null },
+ label = { Text("Пароль файла") },
+ visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(),
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth().onFocusChanged { passwordFocused = it.isFocused }
+ )
+ } else {
+ Text("Будут заменены все три VPN-профиля и локальные настройки администратора. Текущие данные приложения восстановить автоматически не получится.")
+ }
+ error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
+ }
+ },
+ confirmButton = {
+ Button(
+ enabled = !busy && (decrypted != null || password.isNotEmpty()),
+ onClick = {
+ busy = true
+ error = null
+ scope.launch {
+ if (decrypted == null) {
+ runCatching {
+ withContext(Dispatchers.Default) {
+ val chars = password.toCharArray()
+ try {
+ WdttTransferCodec.decryptAdminSettings(encryptedDocument, chars)
+ } finally {
+ chars.fill('\u0000')
+ }
+ }
+ }.onSuccess {
+ decrypted = it
+ password = ""
+ }.onFailure { error = it.message ?: "Не удалось расшифровать настройки." }
+ busy = false
+ } else {
+ runCatching { settingsStore.importAdminSettings(decrypted!!) }
+ .onSuccess { onFinished("Настройки администратора импортированы. Активирован режим администратора.") }
+ .onFailure { error = it.message ?: "Не удалось импортировать настройки." }
+ busy = false
+ }
+ }
+ }
+ ) { Text(if (decrypted == null) "Проверить" else "Заменить") }
+ },
+ dismissButton = { TextButton(onClick = onDismiss, enabled = !busy) { Text("Отмена") } }
+ )
+}
+
+@Composable
+private fun AdminExportPasswordDialog(onDismiss: () -> Unit, onConfirm: (CharArray) -> Unit) {
+ var password by remember { mutableStateOf("") }
+ var repeat by remember { mutableStateOf("") }
+ var passwordFocused by remember { mutableStateOf(false) }
+ var repeatFocused by remember { mutableStateOf(false) }
+ val error = when {
+ password.isNotEmpty() && password.length < 8 -> "Минимум 8 символов"
+ repeat.isNotEmpty() && password != repeat -> "Пароли не совпадают"
+ else -> null
+ }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Защитить настройки") },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Пароль не сохраняется. Передайте его получателю отдельно.")
+ OutlinedTextField(
+ password,
+ { password = it },
+ label = { Text("Пароль") },
+ visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(),
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth().onFocusChanged { passwordFocused = it.isFocused }
+ )
+ OutlinedTextField(
+ repeat,
+ { repeat = it },
+ label = { Text("Повторите пароль") },
+ visualTransformation = if (repeatFocused) VisualTransformation.None else PasswordVisualTransformation(),
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth().onFocusChanged { repeatFocused = it.isFocused }
+ )
+ error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
+ }
+ },
+ confirmButton = {
+ Button(onClick = { onConfirm(password.toCharArray()); password = ""; repeat = "" }, enabled = password.length >= 8 && password == repeat) {
+ Text("Продолжить")
+ }
+ },
+ dismissButton = { TextButton(onClick = onDismiss) { Text("Отмена") } }
+ )
+}
+
+@Composable
+private fun QrDisplayDialog(
+ title: String,
+ bitmap: Bitmap,
+ onDismiss: () -> Unit,
+ onShare: () -> Unit,
+ onSave: () -> Unit
+) {
+ val context = androidx.compose.ui.platform.LocalContext.current
+ val permissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
+ if (granted) onSave()
+ else Toast.makeText(context, "Без разрешения Android 9 не может сохранить QR-код в галерею.", Toast.LENGTH_LONG).show()
+ }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = androidx.compose.ui.Alignment.CenterVertically
+ ) {
+ Text(title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
+ IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) {
+ Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
+ }
+ }
+ Image(bitmap = bitmap.asImageBitmap(), contentDescription = "QR-код WDTT Plus", modifier = Modifier.fillMaxWidth())
+ Text("QR содержит секретные данные. Не публикуйте изображение.", 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),
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
+ onClick = {
+ if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P &&
+ ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
+ ) {
+ permissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ } else {
+ onSave()
+ }
+ }
+ ) {
+ Icon(Icons.Default.SaveAlt, null, Modifier.size(18.dp))
+ Text(" Сохранить", maxLines = 1)
+ }
+ Button(
+ onClick = onShare,
+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)
+ ) {
+ Icon(Icons.Default.Share, null, Modifier.size(18.dp))
+ Text(" Поделиться", maxLines = 1)
+ }
+ }
+ }
+ },
+ confirmButton = {}
+ )
+}
+
+@Composable
+private fun TransferButton(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, busy: Boolean, onClick: () -> Unit) {
+ OutlinedButton(onClick = onClick, enabled = !busy) {
+ Icon(icon, null, Modifier.size(18.dp))
+ Text(" $label")
+ }
+}
+
+private fun shareText(context: Context, text: String) {
+ val intent = Intent(Intent.ACTION_SEND).apply {
+ type = "text/plain"
+ putExtra(Intent.EXTRA_TEXT, text)
+ }
+ context.startActivity(Intent.createChooser(intent, "Передать подключение WDTT Plus"))
+}
+
+private fun String.safeQrFileName(): String =
+ replace(Regex("[^\\p{L}\\p{N}._-]+"), "-")
+ .replace(Regex("-+"), "-")
+ .trim('_', '.', '-')
+ .take(48)
+ .trim('_', '.', '-')
+ .ifBlank { "qr" }
+
+private fun shareUri(context: Context, uri: Uri, mimeType: String, title: String) {
+ val intent = Intent(Intent.ACTION_SEND).apply {
+ type = mimeType
+ putExtra(Intent.EXTRA_STREAM, uri)
+ clipData = ClipData.newUri(context.contentResolver, title, uri)
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ context.startActivity(Intent.createChooser(intent, title))
+}
diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml
new file mode 100644
index 0000000..86f0f2b
--- /dev/null
+++ b/app/src/main/res/xml/file_paths.xml
@@ -0,0 +1,6 @@
+
+
+
+
diff --git a/app/src/test/java/com/wdtt/plus/TransferCodecTest.kt b/app/src/test/java/com/wdtt/plus/TransferCodecTest.kt
new file mode 100644
index 0000000..b2ab30d
--- /dev/null
+++ b/app/src/test/java/com/wdtt/plus/TransferCodecTest.kt
@@ -0,0 +1,95 @@
+package com.wdtt.plus
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.json.JSONObject
+
+class TransferCodecTest {
+ @Test
+ fun modernConnectionLink_roundTripsSpecialCharacters() {
+ val original = WdttLinkParts(
+ host = "vpn.example.org",
+ dtlsPort = 56000,
+ wgPort = 56001,
+ localPort = 9000,
+ password = "пароль: со знаками +?&=%",
+ hashes = "1234567890abcdef,fedcba0987654321"
+ )
+
+ val link = WdttTransferCodec.buildConnectionLink(original)
+ val parsed = WdttTransferCodec.parseConnectionLink(link)
+
+ assertEquals(original, parsed)
+ assertTrue(WdttDeepLink.validate(link).canStartVpn)
+ }
+
+ @Test
+ fun legacyConnectionLink_remainsSupported() {
+ val validation = WdttDeepLink.validate(
+ "wdtt://vpn.example.org:56000:56001:9000:secret:1234567890abcdef"
+ )
+
+ assertTrue(validation.canStartVpn)
+ assertEquals("vpn.example.org", validation.parts?.host)
+ }
+
+ @Test
+ fun linkCanBeExtractedFromSharedText() {
+ val value = "Подключение: wdtt://vpn.example.org:56000:56001:9000:secret:1234567890abcdef\nНе передавайте посторонним"
+
+ assertEquals(
+ "wdtt://vpn.example.org:56000:56001:9000:secret:1234567890abcdef",
+ WdttTransferCodec.extractWdttLink(value)
+ )
+ }
+
+ @Test
+ fun modernConnectionLink_rejectsInvalidPort() {
+ val link = WdttTransferCodec.buildConnectionLink(
+ WdttLinkParts("vpn.example.org", 70000, 56001, 9000, "secret", "1234567890abcdef")
+ )
+
+ assertFalse(WdttDeepLink.validate(link).canStartVpn)
+ }
+
+ @Test
+ fun malformedModernLink_isNotParsed() {
+ val validation = WdttDeepLink.validate("wdtt://connect?v=1&host=vpn.example.org")
+
+ assertFalse(validation.canStartVpn)
+ assertNotNull(validation.errors.firstOrNull())
+ }
+
+ @Test
+ fun malformedPercentEncoding_doesNotCrashParser() {
+ val validation = WdttDeepLink.validate("wdtt://connect?v=1&host=%ZZ")
+
+ assertFalse(validation.canStartVpn)
+ }
+
+ @Test
+ fun adminSettings_areEncryptedAndAuthenticated() {
+ val plain = JSONObject()
+ .put("format", "wdtt-plus-admin-settings")
+ .put("version", 1)
+ .put("secret", "bot-token-and-password")
+ .toString()
+ val password = "сложный пароль 123".toCharArray()
+
+ val encrypted = WdttTransferCodec.encryptAdminSettings(plain, password)
+
+ assertTrue(WdttTransferCodec.isAdminTransfer(encrypted))
+ assertFalse(encrypted.contains("bot-token-and-password"))
+ assertEquals(plain, WdttTransferCodec.decryptAdminSettings(encrypted, password))
+ }
+
+ @Test(expected = IllegalArgumentException::class)
+ fun adminSettings_rejectWrongPassword() {
+ val encrypted = WdttTransferCodec.encryptAdminSettings("{}", "correct-password".toCharArray())
+
+ WdttTransferCodec.decryptAdminSettings(encrypted, "wrong-password".toCharArray())
+ }
+}
diff --git a/bot.go b/bot.go
index d9decd7..3fc3baa 100644
--- a/bot.go
+++ b/bot.go
@@ -97,7 +97,7 @@ func normalizePublicAddressInput(input string) (string, error) {
return "", nil
}
if !isValidPublicHost(value) {
- return "", errors.New("укажите домен, IPv4 или `auto` без `http://` и без порта")
+ return "", errors.New("укажите домен или IPv4 без `http://` и без порта либо выберите автоматическое определение")
}
return value, nil
}
@@ -1092,10 +1092,12 @@ func sendMainMenu(token string, adminID int64, messageID int) int {
defaultPorts = defaultPortsSpec()
}
if publicIPValue == "" {
- publicIPValue = "auto"
+ publicIPValue = "автоматически: " + getPublicIP()
+ } else {
+ publicIPValue = "задан вручную: " + publicIPValue
}
text := fmt.Sprintf(
- "🤖 *WDTT VPN Manager*\n\nПароли: %d/%d\nУстройства: %d\nDNS: `%s`\nПорты ссылок: `%s`\nПубличный адрес: `%s`",
+ "🤖 *WDTT VPN Manager*\n\nПароли: %d/%d\nУстройства: %d\nDNS: `%s`\nПорты ссылок: `%s`\nАдрес сервера для ссылок: `%s`",
passwords, maxGeneratedPasswords, devices, mdCode(dnsValue), mdCode(defaultPorts), mdCode(publicIPValue),
)
return sendOrEditTelegram(token, adminID, messageID, text, inlineKeyboard(
@@ -1126,6 +1128,9 @@ func sendSettingsMenu(token string, adminID int64, messageID int) int {
usedDevices[entry.DeviceID] = struct{}{}
}
}
+ for deviceID := range adminDeviceIDSet(db) {
+ usedDevices[deviceID] = struct{}{}
+ }
totalTraffic := databaseTrafficTotals(0)
for devID := range db.Devices {
if _, ok := usedDevices[devID]; !ok {
@@ -1141,10 +1146,12 @@ func sendSettingsMenu(token string, adminID int64, messageID int) int {
}
publicIPLabel := publicIPValue
if publicIPLabel == "" {
- publicIPLabel = "auto: " + getPublicIP()
+ publicIPLabel = "определён автоматически: " + getPublicIP()
+ } else {
+ publicIPLabel = "задан вручную: " + publicIPLabel
}
text := fmt.Sprintf(
- "⚙️ *Настройки сервера*\n\nDNS WG-клиентов: `%s`\nЛимит ключей: `%d`\nПорты быстрых ссылок: `%s`\nПубличный адрес ссылок: `%s`\n\nПароли: %d/%d\nУстройства: %d\nИстёкших ключей: %d\nЗабытых устройств: %d\nТрафик всего: %.2f MB ↓ / %.2f MB ↑\n\nИзменения DNS применятся к новым конфигам клиентов. Сетевые порты самого сервера меняются через systemd/флаги и требуют перезапуска.",
+ "⚙️ *Настройки сервера*\n\nDNS WG-клиентов: `%s`\nЛимит ключей: `%d`\nПорты быстрых ссылок: `%s`\nАдрес сервера для ссылок: `%s`\n\nПароли: %d/%d\nУстройства: %d\nИстёкших ключей: %d\nЗабытых устройств: %d\nТрафик всего: %.2f MB ↓ / %.2f MB ↑\n\nИзменения DNS применятся к новым конфигам клиентов. Сетевые порты самого сервера меняются через systemd/флаги и требуют перезапуска.",
mdCode(dnsValue), maxGeneratedPasswords, mdCode(defaultPorts), mdCode(publicIPLabel),
passwords, maxGeneratedPasswords, devices, expired, orphanDevices,
float64(totalTraffic.Down)/(1024*1024), float64(totalTraffic.Up)/(1024*1024),
@@ -1156,7 +1163,10 @@ func sendSettingsMenu(token string, adminID int64, messageID int) int {
},
[]map[string]interface{}{
inlineButton("⚙️ Порты ссылок", "settings_ports"),
- inlineButton("📍 Адрес ссылок", "settings_ip"),
+ inlineButton("📍 Адрес сервера для ссылок", "settings_ip"),
+ },
+ []map[string]interface{}{
+ inlineButton("👤 Профиль владельца", "settings_owner_profile"),
},
[]map[string]interface{}{
inlineButton("🧹 Очистить истёкшие", "settings_cleanup_expired"),
@@ -1169,9 +1179,6 @@ func sendSettingsMenu(token string, adminID int64, messageID int) int {
[]map[string]interface{}{
inlineButton("🌐 Выходной IP и прокси", "settings_outbound"),
},
- []map[string]interface{}{
- inlineButton("🔎 Обновить auto", "settings_refresh_ip"),
- },
[]map[string]interface{}{inlineButton("🔄 Перезапустить WDTT", "restart_server")},
[]map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")},
))
@@ -1184,6 +1191,9 @@ func collectOrphanDevicesLocked() []*ClientDevice {
usedDevices[entry.DeviceID] = struct{}{}
}
}
+ for deviceID := range adminDeviceIDSet(db) {
+ usedDevices[deviceID] = struct{}{}
+ }
orphanDevices := make([]*ClientDevice, 0)
for devID, dev := range db.Devices {
if _, used := usedDevices[devID]; used || dev == nil {
@@ -1319,21 +1329,114 @@ func sendDefaultPortsSettingsMenu(token string, adminID int64, messageID int) in
))
}
+func sendOwnerProfileMenu(token string, adminID int64, messageID int) int {
+ dbMutex.Lock()
+ profile := normalizeAdminProfileForView(db.AdminProfile, db.DefaultPorts)
+ dbMutex.Unlock()
+
+ text := fmt.Sprintf(
+ "👤 *Профиль владельца*\n\nЭтот профиль принадлежит главному паролю и хранится отдельно от клиентов. Он не виден в списке доступов, не занимает лимит клиентов и используется для восстановления полей владельца в Android-приложении.\n\nVK-хеши: `%s`\nРезервный VK-хеш: `%s`\nПорты ссылки: `%s`\nПотоки на хеш: `%d`\nПротокол: `%s`\nSNI: `%s`\nNo DNS: `%s`\nОбновлён: `%s`",
+ mdCode(ownerSecretPresenceLabel(profile.VkHashes)),
+ mdCode(ownerSecretPresenceLabel(profile.SecondaryVkHash)),
+ mdCode(profile.Ports),
+ profile.WorkersPerHash,
+ mdCode(profile.Protocol),
+ mdCode(emptyLabel(profile.SNI, "не задан")),
+ mdCode(boolOnOff(profile.NoDNS)),
+ mdCode(formatOwnerUpdatedAt(profile.UpdatedAt)),
+ )
+ rows := [][]map[string]interface{}{
+ {inlineButton("🔗 Ссылка владельца", "owner_link")},
+ {inlineButton("🔑 Обновить VK-хеши", "owner_hash_edit")},
+ {inlineButton("⚙️ Порты владельца", "owner_ports_edit")},
+ }
+ if strings.TrimSpace(profile.VkHashes) != "" || strings.TrimSpace(profile.SecondaryVkHash) != "" {
+ rows = append(rows, []map[string]interface{}{inlineButton("🧹 Очистить VK-хеши", "owner_hash_clear")})
+ }
+ rows = append(rows, []map[string]interface{}{inlineButton("◀️ Назад", "settings")})
+ return sendOrEditTelegram(token, adminID, messageID, text, inlineKeyboard(rows...))
+}
+
+func ownerSecretPresenceLabel(value string) string {
+ count := 0
+ for _, item := range strings.FieldsFunc(value, func(r rune) bool {
+ return r == ',' || r == ' ' || r == '\n' || r == '\r' || r == '\t'
+ }) {
+ if strings.TrimSpace(item) != "" {
+ count++
+ }
+ }
+ if count == 0 {
+ return "не заданы"
+ }
+ return fmt.Sprintf("заданы (%d)", count)
+}
+
+func emptyLabel(value, fallback string) string {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return fallback
+ }
+ return value
+}
+
+func boolOnOff(value bool) string {
+ if value {
+ return "включено"
+ }
+ return "выключено"
+}
+
+func formatOwnerUpdatedAt(ts int64) string {
+ if ts <= 0 {
+ return "неизвестно"
+ }
+ return time.Unix(ts, 0).Format("02.01.2006 15:04")
+}
+
+func ownerProfileLink() (string, error) {
+ dbMutex.Lock()
+ profile := normalizeAdminProfileForView(db.AdminProfile, db.DefaultPorts)
+ mainPassword := db.MainPassword
+ publicHost := db.PublicIP
+ dbMutex.Unlock()
+ if strings.TrimSpace(profile.VkHashes) == "" {
+ return "", errors.New("в профиле владельца не задан VK-хеш")
+ }
+ if strings.TrimSpace(mainPassword) == "" {
+ return "", errors.New("главный пароль не задан")
+ }
+ if strings.TrimSpace(publicHost) == "" {
+ publicHost = getPublicIP()
+ }
+ pts := strings.Split(profile.Ports, ",")
+ if len(pts) != 3 {
+ return "", errors.New("порты владельца повреждены")
+ }
+ return fmt.Sprintf("wdtt://%s:%s:%s:%s:%s:%s", publicHost, pts[0], pts[1], pts[2], mainPassword, profile.VkHashes), nil
+}
+
func sendPublicIPSettingsMenu(token string, adminID int64, messageID int) int {
dbMutex.Lock()
ip := db.PublicIP
dbMutex.Unlock()
label := ip
if label == "" {
- label = "auto: " + getPublicIP()
+ label = "определён автоматически: " + getPublicIP()
+ } else {
+ label = "задан вручную: " + label
}
text := fmt.Sprintf(
- "📍 *Публичный адрес быстрых ссылок*\n\nТекущее значение: `%s`\n\nИспользуется только в новых `wdtt://` ссылках. Можно указать домен или IP. Для бесшовного переезда лучше использовать домен: при смене сервера достаточно обновить DNS-запись.",
+ "📍 *Адрес сервера для ссылок*\n\nТекущее значение: `%s`\n\nЭтот адрес добавляется в новые `wdtt://` ссылки. Можно задать домен или IP вручную либо разрешить серверу автоматически определять свой публичный IP. Для бесшовного переезда лучше использовать домен: при смене сервера достаточно обновить DNS-запись.",
mdCode(label),
)
+ modeButton := inlineButton("🔎 Определять автоматически", "set_public_ip_auto")
+ if ip == "" {
+ modeButton = inlineButton("🔎 Проверить текущий IP", "settings_refresh_ip")
+ }
return sendOrEditTelegram(token, adminID, messageID, text, inlineKeyboard(
[]map[string]interface{}{inlineButton("✏️ Ввести адрес", "settings_ip_edit")},
- []map[string]interface{}{inlineButton("Вернуть auto", "set_public_ip_auto")},
+ []map[string]interface{}{modeButton},
[]map[string]interface{}{inlineButton("◀️ Назад", "settings")},
))
}
@@ -1343,16 +1446,16 @@ func sendRefreshIPMenu(token string, adminID int64, messageID int) int {
manualIP := db.PublicIP
dbMutex.Unlock()
current := getPublicIP()
- mode := "auto"
+ mode := "автоматическое определение"
if manualIP != "" {
- mode = "ручной"
+ mode = "задан вручную"
}
text := fmt.Sprintf(
- "🔎 *Обновить auto адрес*\n\nТекущий адрес для ссылок: `%s`\nРежим: `%s`\n\nДействие сбросит кэш автоопределения и заново запросит публичный IP. Если задан ручной домен или IP, он останется приоритетным.",
+ "🔎 *Определить публичный IP заново*\n\nСейчас определён IP: `%s`\nРежим адреса для ссылок: `%s`\n\nСервер повторно запросит свой публичный IP. Если домен или IP задан вручную, он останется приоритетным.",
mdCode(current), mdCode(mode),
)
return sendOrEditTelegram(token, adminID, messageID, text, inlineKeyboard(
- []map[string]interface{}{inlineButton("🔎 Обновить", "confirm_refresh_ip")},
+ []map[string]interface{}{inlineButton("🔎 Определить IP", "confirm_refresh_ip")},
[]map[string]interface{}{inlineButton("◀️ Назад", "settings")},
))
}
@@ -2076,6 +2179,49 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
))
} else if data == "settings_dns" {
promptMessageID = sendDNSSettingsMenu(token, adminID, menuMessageID)
+ } else if data == "settings_owner_profile" {
+ promptMessageID = sendOwnerProfileMenu(token, adminID, menuMessageID)
+ } else if data == "owner_link" {
+ link, err := ownerProfileLink()
+ if err != nil {
+ promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, fmt.Sprintf("❌ %s.\n\nСначала обновите VK-хеши владельца в этом меню.", err.Error()), inlineKeyboard(
+ []map[string]interface{}{inlineButton("🔑 Обновить VK-хеши", "owner_hash_edit")},
+ []map[string]interface{}{inlineButton("◀️ Назад", "settings_owner_profile")},
+ ))
+ continue
+ }
+ promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, fmt.Sprintf("🔗 *Ссылка владельца:*\n`%s`\n\nЭта ссылка использует главный пароль и профиль владельца. Не пересылайте её как клиентский доступ.", mdCode(link)), inlineKeyboard(
+ []map[string]interface{}{inlineButton("◀️ Профиль владельца", "settings_owner_profile")},
+ []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")},
+ ))
+ } else if data == "owner_hash_edit" {
+ waitingForSetting = "owner_hash"
+ promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "🔑 Отправьте VK-хеши владельца или ссылки приглашения.\n\nМожно несколько значений через пробел, запятую или новую строку.", inlineKeyboard(
+ []map[string]interface{}{inlineButton("◀️ Назад", "settings_owner_profile")},
+ ))
+ } else if data == "owner_hash_clear" {
+ dbMutex.Lock()
+ db.AdminProfile.VkHashes = ""
+ db.AdminProfile.SecondaryVkHash = ""
+ db.AdminProfile.UpdatedAt = time.Now().Unix()
+ saveDB()
+ dbMutex.Unlock()
+ promptMessageID = sendOwnerProfileMenu(token, adminID, menuMessageID)
+ } else if data == "owner_ports_edit" {
+ waitingForSetting = "owner_ports"
+ promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "⚙️ Укажите порты ссылки владельца.\n\nФормат: `DTLS,WG,TUN`, например `56000,56001,9000`.", inlineKeyboard(
+ []map[string]interface{}{inlineButton("Стандартные", "owner_ports_default")},
+ []map[string]interface{}{inlineButton("◀️ Назад", "settings_owner_profile")},
+ ))
+ } else if data == "owner_ports_default" {
+ ports := defaultPortsSpec()
+ dbMutex.Lock()
+ db.AdminProfile.Ports = ports
+ db.AdminProfile.ListenPort = adminProfileDefaultListenPort(ports)
+ db.AdminProfile.UpdatedAt = time.Now().Unix()
+ saveDB()
+ dbMutex.Unlock()
+ promptMessageID = sendOwnerProfileMenu(token, adminID, menuMessageID)
} else if data == "settings_dns_edit" {
waitingForSetting = "dns"
promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "🌐 Введите DNS для WireGuard-клиентов.\n\nМожно несколько через запятую, например: `1.1.1.1,8.8.8.8`.", inlineKeyboard(
@@ -2142,8 +2288,8 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
promptMessageID = sendPublicIPSettingsMenu(token, adminID, menuMessageID)
} else if data == "settings_ip_edit" {
waitingForSetting = "public_ip"
- promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "📍 Введите публичный адрес для быстрых ссылок.\n\nМожно домен или IP без `http://` и без порта, например `site.ru`.\n\n`auto` или `-` — автоопределение IP через ipify.", inlineKeyboard(
- []map[string]interface{}{inlineButton("Auto", "set_public_ip_auto")},
+ promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "📍 Введите адрес сервера для новых ссылок.\n\nМожно указать домен или IP без `http://` и без порта, например `site.ru`. Либо нажмите кнопку автоматического определения ниже.", inlineKeyboard(
+ []map[string]interface{}{inlineButton("Определять автоматически", "set_public_ip_auto")},
[]map[string]interface{}{inlineButton("◀️ Назад", "settings")},
))
} else if data == "set_public_ip_auto" {
@@ -2159,7 +2305,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
} else if data == "confirm_refresh_ip" {
publicIP = ""
ip := getPublicIP()
- promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, fmt.Sprintf("🔎 Auto адрес обновлён: `%s`", mdCode(ip)), inlineKeyboard(
+ promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, fmt.Sprintf("🔎 Публичный IP сервера определён: `%s`", mdCode(ip)), inlineKeyboard(
[]map[string]interface{}{inlineButton("◀️ Назад", "settings")},
[]map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")},
))
@@ -2379,6 +2525,9 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
continue
}
entry.IsDeactivated = false
+ if entry.DeviceID != "" {
+ upsertPeerInWG(wgDev, db.Devices[entry.DeviceID])
+ }
saveDB()
dbMutex.Unlock()
promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, fmt.Sprintf("✅ Пароль `%s` активирован", mdCode(pass)), inlineKeyboard(
@@ -2600,7 +2749,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
if err != nil {
waitingForSetting = "public_ip"
promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, fmt.Sprintf("❌ %s.", err.Error()), inlineKeyboard(
- []map[string]interface{}{inlineButton("Auto", "set_public_ip_auto")},
+ []map[string]interface{}{inlineButton("Определять автоматически", "set_public_ip_auto")},
[]map[string]interface{}{inlineButton("◀️ Назад", "settings")},
))
continue
@@ -2613,6 +2762,40 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
dbMutex.Unlock()
promptMessageID = sendSettingsMenu(token, adminID, promptMessageID)
continue
+ case "owner_hash":
+ hash, err := normalizeVKHashesInput(cmd)
+ if err != nil {
+ waitingForSetting = "owner_hash"
+ promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, fmt.Sprintf("❌ %s\n\nОтправьте VK-хеши владельца ещё раз.", err.Error()), inlineKeyboard(
+ []map[string]interface{}{inlineButton("◀️ Назад", "settings_owner_profile")},
+ ))
+ continue
+ }
+ dbMutex.Lock()
+ db.AdminProfile.VkHashes = hash
+ db.AdminProfile.UpdatedAt = time.Now().Unix()
+ saveDB()
+ dbMutex.Unlock()
+ promptMessageID = sendOwnerProfileMenu(token, adminID, promptMessageID)
+ continue
+ case "owner_ports":
+ ports, err := parsePortsSpec(cmd)
+ if err != nil {
+ waitingForSetting = "owner_ports"
+ promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, fmt.Sprintf("❌ %s.\n\nУкажите 3 порта через запятую, например: `56000,56001,9000`.", err.Error()), inlineKeyboard(
+ []map[string]interface{}{inlineButton("Стандартные", "owner_ports_default")},
+ []map[string]interface{}{inlineButton("◀️ Назад", "settings_owner_profile")},
+ ))
+ continue
+ }
+ dbMutex.Lock()
+ db.AdminProfile.Ports = ports
+ db.AdminProfile.ListenPort = adminProfileDefaultListenPort(ports)
+ db.AdminProfile.UpdatedAt = time.Now().Unix()
+ saveDB()
+ dbMutex.Unlock()
+ promptMessageID = sendOwnerProfileMenu(token, adminID, promptMessageID)
+ continue
case "outbound_external_check", "outbound_external_enable":
kind, host, port, login, password, err := parseExternalProxyInput(cmd)
if err != nil {
@@ -2793,9 +2976,17 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) {
targetPassword = ""
srvIP := getPublicIP()
pts := strings.Split(tempPorts, ",")
- link := fmt.Sprintf("wdtt://%s:%s:%s:%s:%s:%s", srvIP, pts[0], pts[1], pts[2], db.MainPassword, hash)
+ dbMutex.Lock()
+ db.AdminProfile.VkHashes = hash
+ db.AdminProfile.Ports = tempPorts
+ db.AdminProfile.ListenPort = adminProfileDefaultListenPort(tempPorts)
+ db.AdminProfile.UpdatedAt = time.Now().Unix()
+ mainPassword := db.MainPassword
+ saveDB()
+ dbMutex.Unlock()
+ link := fmt.Sprintf("wdtt://%s:%s:%s:%s:%s:%s", srvIP, pts[0], pts[1], pts[2], mainPassword, hash)
promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, fmt.Sprintf("🔗 *Ссылка для главного пароля:*\n`%s`", mdCode(link)), inlineKeyboard(
- []map[string]interface{}{inlineButton("🔐 К списку", "backlist")},
+ []map[string]interface{}{inlineButton("👤 Профиль владельца", "settings_owner_profile")},
[]map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")},
))
continue
@@ -2883,14 +3074,9 @@ func sendPasswordList(token string, adminID int64, wgDev *device.Device, message
saveDB()
}
- txt := "🔐 *Пароли:*\n\n"
- txt += fmt.Sprintf("🔒 Главный: `%s` (владелец)\n\n", mdCode(db.MainPassword))
+ txt := "🔐 *Клиентские доступы:*\n\n"
var inlineKb []map[string]interface{}
- inlineKb = append(inlineKb, map[string]interface{}{
- "text": "🔗 Ссылка на главный пароль",
- "callback_data": "mainlink",
- })
if len(db.Passwords) == 0 {
txt += "_Нет сгенерированных паролей._\n"
@@ -2928,16 +3114,15 @@ func sendPasswordList(token string, adminID int64, wgDev *device.Device, message
txt += "\n🟢 = свободен | 🔗 = привязан"
- var replyMarkup interface{}
+ var keyboard [][]map[string]interface{}
if len(inlineKb) > 0 {
- var keyboard [][]map[string]interface{}
for _, btn := range inlineKb {
keyboard = append(keyboard, []map[string]interface{}{btn})
}
- keyboard = append(keyboard, []map[string]interface{}{inlineButton("➕ Новый пароль", "menu_new")})
- keyboard = append(keyboard, []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")})
- replyMarkup = map[string]interface{}{"inline_keyboard": keyboard}
}
+ keyboard = append(keyboard, []map[string]interface{}{inlineButton("➕ Новый пароль", "menu_new")})
+ keyboard = append(keyboard, []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")})
+ replyMarkup := map[string]interface{}{"inline_keyboard": keyboard}
return sendOrEditTelegram(token, adminID, messageID, txt, replyMarkup)
}
diff --git a/server.go b/server.go
index c391aae..3ba3ec4 100644
--- a/server.go
+++ b/server.go
@@ -90,6 +90,19 @@ type PasswordEntry struct {
BindHistory []BindHistoryEntry `json:"bind_history,omitempty"`
}
+type AdminProfileEntry struct {
+ VkHashes string `json:"vk_hashes,omitempty"`
+ SecondaryVkHash string `json:"secondary_vk_hash,omitempty"`
+ WorkersPerHash int `json:"workers_per_hash,omitempty"`
+ Protocol string `json:"protocol,omitempty"`
+ ListenPort int `json:"listen_port,omitempty"`
+ SNI string `json:"sni,omitempty"`
+ NoDNS bool `json:"no_dns,omitempty"`
+ Ports string `json:"ports,omitempty"` // "dtls,wg,tun"
+ DeviceIDs []string `json:"device_ids,omitempty"` // устройства, подключавшиеся по main_password
+ UpdatedAt int64 `json:"updated_at,omitempty"`
+}
+
type TrafficBucket struct {
Date string `json:"date"`
DownBytes int64 `json:"down_bytes"`
@@ -117,6 +130,7 @@ type Database struct {
MaxPasswords int `json:"max_passwords,omitempty"`
DefaultPorts string `json:"default_ports,omitempty"`
PublicIP string `json:"public_ip,omitempty"`
+ AdminProfile AdminProfileEntry `json:"admin_profile,omitempty"`
AdminDownBytes int64 `json:"admin_down_bytes,omitempty"`
AdminUpBytes int64 `json:"admin_up_bytes,omitempty"`
AdminTraffic []TrafficBucket `json:"admin_traffic,omitempty"`
@@ -407,6 +421,31 @@ func refreshWrapKeysFromDBLocked() error {
return serverWrapKeys.SetPasswords(db.MainPassword, passwords)
}
+func rememberAdminDeviceID(profile *AdminProfileEntry, deviceID string) bool {
+ deviceID = strings.TrimSpace(deviceID)
+ if deviceID == "" {
+ return false
+ }
+ for _, existing := range profile.DeviceIDs {
+ if existing == deviceID {
+ return false
+ }
+ }
+ profile.DeviceIDs = append(profile.DeviceIDs, deviceID)
+ return true
+}
+
+func adminDeviceIDSet(loaded *Database) map[string]struct{} {
+ result := make(map[string]struct{}, len(loaded.AdminProfile.DeviceIDs))
+ for _, deviceID := range loaded.AdminProfile.DeviceIDs {
+ deviceID = strings.TrimSpace(deviceID)
+ if deviceID != "" {
+ result[deviceID] = struct{}{}
+ }
+ }
+ return result
+}
+
func initDB(dir, mainPass, adminID, botToken, dnsValue string) {
dbFile = filepath.Join(dir, "passwords.json")
db = &Database{
@@ -451,6 +490,7 @@ func initDB(dir, mainPass, adminID, botToken, dnsValue string) {
if strings.TrimSpace(db.DefaultPorts) == "" {
db.DefaultPorts = "56000,56001,9000"
}
+ db.AdminProfile = normalizeAdminProfileForStorage(db.AdminProfile, db.DefaultPorts)
setServerDefaultPorts(db.DefaultPorts)
setServerPublicIPOverride(db.PublicIP)
saveDB()
@@ -528,12 +568,15 @@ func upsertPeerInWG(wgDev *device.Device, dev *ClientDevice) {
func cleanupExpiredPasswordsLocked(wgDev *device.Device) int {
removed := 0
nowUnix := time.Now().Unix()
+ adminDevices := adminDeviceIDSet(db)
for p, entry := range db.Passwords {
if isPasswordExpired(entry) {
if entry != nil && entry.DeviceID != "" {
markActiveBindUnbound(entry, entry.DeviceID, nowUnix)
- removePeerFromWG(wgDev, db.Devices[entry.DeviceID])
- delete(db.Devices, entry.DeviceID)
+ if _, isAdminDevice := adminDevices[entry.DeviceID]; !isAdminDevice {
+ removePeerFromWG(wgDev, db.Devices[entry.DeviceID])
+ delete(db.Devices, entry.DeviceID)
+ }
}
delete(db.Passwords, p)
serverWrapKeys.RemovePassword(p)
@@ -1183,6 +1226,10 @@ PersistentKeepalive = %d`,
// ==================== Main ====================
func main() {
+ if len(os.Args) > 1 && os.Args[1] == "admin" {
+ os.Exit(runAdminCLI(os.Args[2:]))
+ }
+
listen := flag.String("listen", "0.0.0.0:56000", "DTLS адрес")
wgPort := flag.Int("wg-port", defaultInternalWGPort, "WireGuard UDP порт")
configDir := flag.String("config-dir", "/etc/wdtt", "директория конфигурации")
@@ -1237,6 +1284,9 @@ func main() {
log.Printf("[DB] Удалено истёкших паролей при старте: %d", removed)
}
syncPersistedPeersToWG(wgDev)
+ if err := startAdminSocket(ctx, *configDir, wgDev); err != nil {
+ log.Fatalf("[ADMIN] Локальное управление: %v", err)
+ }
defer func() {
wgDev.Close()
runCmdSilent("ip", "link", "del", wgIfaceName)
@@ -1383,6 +1433,9 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD
newlyBound = true
log.Printf("[WG] Пароль %s привязан к устройству %s", maskPassword(password), deviceID)
}
+ if isMainPass {
+ rememberAdminDeviceID(&db.AdminProfile, deviceID)
+ }
dev, exists := db.Devices[deviceID]
if !exists {