Выпуск WDTT Plus v2
This commit is contained in:
1 parent
a8dce499eb
commit
d30934ef4f
28 files changed
+8182
-355
No files matched your search
@@ -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.
|
||||
- Переработано множество мелких и внутренних деталей, не вынесенных в этот список.
|
||||
@@ -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-выход.
|
||||
|
||||
#### Обновления
|
||||
|
||||
|
||||
+170
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -11,6 +11,14 @@
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="28" />
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera.any"
|
||||
android:required="false" />
|
||||
|
||||
<application
|
||||
android:name=".WdttApplication"
|
||||
@@ -38,14 +46,45 @@
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="text/plain" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="image/*" />
|
||||
<data android:mimeType="application/json" />
|
||||
<data android:mimeType="application/vnd.wdtt.plus.transfer" />
|
||||
<data android:mimeType="application/octet-stream" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="wdtt" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="application/json" />
|
||||
<data android:mimeType="application/vnd.wdtt.plus.transfer" />
|
||||
<data android:mimeType="application/octet-stream" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.files"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
|
||||
<activity
|
||||
android:name=".QrCaptureActivity"
|
||||
android:screenOrientation="fullSensor"
|
||||
android:stateNotNeeded="true"
|
||||
android:theme="@style/zxing_CaptureTheme" />
|
||||
|
||||
<service
|
||||
android:name=".TunnelService"
|
||||
android:exported="false"
|
||||
|
||||
@@ -2,20 +2,21 @@
|
||||
# ==============================================================================
|
||||
# WDTT Plus Server — Универсальный установщик для VPS
|
||||
# Поддержка: Debian 11+, Ubuntu 20.04+, CentOS/RHEL/Fedora/AlmaLinux/Rocky
|
||||
# Версия: 3.2 | Дата: 2026-05-13
|
||||
# Версия: 3.3 | Дата: 2026-07-02
|
||||
# NAT: MASQUERADE через iptables
|
||||
# WG: порт 56001 (не конфликтует с существующим WG на 51820)
|
||||
# DTLS: порт 56000
|
||||
# ==============================================================================
|
||||
set -uo pipefail
|
||||
|
||||
readonly SCRIPT_VERSION="3.2"
|
||||
readonly SCRIPT_VERSION="3.3"
|
||||
readonly LOG_FILE="/var/log/wdtt-install.log"
|
||||
readonly WG_PORT="${WDTT_WG_PORT:-56001}"
|
||||
readonly DTLS_PORT="${WDTT_DTLS_PORT:-56000}"
|
||||
readonly SSH_PORT="${WDTT_SSH_PORT:-22}"
|
||||
readonly MAX_PASSWORDS="${WDTT_MAX_PASSWORDS:-50}"
|
||||
readonly WDTT_ARGS="${WDTT_ARGS:-}"
|
||||
readonly WDTT_PRESERVE_DATA="${WDTT_PRESERVE_DATA:-0}"
|
||||
readonly WDTT_IFACE="wdtt0"
|
||||
readonly WDTT_CONFIG_DIR="/etc/wdtt"
|
||||
readonly WDTT_ACCESS_DB="passwords.json"
|
||||
@@ -356,8 +357,14 @@ wdtt_cleanup() {
|
||||
# Удаляем старые правила NAT для WDTT подсети
|
||||
fw_cleanup_wdtt_rules "$(detect_wan_interface)"
|
||||
|
||||
rm -f /usr/local/bin/wdtt-server 2>/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 уже установлен"
|
||||
|
||||
@@ -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<String?>(null)
|
||||
private var wdttDeepLinkMessage by mutableStateOf<String?>(null)
|
||||
private var pendingWdttDeepLinkPlan by mutableStateOf<WdttDeepLinkApplyPlan?>(null)
|
||||
private var pendingAdminTransfer by mutableStateOf<String?>(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) }) {
|
||||
|
||||
@@ -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<View>(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)
|
||||
}
|
||||
}
|
||||
@@ -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<String> = 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<ServerDeviceInfo>,
|
||||
val traffic: ServerTrafficPeriod,
|
||||
val adminTraffic: ServerTrafficPeriod,
|
||||
val adminProfile: ServerAdminProfileInfo,
|
||||
val clients: List<ServerClientInfo>
|
||||
) {
|
||||
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<ServerBindEvent>
|
||||
) {
|
||||
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<String>): ServerAdminActionResult =
|
||||
withContext(Dispatchers.IO) {
|
||||
withSession(target) { ssh -> actionFromResponse(callAdmin(ssh, target, args)) }
|
||||
}
|
||||
|
||||
private fun <T> 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<String>): 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
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -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<String>()
|
||||
val warnings = mutableListOf<String>()
|
||||
|
||||
@@ -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<T>
|
||||
WORKERS_PER_HASH, VK_HASH_NEXT_SLOT, LISTEN_PORT, SERVER_DTLS_PORT, SERVER_WG_PORT, PROXY_PORT -> intPreferencesKey(newName) as Preferences.Key<T>
|
||||
MANUAL_PORTS_ENABLED, NO_DTLS, NO_DNS, IS_WHITELIST, WDTT_LINK_MODE, VKCALLS_PREFLIGHT -> booleanPreferencesKey(newName) as Preferences.Key<T>
|
||||
MANUAL_PORTS_ENABLED, NO_DTLS, NO_DNS, IS_WHITELIST, WDTT_LINK_MODE, VKCALLS_PREFLIGHT, DETAILED_LOGS -> booleanPreferencesKey(newName) as Preferences.Key<T>
|
||||
else -> throw IllegalArgumentException("Unsupported key type: ${baseKey.name}")
|
||||
}
|
||||
}
|
||||
@@ -408,7 +424,10 @@ class SettingsStore(context: Context) {
|
||||
prefs[getProfileKey(baseKey, profile)] ?: ""
|
||||
}
|
||||
|
||||
val detailedLogs: Flow<Boolean> = dataStore.data.map { it[DETAILED_LOGS] ?: false }
|
||||
val detailedLogs: Flow<Boolean> = dataStore.data.map { prefs ->
|
||||
val profile = prefs[ACTIVE_PROFILE] ?: 0
|
||||
prefs[getProfileKey(DETAILED_LOGS, profile)] ?: false
|
||||
}
|
||||
|
||||
// ═══ Пароли и Управление ═══
|
||||
val connectionPassword: Flow<String> = dataStore.data.map { prefs ->
|
||||
@@ -495,6 +514,10 @@ class SettingsStore(context: Context) {
|
||||
val updateDialogLastActionVersion: Flow<String> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_VERSION] ?: "" }
|
||||
val updateDialogLastAction: Flow<String> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION] ?: "" }
|
||||
val updateDialogLastActionAt: Flow<Long> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_AT] ?: 0L }
|
||||
val migrationNoticeV2Shown: Flow<Boolean> = dataStore.data.map { it[MIGRATION_NOTICE_V2_SHOWN] ?: false }
|
||||
val deployClientsSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: true }
|
||||
val deployOutboundSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_OUTBOUND_SECTION_EXPANDED] ?: false }
|
||||
val deployMigrationSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_MIGRATION_SECTION_EXPANDED] ?: false }
|
||||
val interfaceRole: Flow<String> = dataStore.data.map { it[INTERFACE_ROLE] ?: "" }
|
||||
val permissionOnboardingComplete: Flow<Boolean> = 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<String>()))
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<Boolean> = rememberSaveable { mutableStateOf(true) },
|
||||
projectExpandedState: MutableState<Boolean> = rememberSaveable { mutableStateOf(true) }
|
||||
projectExpandedState: MutableState<Boolean> = 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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<ServerAdminState?>(null)
|
||||
val clientSearch = mutableStateOf("")
|
||||
val selectedClientIndex = mutableIntStateOf(0)
|
||||
var targetKey: String = ""
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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<String?>(null) }
|
||||
var qrData by remember { mutableStateOf<Pair<String, Bitmap>?>(null) }
|
||||
var adminAction by remember { mutableStateOf<AdminExportAction?>(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<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(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))
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<cache-path
|
||||
name="transfers"
|
||||
path="transfers/" />
|
||||
</paths>
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user