diff --git a/CHANGELOG.md b/CHANGELOG.md index 81b9243..f8f6488 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ Здесь фиксируются заметные пользовательские изменения WDTT Plus. +## v3 — 04.07.2026 + +### Клиенты и сервер + +- Добавлен экспорт и импорт отдельного клиента через блок «Деплой» → «Клиенты и сервер»: доступны QR-код, камера, изображение, файл, Android Share и код передачи. +- После импорта приложение показывает ход операции, перечитывает список клиентов с сервера и выбирает нового клиента без ручного обновления. +- При переносе отдельного клиента сохраняются пароль, название, VK-хеши, срок и состояние доступа; устройство, статистика, история, адрес и серверные параметры берутся с нового сервера. +- При создании клиента можно выбрать автоматический пароль или задать пароль вручную с проверкой конфликтов. +- Добавлена смена пароля клиента из приложения и Telegram-бота. Перед изменением показываются клиент, текущий пароль в сокращённом виде и привязанное устройство, если оно есть. +- Создание, импорт и смена пароля клиента применяются на работающем сервере без перезапуска службы. + +### Туннель + +- VPN-профили можно переименовать долгим нажатием на кнопки VPN 1/2/3 в боковых настройках. +- В заголовках вкладок «Туннель» и «Деплой» показывается название активного VPN-профиля. +- Плитка быстрых настроек Android и активное уведомление туннеля показывают название выбранного VPN-профиля. +- В окне настройки VK-хешей добавлено копирование каждого хеша отдельно и всех заполненных хешей одной кнопкой в порядке слотов 1–4. + +### Деплой + +- Для администраторов добавлено предупреждение версии 3 о необходимости обновить установку серверной части через вкладку «Деплой» с сохранением данных. + ## v2 — 03.07.2026 Второй выпуск — крупное обновление WDTT Plus. diff --git a/README.md b/README.md index 496adc9..227f9bc 100644 --- a/README.md +++ b/README.md @@ -43,10 +43,10 @@ ### Что изменено в модификации -- **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями. +- **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Клиента можно перенести отдельно через QR, камеру, изображение, файл, Android Share или код передачи; создать с автоматическим или заданным вручную паролем и безопасно сменить пароль без перезапуска сервера. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями. - **Обновление, восстановление и перенос сервера:** повторный деплой предлагает безопасное обновление с сохранением данных или чистую установку. Перед обновлением создаётся страховочная копия сервера; новая служба и целостность доступов проверяются, а при ошибке выполняется откат. Экспорт/импорт переносит базу доступов и при необходимости WireGuard-ключи. -- **Ссылки, роли и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Импорт проверяется и занимает свободный VPN-профиль; при трёх занятых приложение запрашивает выбор профиля для замены. Для администратора доступен защищённый паролем перенос локальных настроек. -- **Проверка VK-хешей:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Настройка мощности сопровождается пояснением о потоках, нагрузке и частоте проверок VK. +- **Ссылки, роли и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Импорт проверяется и занимает свободный VPN-профиль; при трёх занятых приложение запрашивает выбор профиля для замены. VPN-профили можно переименовывать долгим нажатием на VPN 1/2/3. Для администратора доступен защищённый паролем перенос локальных настроек. +- **Проверка VK-хешей:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Хеши можно копировать по одному или все заполненные сразу в порядке слотов. Настройка мощности сопровождается пояснением о потоках, нагрузке и частоте проверок VK. - **Настраиваемый выходной 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. @@ -55,17 +55,18 @@ ## Возможности Android-версии - **Полноценный VPN-режим:** приложение использует `VpnService` и WireGuard GoBackend, поэтому трафик выбранных приложений проходит через системный VPN-интерфейс без ручного импорта конфигов. -- **Корректная передача VPN-слота:** если Android отключает WDTT Plus VPN или другой VPN забирает системный VPN-слот, WDTT Plus останавливает транспорт и переводит плитку/виджет в неактивное состояние. Плитка запускает VPN как с обычными настройками, так и в режиме ссылки. +- **Три профиля подключения:** VPN 1, VPN 2 и VPN 3 хранят отдельные настройки туннеля и деплоя; профиль можно переименовать долгим нажатием в боковых настройках. Название активного профиля видно в заголовках вкладок, передаче подключения, плитке быстрых настроек и активном уведомлении туннеля. +- **Корректная передача VPN-слота:** если Android отключает WDTT Plus VPN или другой VPN забирает системный VPN-слот, WDTT Plus останавливает транспорт и переводит плитку/виджет в неактивное состояние. Плитка запускает VPN как с обычными настройками, так и в режиме ссылки, а при активном подключении показывает выбранный профиль вместе с уведомлением туннеля. - **TURN/DTLS-транспорт:** нативный Go-клиент получает временные TURN-учётные данные VK-звонка и поднимает DTLS-соединения к relay-серверу, через который передаётся трафик до вашего сервера. - **Импорт VK-ссылок через «Поделиться»:** ссылку VK-звонка можно отправить прямо в WDTT Plus. Приложение извлечёт хеш после `/call/join/`, заполнит следующий слот VK-хеша и покажет, какой номер был обновлён. - **Передача между устройствами:** текущий VPN-профиль отправляется как `wdtt://`-ссылка, файл или QR-код. Приложение принимает эти данные через Android, камеру, галерею и выбор файла, сохраняя совместимость со старыми ссылками. -- **Проверка VK-хешей:** окно VK-хешей умеет проверить, жив ли групповой звонок, решить VK Captcha в процессе проверки и показать понятный статус по каждому полю. +- **Проверка 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-бота. +- **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит пользовательских паролей, 16-символьную генерацию, ручное задание пароля с проверками, привязку к устройству и срок действия. Клиентов можно создавать, импортировать, экспортировать, отключать, продлевать, отвязывать, удалять и менять им пароль из приложения или Telegram-бота. - **Горячее обновление WRAP-ключей:** создание, удаление и истечение паролей обновляют набор WRAP-ключей на сервере без перезапуска ядра. - **Исключения приложений:** ЧС и БС хранят независимые наборы. В ЧС отмеченные приложения работают напрямую, в БС только отмеченные направляются в VPN; изменения применяются быстрой перезагрузкой WireGuard. - **Рабочая captcha-цепочка:** сначала приложение пробует получить TURN credentials через отключаемый VKCalls preflight. Если анонимный вход недоступен, Auto WebView решает обычную проверку, Go v2 используется как следующий автоматический этап, а ручной WebView остаётся fallback для slider/puzzle и других строгих проверок. @@ -149,7 +150,9 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se - **Главный пароль:** задаётся при деплое и используется владельцем сервера. - **Сгенерированные пароли:** создаются из приложения или Telegram-бота, имеют срок действия, привязываются к первому устройству и обновляют WRAP-ключи на сервере без перезапуска. -В блоке **«Клиенты и сервер»** вкладки **«Деплой»** можно искать и фильтровать клиентов, создавать доступы, редактировать их параметры, срок и привязку устройства, а также передавать подключение ссылкой, файлом или QR-кодом. Там же доступны история, трафик, настройки сервера, очистка устаревших записей и сервисные действия. +В блоке **«Клиенты и сервер»** вкладки **«Деплой»** можно искать и фильтровать клиентов, создавать доступы с автоматическим или ручным паролем, редактировать параметры, срок и привязку устройства, менять пароль, а также передавать подключение ссылкой, файлом или QR-кодом. Там же доступны экспорт и импорт отдельного клиента для ручного переноса на другой сервер, история, трафик, настройки сервера, очистка устаревших записей и сервисные действия. После импорта приложение перечитывает список сервера и выбирает добавленного клиента. + +Экспорт отдельного клиента переносит только данные доступа: пароль, название, VK-хеши, срок и состояние. Устройство, WireGuard-ключи, статистика, история, адрес, порты и серверные параметры не копируются; после импорта клиент использует настройки нового сервера и привязывается к устройству при первом подключении. Обычные изменения применяются работающим сервером сразу и не прерывают остальных клиентов: Android вызывает admin-команды по SSH, а они обращаются к закрытому локальному сокету `wdtt-server`, не открывая отдельный управляющий порт в сеть. Явный перезапуск сервиса оставлен отдельным подтверждаемым действием. При удалении или истечении пароля соответствующий WRAP-ключ удаляется из памяти сервера. @@ -157,7 +160,7 @@ Android → SSH → /tmp/deploy.sh + /tmp/wdtt-server → /usr/local/bin/wdtt-se #### Передача между устройствами -Раздел **«Передать или получить»** находится в боковых настройках. Пользователь может отправить активный VPN-профиль ссылкой, файлом или QR-кодом; на другом устройстве данные можно открыть напрямую, выбрать как файл, отсканировать камерой либо распознать на изображении из галереи. Приложение использует первый пустой профиль VPN, а если заняты все три — предлагает выбрать профиль и подтвердить замену. +Раздел **«Передать или получить»** находится в боковых настройках. Пользователь может отправить активный VPN-профиль ссылкой, файлом или QR-кодом; на другом устройстве данные можно открыть напрямую, выбрать как файл, отсканировать камерой либо распознать на изображении из галереи. Приложение использует первый пустой профиль VPN, а если заняты все три — предлагает выбрать профиль и подтвердить замену. Названия профилей помогают отличать подключения в заголовках вкладок «Туннель» и «Деплой». В режиме администратора там же можно передать все локальные VPN-профили, параметры деплоя, исключения и настройки выхода. Такой экспорт шифруется отдельным паролем; пароль не сохраняется и должен передаваться получателю отдельно. Резервная копия состояния самого сервера по-прежнему импортируется через **«Деплой» → «Перенос сервера»**. diff --git a/admin.go b/admin.go index 62c9f59..880ce25 100644 --- a/admin.go +++ b/admin.go @@ -188,6 +188,8 @@ func executeAdminCommand(configDir string, loaded *Database, rest []string, wgDe response, err = adminSetPasswordExpiry(configDir, loaded, rest[1:]) case "set-ports": response, err = adminSetPasswordPorts(configDir, loaded, rest[1:]) + case "set-password": + response, err = adminSetPassword(configDir, loaded, rest[1:]) case "update-client": response, err = adminUpdateClient(configDir, loaded, rest[1:]) case "set-dns": @@ -245,6 +247,22 @@ func captureAdminLiveSnapshot(loaded *Database, args []string) adminLiveSnapshot } } return snapshot + case "set-password": + fs := flag.NewFlagSet("set-password", flag.ContinueOnError) + fs.SetOutput(io.Discard) + password := fs.String("password", "", "текущий пароль клиента") + _ = fs.String("new-password", "", "новый пароль клиента") + if err := fs.Parse(args[1:]); err != nil || strings.TrimSpace(*password) == "" { + return adminLiveSnapshot{} + } + snapshot := adminLiveSnapshot{password: strings.TrimSpace(*password)} + if entry := loaded.Passwords[snapshot.password]; entry != nil && entry.DeviceID != "" { + if dev := loaded.Devices[entry.DeviceID]; dev != nil { + copyOfDevice := *dev + snapshot.device = ©OfDevice + } + } + return snapshot default: return adminLiveSnapshot{} } @@ -259,6 +277,9 @@ func applyLiveAdminEffects(configDir string, loaded *Database, args []string, re if response.Password == nil { return errors.New("сервер создал клиента без пароля") } + if response.Password.Status != "active" { + break + } password := response.Password.Password if err := serverWrapKeys.AddPassword(password); err != nil { delete(loaded.Passwords, password) @@ -288,6 +309,25 @@ func applyLiveAdminEffects(configDir string, loaded *Database, args []string, re return fmt.Errorf("не удалось вернуть WRAP-ключ: %w", err) } upsertPeerInWG(wgDev, snapshot.device) + case "set-password": + if response.Password == nil { + return errors.New("сервер изменил пароль клиента без нового значения") + } + newPassword := response.Password.Password + if response.Password.Status == "active" { + if err := serverWrapKeys.AddPassword(newPassword); err != nil { + if entry := loaded.Passwords[newPassword]; entry != nil { + delete(loaded.Passwords, newPassword) + loaded.Passwords[snapshot.password] = entry + _ = saveAdminDB(configDir, loaded) + } + return fmt.Errorf("не удалось заменить WRAP-ключ: %w", err) + } + } + serverWrapKeys.RemovePassword(snapshot.password) + if !isAdminSnapshotDevice(loaded, snapshot) { + removePeerFromWG(wgDev, snapshot.device) + } case "set-dns", "update-settings": setServerDNS(loaded.DNS) setServerDefaultPorts(loaded.DefaultPorts) @@ -745,6 +785,9 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm label := fs.String("label", "", "название клиента") vkHash := fs.String("vk-hash", "", "VK-хеш или ссылка") ports := fs.String("ports", "", "DTLS,WG,TUN") + clientPassword := fs.String("client-password", "", "заданный пароль клиента") + expiresAt := fs.Int64("expires-at", -1, "точная дата окончания unix, 0 = бессрочно") + deactivated := fs.Bool("deactivated", false, "создать клиента отключённым") if err := fs.Parse(args); err != nil { return adminResponse{}, err } @@ -772,22 +815,45 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm normalizedHash = value } password := "" - for i := 0; i < 64; i++ { - candidate := generatePassword() - if _, exists := loaded.Passwords[candidate]; !exists { - password = candidate - break + if strings.TrimSpace(*clientPassword) != "" { + value, err := normalizeClientPassword(*clientPassword) + if err != nil { + return adminResponse{}, err + } + if value == loaded.MainPassword { + return adminResponse{}, errors.New("пароль клиента не должен совпадать с главным паролем") + } + if _, exists := loaded.Passwords[value]; exists { + return adminResponse{}, errors.New("клиент с таким паролем уже существует") + } + password = value + } else { + for i := 0; i < 64; i++ { + candidate := generatePassword() + if candidate == loaded.MainPassword { + continue + } + if _, exists := loaded.Passwords[candidate]; !exists { + password = candidate + break + } } } if password == "" { return adminResponse{}, errors.New("не удалось создать уникальный пароль") } entry := &PasswordEntry{ - Label: normalizePasswordLabel(*label), - VkHash: normalizedHash, - Ports: normalizedPorts, + Label: normalizePasswordLabel(*label), + VkHash: normalizedHash, + Ports: normalizedPorts, + IsDeactivated: *deactivated, } - if *days > 0 { + if *expiresAt >= 0 { + if *expiresAt > 0 && *expiresAt <= time.Now().Unix() { + return adminResponse{}, errors.New("срок импортируемого клиента уже истёк") + } + entry.ExpiresAt = *expiresAt + } else if *days > 0 { entry.ExpiresAt = time.Now().Add(time.Duration(*days) * 24 * time.Hour).Unix() } loaded.Passwords[password] = entry @@ -803,6 +869,48 @@ func adminCreatePassword(configDir string, loaded *Database, args []string) (adm }, nil } +func adminSetPassword(configDir string, loaded *Database, args []string) (adminResponse, error) { + fs := flag.NewFlagSet("set-password", flag.ContinueOnError) + fs.SetOutput(io.Discard) + oldPassword := fs.String("password", "", "текущий пароль клиента") + newPasswordRaw := fs.String("new-password", "", "новый пароль клиента") + if err := fs.Parse(args); err != nil { + return adminResponse{}, err + } + oldValue := strings.TrimSpace(*oldPassword) + entry, err := requireAdminPassword(loaded, oldValue) + if err != nil { + return adminResponse{}, err + } + newValue, err := normalizeClientPassword(*newPasswordRaw) + if err != nil { + return adminResponse{}, err + } + if newValue == oldValue { + return adminResponse{}, errors.New("новый пароль совпадает с текущим") + } + if newValue == loaded.MainPassword { + return adminResponse{}, errors.New("пароль клиента не должен совпадать с главным паролем") + } + if _, exists := loaded.Passwords[newValue]; exists { + return adminResponse{}, errors.New("клиент с таким паролем уже существует") + } + delete(loaded.Passwords, oldValue) + loaded.Passwords[newValue] = entry + if err := saveAdminDB(configDir, loaded); err != nil { + delete(loaded.Passwords, newValue) + loaded.Passwords[oldValue] = entry + return adminResponse{}, err + } + return adminResponse{ + OK: true, + Message: "Пароль клиента изменён", + RestartRequired: true, + Server: buildAdminServerInfo(configDir, loaded), + Password: ptrAdminPasswordInfo(buildAdminPasswordInfo(loaded, newValue, entry)), + }, nil +} + func adminDeletePassword(configDir string, loaded *Database, args []string) (adminResponse, error) { password, err := adminPasswordArg("delete", args) if err != nil { diff --git a/admin_test.go b/admin_test.go index 8b84077..a756d78 100644 --- a/admin_test.go +++ b/admin_test.go @@ -167,4 +167,76 @@ func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) { if serverWrapKeys.Count() != 0 { t.Fatalf("expected deletion to remove live WRAP key, got %d", serverWrapKeys.Count()) } + + custom := "ABCDEFGHJKLMNPQR" + createdCustom := request( + "create", "--client-password", custom, "--expires-at", "0", "--deactivated", + "--label", "Перенос", "--vk-hash", "abcdefghijklmnop", "--ports", "56000,56001,9000", + ) + if createdCustom.Password == nil || createdCustom.Password.Password != custom || createdCustom.Password.Status != "deactivated" { + t.Fatalf("custom client was not created intact: %#v", createdCustom.Password) + } + if serverWrapKeys.Count() != 0 { + t.Fatalf("deactivated custom client must not add a live WRAP key, got %d", serverWrapKeys.Count()) + } + deactivatedPassword := "RSTUVWXYZ2345678" + changedDeactivated := request("set-password", "--password", custom, "--new-password", deactivatedPassword) + if changedDeactivated.Password == nil || changedDeactivated.Password.Status != "deactivated" || serverWrapKeys.Count() != 0 { + t.Fatalf("deactivated password change enabled access: %#v keys=%d", changedDeactivated.Password, serverWrapKeys.Count()) + } + custom = deactivatedPassword + request("activate", "--password", custom) + newPassword := "23456789ABCDEFGH" + changed := request("set-password", "--password", custom, "--new-password", newPassword) + if changed.Password == nil || changed.Password.Password != newPassword || changed.Password.Label != "Перенос" { + t.Fatalf("password change lost client data: %#v", changed.Password) + } + if db.Passwords[custom] != nil || db.Passwords[newPassword] == nil { + t.Fatal("password map key was not replaced") + } + if serverWrapKeys.Count() != 1 { + t.Fatalf("password change must replace one live WRAP key, got %d", serverWrapKeys.Count()) + } + request("delete", "--password", newPassword) +} + +func TestClientPasswordValidation(t *testing.T) { + valid := []string{"ABCDEFGHJKLMNPQR", "abcdefghjkmnpqrs", "23456789ABCDEFGH"} + for _, value := range valid { + if normalized, err := normalizeClientPassword(value); err != nil || normalized != value { + t.Fatalf("valid password %q rejected: %v", value, err) + } + } + invalid := []string{"short", "ABCDEFGHJKLMNPQ0", "ABCDEFGHJKLMNPQ_", "ABCDEFGHJKLMNPQRS"} + for _, value := range invalid { + if _, err := normalizeClientPassword(value); err == nil { + t.Fatalf("invalid password %q accepted", value) + } + } +} + +func TestAdminCreateRejectsPasswordConflicts(t *testing.T) { + configDir := t.TempDir() + loaded := &Database{ + MainPassword: "ABCDEFGHJKLMNPQR", + DefaultPorts: "56000,56001,9000", + MaxPasswords: 10, + Passwords: map[string]*PasswordEntry{ + "RSTUVWXYZ2345678": {}, + }, + Devices: make(map[string]*ClientDevice), + } + if _, err := adminCreatePassword(configDir, loaded, []string{"--client-password", loaded.MainPassword}); err == nil { + t.Fatal("main password was accepted as a client password") + } + if _, err := adminCreatePassword(configDir, loaded, []string{"--client-password", "RSTUVWXYZ2345678"}); err == nil { + t.Fatal("duplicate client password was accepted") + } + if _, err := adminCreatePassword(configDir, loaded, []string{"--client-password", "23456789ABCDEFGH", "--expires-at", "1"}); err == nil { + t.Fatal("expired imported client was accepted") + } + loaded.MaxPasswords = len(loaded.Passwords) + if _, err := adminCreatePassword(configDir, loaded, []string{"--client-password", "23456789ABCDEFGH"}); err == nil { + t.Fatal("client limit was ignored") + } } diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 622032a..b19911e 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -5,7 +5,7 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") } -val appVersionName = "2" +val appVersionName = "3" val releaseApkBaseName = "WDTT-Plus" val localProperties = Properties() @@ -22,9 +22,9 @@ android { applicationId = "com.wdtt.plus" minSdk = 28 targetSdk = 35 - versionCode = 2 + versionCode = 3 versionName = appVersionName - buildConfigField("String", "MOD_RELEASE_DATE", "\"03.07.2026\"") + buildConfigField("String", "MOD_RELEASE_DATE", "\"04.07.2026\"") testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" vectorDrawables { diff --git a/app/src/main/java/com/wdtt/plus/ClientTransferCodec.kt b/app/src/main/java/com/wdtt/plus/ClientTransferCodec.kt new file mode 100644 index 0000000..01e4021 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ClientTransferCodec.kt @@ -0,0 +1,114 @@ +package com.wdtt.plus + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import org.json.JSONObject +import java.security.SecureRandom + +private const val CLIENT_TRANSFER_FORMAT = "wdtt-plus-client" +private const val CLIENT_TRANSFER_VERSION = 1 + +data class ClientTransferPayload( + val password: String, + val label: String, + val vkHash: String, + val expiresAt: Long, + val deactivated: Boolean, + val createdAt: Long = System.currentTimeMillis() +) + +object ClientPasswordRules { + const val LENGTH = 16 + const val ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789" + private val random = SecureRandom() + + fun generate(): String = buildString(LENGTH) { + repeat(LENGTH) { append(ALPHABET[random.nextInt(ALPHABET.length)]) } + } + + fun validate(value: String): String? = when { + value.length != LENGTH -> "Пароль должен содержать ровно $LENGTH символов." + value.any { it !in ALPHABET } -> "Допустимы только безопасные латинские буквы и цифры без 0, 1, I, i, O, o и l." + else -> null + } +} + +object ClientTransferCodec { + fun encode(payload: ClientTransferPayload): String { + ClientPasswordRules.validate(payload.password)?.let { throw IllegalArgumentException(it) } + require(payload.expiresAt >= 0) { "Некорректный срок клиента." } + require(payload.label.length <= 40 && payload.label.none(Char::isISOControl)) { "Название клиента повреждено или слишком длинное." } + val vkHash = normalizeVkHashes(payload.vkHash) + return JSONObject() + .put("format", CLIENT_TRANSFER_FORMAT) + .put("version", CLIENT_TRANSFER_VERSION) + .put("created_at", payload.createdAt) + .put("password", payload.password) + .put("label", payload.label.trim()) + .put("vk_hash", vkHash) + .put("expires_at", payload.expiresAt) + .put("deactivated", payload.deactivated) + .toString() + } + + fun decode(value: String): ClientTransferPayload { + val json = runCatching { JSONObject(value.trim()) } + .getOrElse { throw IllegalArgumentException("Данные клиента повреждены или имеют неверный формат.") } + require(json.optString("format") == CLIENT_TRANSFER_FORMAT) { "Это не файл переноса клиента WDTT Plus." } + require(json.optInt("version", -1) == CLIENT_TRANSFER_VERSION) { "Версия файла клиента не поддерживается." } + val password = json.optString("password") + ClientPasswordRules.validate(password)?.let { throw IllegalArgumentException(it) } + val label = json.optString("label").trim() + require(label.length <= 40 && label.none(Char::isISOControl)) { "Название клиента повреждено или длиннее 40 символов." } + val vkHash = normalizeVkHashes(json.optString("vk_hash")) + val expiresAt = json.optLong("expires_at", -1) + require(expiresAt >= 0) { "В файле указан некорректный срок клиента." } + return ClientTransferPayload( + password = password, + label = label, + vkHash = vkHash, + expiresAt = expiresAt, + deactivated = json.optBoolean("deactivated", false), + createdAt = json.optLong("created_at", 0) + ) + } + + fun isClientTransfer(value: String): Boolean = runCatching { + val json = JSONObject(value.trim()) + json.optString("format") == CLIENT_TRANSFER_FORMAT + }.getOrDefault(false) + + fun fromClient(client: ServerClientInfo): ClientTransferPayload = ClientTransferPayload( + password = client.password, + label = client.label, + vkHash = client.vkHash, + expiresAt = client.expiresAt, + deactivated = client.status == "deactivated" + ) + + private fun normalizeVkHashes(value: String): String { + val clean = value.trim() + if (clean.isBlank()) return "" + require(clean.length <= 4096 && clean.none(Char::isISOControl)) { "Поле VK-хешей повреждено." } + val hashes = clean.split(Regex("[,\\s]+")) + .map { VkJoinLink.extractHash(it) } + .filter { it.isNotBlank() } + require(hashes.isNotEmpty() && hashes.all { it.length >= 16 } && hashes.none { it.contains('/') || it.contains('\\') }) { + "VK-хеши в переносе имеют неверный формат." + } + return hashes.distinct().joinToString(",") + } +} + +object ClientTransferInbox { + private val mutablePending = MutableStateFlow(null) + val pending = mutablePending.asStateFlow() + + fun offer(value: String) { + mutablePending.value = value.trim() + } + + fun clear(value: String) { + if (mutablePending.value == value) mutablePending.value = null + } +} diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt index 60eb0e4..b691b72 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -217,7 +217,9 @@ class MainActivity : ComponentActivity() { } ?: 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" + type == "application/vnd.wdtt.plus.transfer" || + type == "application/vnd.wdtt.plus.client" || + type == "application/octet-stream" } == true if (streamFirst && streamUri != null) { handleIncomingUri(streamUri, intent.type) @@ -252,6 +254,10 @@ class MainActivity : ComponentActivity() { private fun handleIncomingTransferText(value: String) { val link = WdttTransferCodec.extractWdttLink(value) when { + ClientTransferCodec.isClientTransfer(value) -> { + ClientTransferInbox.offer(value) + wdttDeepLinkMessage = "Распознан перенос клиента. В режиме «Я — админ» откройте «Деплой» → «Клиенты и сервер»: перед импортом приложение покажет проверку данных и целевого сервера." + } link != null -> handleIncomingWdttLink(link) WdttTransferCodec.isAdminTransfer(value) -> pendingAdminTransfer = value.trim() WdttTransferCodec.documentFormat(value) == "wdtt-server-backup" -> { @@ -292,7 +298,7 @@ class MainActivity : ComponentActivity() { wdttDeepLinkMessage = if (result == null) { WdttDeepLink.validate(plan.link).userMessage() } else { - val profileLabel = "VPN ${result.targetProfile + 1}" + val profileLabel = vpnProfileDisplayName(result.targetProfile, store.profileNames.first()) val action = if (result.overwritten) "перезаписана" else "добавлена" val mode = if (result.storedAsLink) "сохранена в режиме ссылки" else "разобрана, поля подключения заполнены" "Ссылка wdtt:// $action в профиль $profileLabel: $mode." @@ -641,10 +647,12 @@ fun MainScreen( val focusManager = LocalFocusManager.current val scope = rememberCoroutineScope() val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0) + val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false) val interfaceRole by settingsStore.interfaceRole.collectAsStateWithLifecycle(initialValue = "") val permissionOnboardingComplete by settingsStore.permissionOnboardingComplete.collectAsStateWithLifecycle(initialValue = false) val migrationNoticeV2Shown by settingsStore.migrationNoticeV2Shown.collectAsStateWithLifecycle(initialValue = true) + val migrationNoticeV3Shown by settingsStore.migrationNoticeV3Shown.collectAsStateWithLifecycle(initialValue = true) val isAdminInterface = interfaceRole == "admin" val isUpdatedInstall = remember(context) { runCatching { @@ -944,9 +952,13 @@ fun MainScreen( // Floating theme toolbar overlay FloatingToolbar( activeProfile = activeProfile, + profileNames = profileNames, onActiveProfileChange = { profile -> scope.launch { settingsStore.saveActiveProfile(profile) } }, + onProfileNameChange = { profile, name -> + scope.launch { settingsStore.saveProfileName(profile, name) } + }, interfaceRole = interfaceRole, onInterfaceRoleChange = { role -> scope.launch { settingsStore.saveInterfaceRole(role) } @@ -997,6 +1009,38 @@ fun MainScreen( ) } + if ( + BuildConfig.VERSION_CODE == 3 && + isAdminInterface && + isUpdatedInstall && + !migrationNoticeV3Shown + ) { + AlertDialog( + onDismissRequest = {}, + properties = DialogProperties( + dismissOnBackPress = false, + dismissOnClickOutside = false + ), + title = { Text("Требуется обновление сервера") }, + text = { + Text( + "Для корректной работы новых функций необходимо обновить установку серверной части во вкладке «Деплой».\n\n" + + "Выберите установку с сохранением данных. Настройки, клиенты и выданные доступы сохранятся — будет обновлена только серверная часть.\n\n" + + "Установку с нуля выполнять не нужно." + ) + }, + confirmButton = { + Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + Button( + onClick = { scope.launch { settingsStore.saveMigrationNoticeV3Shown() } } + ) { + Text("Хорошо") + } + } + } + ) + } + if (showTransferCenter) { TransferCenterDialog( settingsStore = settingsStore, @@ -1126,7 +1170,7 @@ fun MainScreen( } pendingWdttDeepLinkPlan?.let { plan -> - val profileLabel = "VPN ${plan.targetProfile + 1}" + val profileLabel = vpnProfileDisplayName(plan.targetProfile, profileNames) AlertDialog( onDismissRequest = onCancelWdttDeepLinkOverwrite, title = { Text("Профили VPN заполнены") }, @@ -1138,7 +1182,7 @@ fun MainScreen( FilterChip( selected = plan.targetProfile == profile, onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) }, - label = { Text("VPN ${profile + 1}") } + label = { Text(vpnProfileDisplayName(profile, profileNames)) } ) } } diff --git a/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt b/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt index f8919a7..6bb11cb 100644 --- a/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt +++ b/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt @@ -14,6 +14,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.Job import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch class QuickToggleTileService : TileService() { @@ -27,8 +28,15 @@ class QuickToggleTileService : TileService() { stateJob?.cancel() stateJob = scope.launch { try { - TunnelManager.running.collect { running -> - updateTile(running) + val settingsStore = SettingsStore(this@QuickToggleTileService) + combine( + TunnelManager.running, + settingsStore.activeProfile, + settingsStore.profileNames + ) { running, activeProfile, profileNames -> + Triple(running, activeProfile, profileNames) + }.collect { (running, activeProfile, profileNames) -> + updateTile(running, activeProfile, profileNames) } } catch (e: Exception) { Log.e("QuickToggleTile", "Error collecting running state", e) @@ -89,14 +97,22 @@ class QuickToggleTileService : TileService() { super.onDestroy() } - private fun updateTile(running: Boolean) { + private fun updateTile(running: Boolean, activeProfile: Int, profileNames: List) { runCatching { + val profile = activeProfile.coerceIn(0, 2) + val profileLabel = vpnProfileDisplayName(profile, profileNames) + val defaultProfileLabel = vpnProfileDefaultName(profile) + val profileIsDefault = profileLabel == defaultProfileLabel qsTile?.apply { - label = "WDTT Plus" + label = when { + !running -> "WDTT Plus" + profileIsDefault -> "WDTT Plus $profileLabel" + else -> profileLabel + } icon = Icon.createWithResource(this@QuickToggleTileService, R.drawable.ic_tile_logo) state = if (running) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE if (Build.VERSION.SDK_INT >= 29) { - subtitle = if (running) "Подключено" else "Отключено" + subtitle = if (running) "" else "Отключено" } updateTile() } diff --git a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt index 4b63837..0690cb3 100644 --- a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt +++ b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt @@ -124,7 +124,10 @@ data class ServerClientCreateRequest( val days: Int, val label: String, val vkHash: String, - val ports: String + val ports: String, + val password: String? = null, + val expiresAt: Long? = null, + val deactivated: Boolean = false ) data class ServerAdminActionResult( @@ -162,10 +165,30 @@ object ServerAdminClient { 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()) + request.password?.takeIf { it.isNotBlank() }?.let { args += listOf("--client-password", it) } + request.expiresAt?.let { args += listOf("--expires-at", it.coerceAtLeast(0).toString()) } + if (request.deactivated) args += "--deactivated" actionFromResponse(callAdmin(ssh, target, args)) } } + suspend fun importClient( + target: ServerAdminTarget, + payload: ClientTransferPayload, + targetPorts: String + ): ServerAdminActionResult = create( + target, + ServerClientCreateRequest( + days = 0, + label = payload.label, + vkHash = payload.vkHash, + ports = targetPorts, + password = payload.password, + expiresAt = payload.expiresAt, + deactivated = payload.deactivated + ) + ) + suspend fun delete(target: ServerAdminTarget, password: String): ServerAdminActionResult = runPasswordAction(target, "delete", password) @@ -208,6 +231,9 @@ object ServerAdminClient { suspend fun setPorts(target: ServerAdminTarget, password: String, ports: String): ServerAdminActionResult = runArgsAction(target, listOf("set-ports", "--password", password, "--ports", ports)) + suspend fun setPassword(target: ServerAdminTarget, password: String, newPassword: String): ServerAdminActionResult = + runArgsAction(target, listOf("set-password", "--password", password, "--new-password", newPassword)) + suspend fun updateClient(target: ServerAdminTarget, password: String, label: String, hash: String, ports: String): ServerAdminActionResult = withContext(Dispatchers.IO) { withSession(target) { ssh -> @@ -509,6 +535,8 @@ object ServerAdminClient { "на сервере не найдена база WDTT Plus. Сначала выполните деплой." "admin_socket_unavailable" in lower -> "сервер ещё не поддерживает управление без перезапуска. Переустановите сервер из этой версии WDTT Plus." + "неизвестная admin-команда" in lower || "flag provided but not defined" in lower -> + "сервер ещё не поддерживает перенос или смену пароля клиента. Выполните установку сервера с сохранением данных из этой версии WDTT Plus." "главный пароль" in lower -> "главный пароль администратора не совпадает с сервером." "no such file" in lower || "not found" in lower && "wdtt-server" in lower -> diff --git a/app/src/main/java/com/wdtt/plus/SettingsStore.kt b/app/src/main/java/com/wdtt/plus/SettingsStore.kt index 069f136..9707bb8 100644 --- a/app/src/main/java/com/wdtt/plus/SettingsStore.kt +++ b/app/src/main/java/com/wdtt/plus/SettingsStore.kt @@ -218,6 +218,7 @@ class SettingsStore(context: Context) { companion object { private val Context.dataStore by preferencesDataStore("settings") private val ACTIVE_PROFILE = intPreferencesKey("active_profile") + private val PROFILE_NAME = stringPreferencesKey("profile_name") private val SHOW_SYSTEM_APPS = booleanPreferencesKey("show_system_apps") private val LOGGING_ENABLED = booleanPreferencesKey("logging_enabled") private val WDTT_LINK = stringPreferencesKey("wdtt_link") @@ -297,6 +298,7 @@ class SettingsStore(context: Context) { 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 MIGRATION_NOTICE_V3_SHOWN = booleanPreferencesKey("migration_notice_v3_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") @@ -311,7 +313,7 @@ class SettingsStore(context: Context) { val newName = "${baseKey.name}_$profile" @Suppress("UNCHECKED_CAST") 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 + PROFILE_NAME, PEER, VK_HASHES, SECONDARY_VK_HASH, PROTOCOL, SNI, USER_AGENT, DEPLOY_IP, DEPLOY_LOGIN, DEPLOY_PASSWORD, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_SSH_PORT, DEPLOY_DNS1, DEPLOY_DNS2, EXCLUDED_APPS, BLACKLIST_APPS, WHITELIST_APPS, CONNECTION_PASSWORD, CONNECTION_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_ADMIN_ID, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_BOT_TOKEN, DEPLOY_BOT_TOKEN_ENCRYPTED, PROXY_MODE, PROXY_HOST, CAPTCHA_MODE, CAPTCHA_SOLVE_METHOD, CAPTCHA_WBV_SOLVE_METHOD, WDTT_LINK, SELECTED_FINGERPRINT, ACTIVE_CLIENT_IDS -> stringPreferencesKey(newName) as Preferences.Key WORKERS_PER_HASH, VK_HASH_NEXT_SLOT, LISTEN_PORT, SERVER_DTLS_PORT, SERVER_WG_PORT, PROXY_PORT -> intPreferencesKey(newName) as Preferences.Key MANUAL_PORTS_ENABLED, NO_DTLS, NO_DNS, IS_WHITELIST, WDTT_LINK_MODE, VKCALLS_PREFLIGHT, DETAILED_LOGS -> booleanPreferencesKey(newName) as Preferences.Key else -> throw IllegalArgumentException("Unsupported key type: ${baseKey.name}") @@ -330,6 +332,11 @@ class SettingsStore(context: Context) { } val activeProfile: Flow = dataStore.data.map { it[ACTIVE_PROFILE] ?: 0 } + val profileNames: Flow> = dataStore.data.map { prefs -> + (0 until VPN_PROFILE_COUNT).map { profile -> + prefs[getProfileKey(PROFILE_NAME, profile)].orEmpty() + } + } val showSystemApps: Flow = dataStore.data.map { it[SHOW_SYSTEM_APPS] ?: false } val loggingEnabled: Flow = dataStore.data.map { it[LOGGING_ENABLED] ?: true } val wdttLink: Flow = dataStore.data.map { prefs -> @@ -515,6 +522,7 @@ class SettingsStore(context: Context) { val updateDialogLastAction: Flow = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION] ?: "" } val updateDialogLastActionAt: Flow = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_AT] ?: 0L } val migrationNoticeV2Shown: Flow = dataStore.data.map { it[MIGRATION_NOTICE_V2_SHOWN] ?: false } + val migrationNoticeV3Shown: Flow = dataStore.data.map { it[MIGRATION_NOTICE_V3_SHOWN] ?: false } val deployClientsSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: true } val deployOutboundSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_OUTBOUND_SECTION_EXPANDED] ?: false } val deployMigrationSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_MIGRATION_SECTION_EXPANDED] ?: false } @@ -621,6 +629,12 @@ class SettingsStore(context: Context) { } } + suspend fun saveMigrationNoticeV3Shown() { + dataStore.edit { prefs -> + prefs[MIGRATION_NOTICE_V3_SHOWN] = true + } + } + suspend fun saveDeployClientsSectionExpanded(expanded: Boolean) { dataStore.edit { prefs -> prefs[DEPLOY_CLIENTS_SECTION_EXPANDED] = expanded @@ -645,6 +659,19 @@ class SettingsStore(context: Context) { } } + suspend fun saveProfileName(profile: Int, name: String) { + dataStore.edit { prefs -> + val index = profile.coerceIn(0, VPN_PROFILE_COUNT - 1) + val clean = normalizeVpnProfileName(name) + val key = getProfileKey(PROFILE_NAME, index) + if (clean.isBlank() || clean == vpnProfileDefaultName(index)) { + prefs.remove(key) + } else { + prefs[key] = clean + } + } + } + suspend fun saveShowSystemApps(enabled: Boolean) { dataStore.edit { prefs -> prefs[SHOW_SYSTEM_APPS] = enabled @@ -696,8 +723,12 @@ class SettingsStore(context: Context) { ) val link = WdttTransferCodec.buildConnectionLink(parts) val validation = WdttDeepLink.validate(link) + val profileLabel = vpnProfileDisplayName( + profile, + (0 until VPN_PROFILE_COUNT).map { index -> prefs[getProfileKey(PROFILE_NAME, index)].orEmpty() } + ) require(validation.canStartVpn) { - "Профиль VPN ${profile + 1} заполнен не полностью. Проверьте адрес, порты, пароль и VK-хеши." + "Профиль «$profileLabel» заполнен не полностью. Проверьте адрес, порты, пароль и VK-хеши." } link }.first() @@ -745,6 +776,7 @@ class SettingsStore(context: Context) { 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") + put("profileName", prefs[getProfileKey(PROFILE_NAME, profile)].orEmpty()) }) } JSONObject().apply { @@ -815,6 +847,13 @@ class SettingsStore(context: Context) { 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") + val importedName = normalizeVpnProfileName(item.optString("profileName")) + val profileNameKey = getProfileKey(PROFILE_NAME, profile) + if (importedName.isBlank() || importedName == vpnProfileDefaultName(profile)) { + prefs.remove(profileNameKey) + } else { + prefs[profileNameKey] = importedName + } } prefs[ACTIVE_PROFILE] = root.optInt("activeProfile", 0).coerceIn(0, VPN_PROFILE_COUNT - 1) prefs[THEME_MODE] = root.optString("themeMode", "system") @@ -1207,3 +1246,16 @@ class SettingsStore(context: Context) { private fun JSONObject.safePort(name: String, fallback: Int): Int = optInt(name, fallback).takeIf { it in 1..65535 } ?: fallback } + +fun vpnProfileDefaultName(profile: Int): String = "VPN ${profile.coerceIn(0, 2) + 1}" + +fun normalizeVpnProfileName(name: String): String = + name + .replace(Regex("\\s+"), " ") + .trim() + .take(48) + +fun vpnProfileDisplayName(profile: Int, names: List): String { + val clean = normalizeVpnProfileName(names.getOrNull(profile).orEmpty()) + return clean.ifBlank { vpnProfileDefaultName(profile) } +} diff --git a/app/src/main/java/com/wdtt/plus/TunnelService.kt b/app/src/main/java/com/wdtt/plus/TunnelService.kt index 541d5f1..d7c25c3 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelService.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelService.kt @@ -24,6 +24,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.isActive import kotlinx.coroutines.launch @@ -44,8 +45,11 @@ class TunnelService : Service() { private var wakeLock: PowerManager.WakeLock? = null private var wifiLock: WifiManager.WifiLock? = null private var updateJob: Job? = null + private var profileNameJob: Job? = null private var networkChangeJob: Job? = null + private var lastNotificationTitle: String? = null private var lastNotificationText: String? = null + private var notificationProfileTitle: String = "WDTT Plus" // Network Monitoring private var connectivityManager: ConnectivityManager? = null @@ -153,13 +157,16 @@ class TunnelService : Service() { CaptchaWebViewManager.onTunnelStart(applicationContext) TunnelManager.start(this, params) + startNotificationProfileWatcher() startStatsUpdater() } private fun stopTunnel() { updateJob?.cancel() + profileNameJob?.cancel() networkChangeJob?.cancel() wakeRescueJob?.cancel() + profileNameJob = null networkChangeJob = null wakeRescueJob = null @@ -177,6 +184,26 @@ class TunnelService : Service() { stopSelf() } + private fun startNotificationProfileWatcher() { + profileNameJob?.cancel() + val settingsStore = SettingsStore(applicationContext) + profileNameJob = TunnelManager.scope.launch(Dispatchers.Main) { + combine( + settingsStore.activeProfile, + settingsStore.profileNames + ) { activeProfile, profileNames -> + val profile = activeProfile.coerceIn(0, 2) + val profileLabel = vpnProfileDisplayName(profile, profileNames) + "WDTT Plus · $profileLabel" + }.collect { prefix -> + notificationProfileTitle = prefix + if (TunnelManager.running.value && !isTunnelPaused) { + updateNotification(buildTunnelNotificationText()) + } + } + } + } + private fun registerScreenStateReceiver() { if (screenStateReceiver != null) return screenStateReceiver = object : BroadcastReceiver() { @@ -647,7 +674,7 @@ class TunnelService : Service() { ) return NotificationCompat.Builder(this, TUNNEL_NOTIFICATION_CHANNEL_ID) - .setContentTitle("WDTT Plus") + .setContentTitle(notificationProfileTitle) .setContentText(text) .setSmallIcon(R.drawable.ic_notification_icon) .setOngoing(true) @@ -677,7 +704,9 @@ class TunnelService : Service() { } private fun updateNotification(text: String) { - if (lastNotificationText == text) return + val title = notificationProfileTitle + if (lastNotificationTitle == title && lastNotificationText == text) return + lastNotificationTitle = title lastNotificationText = text val notification = createNotification(text) getSystemService(NotificationManager::class.java).notify(TUNNEL_NOTIFICATION_ID, notification) diff --git a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt index 7ead243..e417a83 100644 --- a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt @@ -57,6 +57,7 @@ import com.wdtt.plus.ServerAdminTarget import com.wdtt.plus.SettingsStore import com.wdtt.plus.TunnelManager import com.wdtt.plus.WDTTColors +import com.wdtt.plus.vpnProfileDisplayName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map @@ -265,6 +266,8 @@ fun DeployTab( LaunchedEffect(Unit) { DeployManager.init(context) } val savedIp by settingsStore.deployIp.collectAsStateWithLifecycle(initialValue = "") + val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0) + val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) val savedLogin by settingsStore.deployLogin.collectAsStateWithLifecycle(initialValue = "") val savedPassword by settingsStore.deployPassword.collectAsStateWithLifecycle(initialValue = "") val savedPeer by settingsStore.peer.collectAsStateWithLifecycle(initialValue = "") @@ -812,11 +815,18 @@ fun DeployTab( .verticalScroll(deployScrollState), verticalArrangement = Arrangement.spacedBy(12.dp) ) { - Text( - "Настройки сервера", - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurface - ) + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + "Настройки сервера", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface + ) + Text( + "(${vpnProfileDisplayName(activeProfile, profileNames)})", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } val importCanProvideMainPassword = selectedImportMode == ServerImportMode.Replace && selectedImportBackup?.mainPassword?.isNotBlank() == true diff --git a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt index 6f220a6..389bb6a 100644 --- a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt +++ b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt @@ -11,9 +11,11 @@ import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.background import androidx.compose.foundation.border +import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.clickable import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -35,8 +37,11 @@ import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.wdtt.plus.SettingsStore +import com.wdtt.plus.normalizeVpnProfileName +import com.wdtt.plus.vpnProfileDisplayName import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -52,11 +57,13 @@ import androidx.compose.material.icons.filled.Share import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties -@OptIn(ExperimentalLayoutApi::class) +@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class) @Composable fun FloatingToolbar( activeProfile: Int, + profileNames: List, onActiveProfileChange: (Int) -> Unit, + onProfileNameChange: (Int, String) -> Unit, interfaceRole: String, onInterfaceRoleChange: (String) -> Unit, currentTheme: String, @@ -89,6 +96,8 @@ fun FloatingToolbar( var isExpanded by rememberSaveable { mutableStateOf(false) } var tabHeightPx by remember { mutableFloatStateOf(0f) } var panelHeightPx by remember { mutableFloatStateOf(0f) } + var renamingProfile by remember { mutableStateOf(null) } + var profileNameInput by rememberSaveable { mutableStateOf("") } val tabWidthDp = 42.dp val tabHeightDp = 52.dp @@ -219,20 +228,29 @@ fun FloatingToolbar( FlowRow( modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), verticalArrangement = Arrangement.spacedBy(8.dp) ) { listOf(0, 1, 2).forEach { profile -> val selected = profile == activeProfile - val profileLabel = "VPN ${profile + 1}" + val profileLabel = vpnProfileDisplayName(profile, profileNames) + val profileShape = RoundedCornerShape(12.dp) Surface( - onClick = { onActiveProfileChange(profile) }, - shape = RoundedCornerShape(12.dp), + shape = profileShape, color = if (selected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), - modifier = Modifier.weight(1f).widthIn(min = 62.dp) + modifier = Modifier + .widthIn(min = 72.dp, max = 180.dp) + .clip(profileShape) + .combinedClickable( + onClick = { onActiveProfileChange(profile) }, + onLongClick = { + renamingProfile = profile + profileNameInput = profileLabel + } + ) ) { Box( - modifier = Modifier.padding(vertical = 8.dp), + modifier = Modifier.padding(horizontal = 6.dp, vertical = 8.dp), contentAlignment = Alignment.Center ) { Text( @@ -240,7 +258,8 @@ fun FloatingToolbar( style = MaterialTheme.typography.bodyMedium, fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal, color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface, - fontSize = 12.sp + fontSize = 12.sp, + textAlign = TextAlign.Center ) } } @@ -532,6 +551,43 @@ fun FloatingToolbar( } } } + + renamingProfile?.let { profile -> + AlertDialog( + onDismissRequest = { renamingProfile = null }, + title = { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text("Название профиля") + IconButton(onClick = { renamingProfile = null }) { + Icon(Icons.Filled.Close, contentDescription = "Закрыть") + } + } + }, + text = { + OutlinedTextField( + value = profileNameInput, + onValueChange = { profileNameInput = normalizeVpnProfileName(it) }, + label = { Text("Название") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + }, + confirmButton = { + Button( + onClick = { + onProfileNameChange(profile, profileNameInput) + renamingProfile = null + } + ) { + Text("Сохранить") + } + } + ) + } } } diff --git a/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt index 0b75fe6..7aa3c4c 100644 --- a/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt +++ b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt @@ -49,6 +49,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.InsertDriveFile import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.CameraAlt import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.ChevronLeft import androidx.compose.material.icons.filled.ChevronRight @@ -57,6 +58,9 @@ import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material.icons.filled.FilterList +import androidx.compose.material.icons.filled.FileOpen +import androidx.compose.material.icons.filled.Image +import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.Link import androidx.compose.material.icons.filled.LockOpen import androidx.compose.material.icons.filled.PauseCircle @@ -106,6 +110,14 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.journeyapps.barcodescanner.ScanContract +import com.journeyapps.barcodescanner.ScanOptions +import com.wdtt.plus.ClientPasswordRules +import com.wdtt.plus.ClientTransferCodec +import com.wdtt.plus.ClientTransferInbox +import com.wdtt.plus.ClientTransferPayload +import com.wdtt.plus.QrCaptureActivity import com.wdtt.plus.ServerAdminActionResult import com.wdtt.plus.ServerAdminClient import com.wdtt.plus.ServerAdminProfileInfo @@ -129,6 +141,7 @@ private enum class ClientWizardStep { Label, Hash, Ports, + Password, Confirm } @@ -178,12 +191,18 @@ fun ServerClientsSection( var busy by remember { mutableStateOf(false) } var status by rememberSaveable { mutableStateOf("") } var showCreateWizard by rememberSaveable { mutableStateOf(false) } + var showImportMethods by rememberSaveable { mutableStateOf(false) } + var pendingImport by remember { mutableStateOf(null) } + var exportClient by remember { mutableStateOf(null) } + var passwordClient by remember { mutableStateOf(null) } + var changedPasswordClient by remember { mutableStateOf(null) } var pendingAction by remember { mutableStateOf(null) } var expiryClient by remember { mutableStateOf(null) } var qrData by remember { mutableStateOf?>(null) } var detailsClient by remember { mutableStateOf(null) } var showServerTools by rememberSaveable { mutableStateOf(false) } var createdClient by remember { mutableStateOf(null) } + var importedClient by remember { mutableStateOf(null) } var filtersExpanded by rememberSaveable { mutableStateOf(false) } var statusFilter by rememberSaveable { mutableStateOf(ClientStatusFilter.All) } var bindingFilter by rememberSaveable { mutableStateOf(ClientBindingFilter.All) } @@ -192,6 +211,7 @@ fun ServerClientsSection( var clientSearchFocused by remember { mutableStateOf(false) } var clientSearch by clientsViewModel.clientSearch var selectedClientIndex by clientsViewModel.selectedClientIndex + val inboxTransfer by ClientTransferInbox.pending.collectAsStateWithLifecycle() val arrowRotation by animateFloatAsState( targetValue = if (expanded) 180f else 0f, label = "server_clients_arrow_rotation" @@ -229,6 +249,40 @@ fun ServerClientsSection( mainPassword = mainPassword ) + fun acceptClientTransfer(raw: String) { + runCatching { ClientTransferCodec.decode(raw) } + .onSuccess { + pendingImport = it + showImportMethods = false + } + .onFailure { status = "Ошибка: ${it.message ?: "данные клиента не распознаны"}" } + } + + val importCameraLauncher = rememberLauncherForActivityResult(ScanContract()) { result -> + result.contents?.takeIf { it.isNotBlank() }?.let(::acceptClientTransfer) + } + val importGalleryLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> + if (uri != null) scope.launch { + runCatching { withContext(Dispatchers.IO) { TransferFiles.decodeQrImage(context, uri) } } + .onSuccess(::acceptClientTransfer) + .onFailure { status = "Ошибка: ${it.message ?: "QR-код не прочитан"}" } + } + } + val importFileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> + if (uri != null) scope.launch { + runCatching { withContext(Dispatchers.IO) { TransferFiles.readText(context, uri) } } + .onSuccess(::acceptClientTransfer) + .onFailure { status = "Ошибка: ${it.message ?: "файл клиента не прочитан"}" } + } + } + + LaunchedEffect(inboxTransfer) { + inboxTransfer?.let { raw -> + acceptClientTransfer(raw) + ClientTransferInbox.clear(raw) + } + } + fun refreshClients() { if (!targetReady || busy) return busy = true @@ -355,12 +409,15 @@ fun ServerClientsSection( Icon(Icons.Default.Add, null, Modifier.size(18.dp)) Text(" Создать") } + OutlinedButton(onClick = { showImportMethods = true }, enabled = canUse && state != null) { + Text("Импорт") + } OutlinedButton(onClick = { showServerTools = true }, enabled = canUse && state != null) { Text("Сервер") } } - if (status.isNotBlank() && state == null) { + if (status.isNotBlank()) { ClientStatusBanner(status = status, busy = busy) } @@ -507,6 +564,7 @@ fun ServerClientsSection( } }, onExtend = { expiryClient = selectedClient }, + onExport = { exportClient = selectedClient }, onDetails = { busy = true status = "Читаю данные клиента..." @@ -529,6 +587,7 @@ fun ServerClientsSection( run = { ServerAdminClient.unbind(target, selectedClient.password) } ) }, + onChangePassword = { passwordClient = selectedClient }, onToggle = { pendingAction = if (selectedClient.status == "deactivated") { PendingClientAction( @@ -559,9 +618,6 @@ fun ServerClientsSection( } ) } - if (status.isNotBlank()) { - ClientStatusBanner(status = status, busy = busy) - } } } } @@ -593,6 +649,8 @@ fun ServerClientsSection( if (showCreateWizard) { CreateClientWizardDialog( defaultPorts = state?.defaultPorts ?: defaultPorts.ifBlank { "56000,56001,9000" }, + existingPasswords = state?.clients?.map { it.password }.orEmpty().toSet(), + mainPassword = mainPassword, busy = busy, onDismiss = { if (!busy) showCreateWizard = false }, onCreate = { request -> @@ -616,6 +674,142 @@ fun ServerClientsSection( ) } + if (showImportMethods) { + ClientImportMethodsDialog( + onDismiss = { showImportMethods = false }, + onCamera = { + importCameraLauncher.launch( + ScanOptions() + .setDesiredBarcodeFormats(ScanOptions.QR_CODE) + .setPrompt("Наведите камеру на QR переноса клиента") + .setBeepEnabled(false) + .setCaptureActivity(QrCaptureActivity::class.java) + .setOrientationLocked(false) + ) + }, + onGallery = { importGalleryLauncher.launch("image/*") }, + onFile = { importFileLauncher.launch("*/*") }, + onPaste = { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val value = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(context)?.toString() + if (value.isNullOrBlank()) status = "Ошибка: в буфере обмена нет данных клиента" + else acceptClientTransfer(value) + } + ) + } + + pendingImport?.let { payload -> + val current = state + ClientImportConfirmDialog( + payload = payload, + targetHost = current?.let { it.publicHost.ifBlank { it.effectivePublicHost.ifBlank { host } } }.orEmpty(), + targetPorts = current?.defaultPorts ?: defaultPorts, + passwordConflict = current?.clients?.any { it.password == payload.password } == true, + mainPasswordConflict = payload.password == mainPassword, + limitReached = current != null && current.passwordCount >= current.maxPasswords && current.expiredCount == 0, + onDismiss = { pendingImport = null }, + onConfirm = { + pendingImport = null + busy = true + status = "Импорт: отправляю данные клиента на сервер..." + scope.launch { + try { + val result = ServerAdminClient.importClient( + target, + payload, + current?.defaultPorts ?: defaultPorts.ifBlank { "56000,56001,9000" } + ) + status = "Импорт: клиент записан, проверяю список на сервере..." + val refreshed = ServerAdminClient.list(target) + val imported = refreshed.clients.firstOrNull { it.password == payload.password } + ?: result.createdClient?.takeIf { created -> created.password == payload.password } + ?: throw IllegalStateException("сервер принял импорт, но клиент не найден в свежем списке. Нажмите «Обновить» и проверьте, не достигнут ли лимит клиентов.") + state = refreshed + clientSearch = "" + statusFilter = ClientStatusFilter.All + bindingFilter = ClientBindingFilter.All + expiryFilter = ClientExpiryFilter.All + vkHashFilter = ClientVkHashFilter.All + selectedClientIndex = refreshed.clients.indexOfFirst { it.password == payload.password } + .coerceAtLeast(0) + importedClient = imported + status = "Клиент импортирован и найден в списке без перезапуска сервера." + } catch (error: Throwable) { + status = "Ошибка: ${error.message ?: "клиент не импортирован"}" + } + busy = false + } + } + ) + } + + exportClient?.let { client -> + val transferResult = remember(client) { runCatching { ClientTransferCodec.encode(ClientTransferCodec.fromClient(client)) } } + val transfer = transferResult.getOrNull() + if (transfer == null) { + AlertDialog( + onDismissRequest = { exportClient = null }, + title = { DialogTitle("Экспорт невозможен", { exportClient = null }) }, + text = { + Text( + transferResult.exceptionOrNull()?.message ?: "Проверьте пароль и VK-хеши клиента.", + color = MaterialTheme.colorScheme.error + ) + }, + confirmButton = { Button(onClick = { exportClient = null }) { Text("Хорошо") } } + ) + } else { + ClientTransferExportDialog( + client = client, + onDismiss = { exportClient = null }, + onCopy = { copyText(context, "Перенос клиента WDTT Plus", transfer) }, + onShare = { shareText(context, transfer, "Передать клиента WDTT Plus") }, + onQr = { + scope.launch { + runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, transfer) } } + .onSuccess { qrData = "Перенос: ${client.displayName()}" to it } + .onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" } + } + }, + onFile = { + scope.launch { + runCatching { + withContext(Dispatchers.IO) { + TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt-client", transfer) + } + }.onSuccess { + shareUri(context, it, "application/vnd.wdtt.plus.client", "Передать клиента WDTT Plus") + }.onFailure { status = "Ошибка: ${it.message ?: "файл клиента не создан"}" } + } + } + ) + } + } + + passwordClient?.let { client -> + ChangeClientPasswordDialog( + client = client, + existingPasswords = state?.clients?.map { it.password }.orEmpty().toSet(), + mainPassword = mainPassword, + onDismiss = { passwordClient = null }, + onConfirm = { newPassword -> + passwordClient = null + busy = true + status = "Изменяю пароль клиента..." + scope.launch { + runCatching { ServerAdminClient.setPassword(target, client.password, newPassword) } + .onSuccess { result -> + status = result.message + changedPasswordClient = result.createdClient + runCatching { ServerAdminClient.list(target) }.onSuccess { state = it } + } + .onFailure { status = "Ошибка: ${it.message ?: "пароль не изменён"}" } + busy = false + } + } + ) + } + pendingAction?.let { action -> ConfirmClientActionDialog( action = action, @@ -654,7 +848,6 @@ fun ServerClientsSection( onShare = { link?.let { shareText(context, it) } }, onQr = { link?.let { value -> - createdClient = null scope.launch { runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } } .onSuccess { qrData = client.displayName() to it } @@ -675,6 +868,73 @@ fun ServerClientsSection( ) } + importedClient?.let { client -> + val link = client.connectionLink(host, state?.publicHost?.ifBlank { state?.effectivePublicHost.orEmpty() }.orEmpty()) + AccessResultDialog( + title = "Импорт готов", + statusText = "Клиент импортирован и найден в списке.", + password = client.password, + link = link, + noLinkText = "VK-хеш не задан. Клиент добавлен; хеш можно указать в «Подробнее».", + onDismiss = { importedClient = null }, + onCopyPassword = { copyText(context, "Пароль импортированного клиента", client.password) }, + onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } }, + onShare = { link?.let { shareText(context, it) } }, + onQr = { + link?.let { value -> + scope.launch { + runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } } + .onSuccess { qrData = client.displayName() to it } + .onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" } + } + } + }, + onFile = { + link?.let { value -> + scope.launch { + runCatching { + withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) } + }.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") } + .onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" } + } + } + } + ) + } + + changedPasswordClient?.let { client -> + val link = client.connectionLink(host, state?.publicHost?.ifBlank { state?.effectivePublicHost.orEmpty() }.orEmpty()) + AccessResultDialog( + title = "Пароль изменён", + password = client.password, + link = link, + noLinkText = "VK-хеш не задан. Новый пароль уже работает; добавьте хеш в «Подробнее», чтобы сформировать ссылку.", + onDismiss = { changedPasswordClient = null }, + onCopyPassword = { copyText(context, "Новый пароль WDTT", client.password) }, + onCopyLink = { link?.let { copyText(context, "Новая ссылка WDTT", it) } }, + onShare = { link?.let { shareText(context, it) } }, + onQr = { + link?.let { value -> + scope.launch { + runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } } + .onSuccess { qrData = client.displayName() to it } + .onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" } + } + } + }, + onFile = { + link?.let { value -> + scope.launch { + runCatching { + withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) } + }.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать новое подключение WDTT Plus") } + .onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" } + } + } + } + ) + } + detailsClient?.let { client -> ClientDetailsDialog( client = client, @@ -991,8 +1251,10 @@ private fun ServerClientActions( onFile: (String) -> Unit, onQr: (String) -> Unit, onExtend: () -> Unit, + onExport: () -> Unit, onDetails: () -> Unit, onUnbind: () -> Unit, + onChangePassword: () -> Unit, onToggle: () -> Unit, onDelete: () -> Unit ) { @@ -1031,6 +1293,7 @@ private fun ServerClientActions( ) { OutlinedButton(onClick = onExtend, enabled = !busy) { Text("Продлить") } OutlinedButton(onClick = onDetails, enabled = !busy) { Text("Подробнее") } + OutlinedButton(onClick = onExport, enabled = !busy) { Text("Экспорт") } } ClientActionCategoryBlock( @@ -1041,6 +1304,10 @@ private fun ServerClientActions( category = ClientActionCategory.Access.takeUnless { category == it } } ) { + OutlinedButton(onClick = onChangePassword, enabled = !busy) { + Icon(Icons.Default.Key, null, Modifier.size(16.dp)) + Text(" Сменить пароль") + } OutlinedButton(onClick = onUnbind, enabled = !busy && client.isBound) { Icon(Icons.Default.Smartphone, null, Modifier.size(16.dp)) Text(" Отвязать") @@ -1124,6 +1391,7 @@ private fun ClientActionCategoryBlock( @Composable private fun AccessResultDialog( title: String, + statusText: String? = null, password: String, link: String?, noLinkText: String, @@ -1139,6 +1407,14 @@ private fun AccessResultDialog( title = { DialogTitle(title, onDismiss) }, text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + statusText?.let { + Text( + it, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary + ) + } Card( shape = RoundedCornerShape(18.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f)) @@ -1741,10 +2017,231 @@ private fun DialogTitle( } } +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun ClientImportMethodsDialog( + onDismiss: () -> Unit, + onCamera: () -> Unit, + onGallery: () -> Unit, + onFile: () -> Unit, + onPaste: () -> Unit +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { DialogTitle("Импорт клиента", onDismiss) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text("Выберите данные переноса клиента. Обычная ссылка подключения сюда не импортируется.") + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedButton(onClick = onCamera) { + Icon(Icons.Default.CameraAlt, null, Modifier.size(18.dp)) + Text(" Камера") + } + OutlinedButton(onClick = onGallery) { + Icon(Icons.Default.Image, null, Modifier.size(18.dp)) + Text(" Галерея") + } + OutlinedButton(onClick = onFile) { + Icon(Icons.Default.FileOpen, null, Modifier.size(18.dp)) + Text(" Файл") + } + OutlinedButton(onClick = onPaste) { Text("Вставить") } + } + Text( + "Файл, изображение или код содержит пароль клиента. После чтения приложение покажет проверку перед записью на сервер.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } + }, + confirmButton = {} + ) +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun ClientTransferExportDialog( + client: ServerClientInfo, + onDismiss: () -> Unit, + onCopy: () -> Unit, + onShare: () -> Unit, + onQr: () -> Unit, + onFile: () -> Unit +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { DialogTitle("Экспорт клиента", onDismiss) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text("Клиент: ${client.displayName()}", fontWeight = FontWeight.Bold) + Text("Переносятся пароль, название, VK-хеши, срок и состояние доступа.") + Text( + "Не переносятся устройство, WireGuard-ключи, адрес, порты, трафик и история. На новом сервере используются его настройки, а устройство привяжется при первом подключении.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedButton(onClick = onQr) { + Icon(Icons.Default.QrCode2, null, Modifier.size(18.dp)) + Text(" QR") + } + OutlinedButton(onClick = onFile) { + Icon(Icons.AutoMirrored.Filled.InsertDriveFile, null, Modifier.size(18.dp)) + Text(" Файл") + } + OutlinedButton(onClick = onShare) { + Icon(Icons.Default.Share, null, Modifier.size(18.dp)) + Text(" Поделиться") + } + OutlinedButton(onClick = onCopy) { Text("Копировать") } + } + Text( + "Передача содержит рабочий пароль клиента. Отправляйте её только себе или доверенному администратору.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } + }, + confirmButton = {} + ) +} + +@Composable +private fun ClientImportConfirmDialog( + payload: ClientTransferPayload, + targetHost: String, + targetPorts: String, + passwordConflict: Boolean, + mainPasswordConflict: Boolean, + limitReached: Boolean, + onDismiss: () -> Unit, + onConfirm: () -> Unit +) { + val expired = payload.expiresAt > 0 && payload.expiresAt <= System.currentTimeMillis() / 1000L + val errors = buildList { + if (passwordConflict) add("На новом сервере уже есть клиент с таким паролем.") + if (mainPasswordConflict) add("Пароль клиента совпадает с главным паролем нового сервера.") + if (expired) add("Срок этого клиента уже истёк.") + if (limitReached) add("На новом сервере достигнут лимит клиентов.") + if (targetHost.isBlank()) add("Не определён адрес нового сервера.") + if (!targetPorts.isPortsSpec()) add("На новом сервере указаны некорректные порты.") + } + AlertDialog( + onDismissRequest = onDismiss, + title = { DialogTitle("Проверка импорта", onDismiss) }, + text = { + Column( + modifier = Modifier.verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + InfoLine("Клиент", payload.label.ifBlank { "Без имени" }) + InfoLine("Пароль", "${payload.password.take(3)}••••${payload.password.takeLast(3)}") + InfoLine("Срок", formatExpiry(payload.expiresAt)) + InfoLine("Состояние", if (payload.deactivated) "Отключён" else "Активен") + InfoLine("VK-хеши", if (payload.vkHash.isBlank()) "не заданы" else "заданы") + HorizontalDivider() + InfoLine("Новый сервер", targetHost.ifBlank { "не определён" }) + InfoLine("Порты нового сервера", targetPorts.ifBlank { "не заданы" }) + Text( + "Клиент будет скопирован без устройства, ключей, статистики и истории. Старый сервер не изменится. Импорт применяется наживую без перезапуска.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + errors.forEach { Text("• $it", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) } + } + }, + confirmButton = { Button(onClick = onConfirm, enabled = errors.isEmpty()) { Text("Импортировать") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Отмена") } } + ) +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun ChangeClientPasswordDialog( + client: ServerClientInfo, + existingPasswords: Set, + mainPassword: String, + onDismiss: () -> Unit, + onConfirm: (String) -> Unit +) { + var automatic by rememberSaveable(client.password) { mutableStateOf(true) } + var generated by remember(client.password) { mutableStateOf(ClientPasswordRules.generate()) } + var manual by rememberSaveable(client.password) { mutableStateOf("") } + val value = if (automatic) generated else manual.trim() + val error = when { + ClientPasswordRules.validate(value) != null -> ClientPasswordRules.validate(value) + value == client.password -> "Новый пароль совпадает с текущим." + value == mainPassword -> "Пароль клиента не должен совпадать с главным паролем." + value in existingPasswords -> "Клиент с таким паролем уже существует." + else -> null + } + AlertDialog( + onDismissRequest = onDismiss, + title = { DialogTitle("Сменить пароль", onDismiss) }, + text = { + Column( + modifier = Modifier.verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + Text("Клиент: ${client.displayName()}", fontWeight = FontWeight.Bold) + InfoLine("Текущий пароль", client.maskedPassword().removePrefix("Пароль: ")) + val deviceLabel = listOf( + client.deviceName, + client.device?.name.orEmpty(), + client.device?.model.orEmpty(), + client.deviceId + ).firstOrNull { it.isNotBlank() } + InfoLine("Устройство", deviceLabel ?: "не привязано") + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + SelectButton("Автоматически", automatic) { automatic = true } + SelectButton("Вручную", !automatic) { automatic = false } + } + if (automatic) { + OutlinedTextField(value = generated, onValueChange = {}, readOnly = true, label = { Text("Новый пароль") }, modifier = Modifier.fillMaxWidth()) + error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) } + OutlinedButton(onClick = { generated = ClientPasswordRules.generate() }) { Text("Другой пароль") } + } else { + OutlinedTextField( + value = manual, + onValueChange = { manual = it.trim().take(32) }, + label = { Text("Новый пароль, 16 символов") }, + supportingText = { error?.let { Text(it) } }, + isError = error != null, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + } + Text( + "Старые ссылки перестанут работать, активное соединение этого клиента завершится. Название, срок, VK-хеши и привязка устройства сохранятся; остальные клиенты не затрагиваются.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + Text("Изменение применяется наживую без перезапуска сервера.", style = MaterialTheme.typography.bodySmall) + } + }, + confirmButton = { Button(onClick = { onConfirm(value) }, enabled = error == null) { Text("Изменить") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Отмена") } } + ) +} + @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable private fun CreateClientWizardDialog( defaultPorts: String, + existingPasswords: Set, + mainPassword: String, busy: Boolean, onDismiss: () -> Unit, onCreate: (ServerClientCreateRequest) -> Unit @@ -1755,8 +2252,17 @@ private fun CreateClientWizardDialog( var vkHash by rememberSaveable { mutableStateOf("") } var useDefaultPorts by rememberSaveable { mutableStateOf(true) } var customPorts by rememberSaveable { mutableStateOf(defaultPorts) } + var useAutoPassword by rememberSaveable { mutableStateOf(true) } + var customPassword by rememberSaveable { mutableStateOf("") } val effectivePorts = if (useDefaultPorts) defaultPorts else customPorts val portsValid = effectivePorts.isPortsSpec() + val passwordError = if (useAutoPassword || customPassword.isEmpty()) null else when { + ClientPasswordRules.validate(customPassword) != null -> ClientPasswordRules.validate(customPassword) + customPassword == mainPassword -> "Пароль клиента не должен совпадать с главным паролем." + customPassword in existingPasswords -> "Клиент с таким паролем уже существует." + else -> null + } + val passwordValid = useAutoPassword || (customPassword.isNotEmpty() && passwordError == null) AlertDialog( onDismissRequest = onDismiss, @@ -1845,12 +2351,44 @@ private fun CreateClientWizardDialog( ) if (!portsValid) Text("Формат: 56000,56001,9000", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) } + ClientWizardStep.Password -> { + Text("Пароль клиента", fontWeight = FontWeight.Bold) + Text( + "Автоматический пароль безопаснее. Ручной режим нужен, например, для переноса существующего клиента с другого сервера.", + style = MaterialTheme.typography.bodySmall + ) + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + SelectButton("Автоматически", useAutoPassword) { useAutoPassword = true } + SelectButton("Вручную", !useAutoPassword) { useAutoPassword = false } + } + if (!useAutoPassword) { + OutlinedTextField( + value = customPassword, + onValueChange = { customPassword = it.trim().take(32) }, + label = { Text("16 символов") }, + supportingText = { + Text(passwordError ?: "Допустимы безопасные латинские буквы и цифры.") + }, + isError = customPassword.isNotEmpty() && passwordError != null, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + OutlinedButton(onClick = { customPassword = ClientPasswordRules.generate() }) { + Text("Сгенерировать") + } + } + } ClientWizardStep.Confirm -> { Text("Проверка", fontWeight = FontWeight.Bold) Text("Срок: ${if (days == 0) "бессрочно" else "$days дн."}") Text("Название: ${label.ifBlank { "без имени" }}") Text("VK-хеш: ${if (vkHash.isBlank()) "не задан" else "задан"}") Text("Порты: $effectivePorts") + Text("Пароль: ${if (useAutoPassword) "будет создан автоматически" else customPassword}") Text( "Новый доступ начнёт работать сразу, текущие подключения не прервутся.", style = MaterialTheme.typography.bodySmall, @@ -1864,7 +2402,9 @@ private fun CreateClientWizardDialog( }, confirmButton = { Button( - enabled = !busy && (step != ClientWizardStep.Ports || portsValid), + enabled = !busy && + (step != ClientWizardStep.Ports || portsValid) && + (step != ClientWizardStep.Password || passwordValid), onClick = { if (step == ClientWizardStep.Confirm) { onCreate( @@ -1872,7 +2412,8 @@ private fun CreateClientWizardDialog( days = days.coerceIn(0, 365), label = label, vkHash = vkHash, - ports = effectivePorts + ports = effectivePorts, + password = customPassword.takeUnless { useAutoPassword } ) ) } else { @@ -2256,12 +2797,12 @@ private fun String.isPortsSpec(): Boolean { return parts.size == 3 && parts.all { it != null && it in 1..65535 } } -private fun shareText(context: Context, text: String) { +private fun shareText(context: Context, text: String, title: String = "Передать подключение WDTT Plus") { val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, text) } - context.startActivity(Intent.createChooser(intent, "Передать подключение WDTT Plus")) + context.startActivity(Intent.createChooser(intent, title)) } private fun copyText(context: Context, label: String, text: String) { diff --git a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt index 9504941..26211c6 100644 --- a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt @@ -1,5 +1,7 @@ package com.wdtt.plus.ui +import android.content.ClipData +import android.content.ClipboardManager import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring @@ -19,6 +21,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.HelpOutline import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.PowerSettingsNew import androidx.compose.material.icons.filled.Stop @@ -54,6 +57,7 @@ import com.wdtt.plus.TunnelService import com.wdtt.plus.VkJoinLink import com.wdtt.plus.WDTTColors import com.wdtt.plus.WdttDeepLink +import com.wdtt.plus.vpnProfileDisplayName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay @@ -120,6 +124,7 @@ fun SettingsTabContent( val savedListenPort by settingsStore.listenPort.collectAsStateWithLifecycle(initialValue = 9000) val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0) + val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false) val wdttLink by settingsStore.wdttLink.collectAsStateWithLifecycle(initialValue = "") val savedVkHashes by settingsStore.vkHashes.collectAsStateWithLifecycle(initialValue = "") @@ -439,11 +444,18 @@ fun SettingsTabContent( if (!wdttLinkMode) { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { // ═══ Заголовок раздела ═══ - Text( - "Настройки туннеля", - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurface - ) + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + "Настройки туннеля", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface + ) + Text( + "(${vpnProfileDisplayName(activeProfile, profileNames)})", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } // ═══ Настройки туннеля ═══ AppSectionCard( @@ -1171,17 +1183,29 @@ fun ImportantInfoDialog(onDismiss: () -> Unit) { Spacer(Modifier.height(16.dp)) - InfoSection("Капча VK", - "Авто-режим старается пройти капчу сам, но иногда VK всё равно показывает проверку. Если появилось окно капчи, чаще всего достаточно поставить галочку в квадрате." + InfoSection( + "Профили VPN", + "В боковых настройках доступны VPN 1, VPN 2 и VPN 3. Короткое нажатие переключает профиль, долгое нажатие позволяет переименовать его." ) - InfoSection("Сетевое окружение", - "Перед подключением выключите другие VPN, системные прокси и «Приватный DNS», чтобы они не перехватывали трафик WDTT Plus." + InfoSection( + "VK-хеши", + "VK-хеш нужен для работы туннеля. В настройке VK-хешей можно проверить каждый слот, скопировать отдельный хеш или все заполненные хеши сразу." ) - InfoSection("VK-хеши и мощность", - "VK-хеш нужен для работы туннеля. Несколько хешей позволяют распределять нагрузку, а мощность лучше держать в умеренном диапазоне 12-36 потоков." + InfoSection( + "Клиенты и сервер", + "В режиме «Я — админ» блок «Деплой» → «Клиенты и сервер» управляет клиентами без Telegram-бота: создание, продление, отключение, смена пароля, экспорт и импорт отдельного клиента." ) - InfoSection("Связь потоков и капч", - "Чем выше мощность, тем больше нагрузка, расход батареи и шанс чаще видеть капчу. Повышайте её только если сеть нестабильная и сервер справляется." + InfoSection( + "Передача подключения", + "Обычное подключение передаётся через «Настройки» → «Передать или получить». Перенос отдельного клиента выполняется именно в блоке «Клиенты и сервер»." + ) + InfoSection( + "После новых серверных функций", + "Если приложение пишет, что сервер не поддерживает действие, выполните во вкладке «Деплой» установку сервера с сохранением данных." + ) + InfoSection( + "Капча и мощность", + "Авто-режим старается пройти капчу сам. Несколько VK-хешей распределяют нагрузку, а мощность лучше держать умеренной: чем она выше, тем больше расход батареи и шанс чаще видеть капчу." ) Spacer(Modifier.height(20.dp)) @@ -1246,6 +1270,13 @@ private fun encodeVkHashSlots(vararg hashes: String): String { return slots.joinToString(",") } +private fun copyVkHashesToClipboard(context: android.content.Context, label: String, value: String) { + if (value.isBlank()) return + val clipboard = context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager + clipboard.setPrimaryClip(ClipData.newPlainText(label, value)) + Toast.makeText(context, "Скопировано", Toast.LENGTH_SHORT).show() +} + // ═══ Модальное окно хешей ═══ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -1276,6 +1307,11 @@ fun HashesDialog( val currentHashes = remember(h1, h2, h3, h4) { listOf(h1, h2, h3, h4).map { stripVkUrlStatic(it) } } + val copiedHashesText = remember(currentHashes) { + currentHashes + .filter { it.isNotBlank() } + .joinToString(",") + } val checkableHashes = remember(currentHashes) { currentHashes.mapIndexedNotNull { index, hash -> if (hash.length >= 16) index + 1 to hash else null @@ -1395,6 +1431,7 @@ fun HashesDialog( Triple("VK Хеш 4", h4) { v: String -> h4 = v } ).forEachIndexed { idx, (label, value, onChange) -> val slot = idx + 1 + val cleanedValue = stripVkUrlStatic(value) HashInputField( slot = slot, label = label, @@ -1404,10 +1441,24 @@ fun HashesDialog( onChange(stripVkUrlStatic(cleaned)) }, result = checkResults[slot], - onInfoClick = { detailSlot = slot } + onInfoClick = { detailSlot = slot }, + canCopy = cleanedValue.isNotBlank(), + onCopyClick = { copyVkHashesToClipboard(context, "VK Хеш $slot", cleanedValue) } ) } + OutlinedButton( + onClick = { copyVkHashesToClipboard(context, "VK Хеши WDTT Plus", copiedHashesText) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + enabled = copiedHashesText.isNotBlank(), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + ) { + Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + FlexibleButtonText("Скопировать все хеши", fontWeight = FontWeight.SemiBold) + } + OutlinedButton( onClick = { checkJob?.cancel(CancellationException("Restarting hash check")) @@ -1506,7 +1557,9 @@ private fun HashInputField( value: String, onValueChange: (String) -> Unit, result: HashCheckResult?, - onInfoClick: () -> Unit + onInfoClick: () -> Unit, + canCopy: Boolean, + onCopyClick: () -> Unit ) { val isShort = value.isNotBlank() && value.length < 16 val visibleResult = result?.takeIf { it.status != "pending" } @@ -1536,30 +1589,47 @@ private fun HashInputField( } else -> null }, - trailingIcon = if (visibleResult != null) { - { + trailingIcon = { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(2.dp) + ) { IconButton( - onClick = onInfoClick, + onClick = onCopyClick, + enabled = canCopy, modifier = Modifier.size(34.dp) ) { - Surface( - shape = CircleShape, - color = borderColor.copy(alpha = 0.14f), - border = BorderStroke(1.dp, borderColor.copy(alpha = 0.7f)), - modifier = Modifier.size(22.dp) + Icon( + Icons.Default.ContentCopy, + contentDescription = "Скопировать VK Хеш $slot", + modifier = Modifier.size(18.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = if (canCopy) 1f else 0.38f) + ) + } + if (visibleResult != null) { + IconButton( + onClick = onInfoClick, + modifier = Modifier.size(34.dp) ) { - Box(contentAlignment = Alignment.Center) { - Text( - "?", - color = borderColor, - style = MaterialTheme.typography.labelSmall, - fontWeight = FontWeight.Bold - ) + Surface( + shape = CircleShape, + color = borderColor.copy(alpha = 0.14f), + border = BorderStroke(1.dp, borderColor.copy(alpha = 0.7f)), + modifier = Modifier.size(22.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Text( + "?", + color = borderColor, + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold + ) + } } } } } - } else null, + }, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = OutlinedTextFieldDefaults.colors( diff --git a/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt b/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt index 62c2c7a..8408f32 100644 --- a/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt +++ b/app/src/main/java/com/wdtt/plus/ui/TransferCenter.kt @@ -58,12 +58,14 @@ import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.window.DialogProperties import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.collectAsStateWithLifecycle 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 com.wdtt.plus.vpnProfileDisplayName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -88,6 +90,8 @@ fun TransferCenterDialog( var error by remember { mutableStateOf(null) } var qrData by remember { mutableStateOf?>(null) } var adminAction by remember { mutableStateOf(null) } + val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) + val activeProfileLabel = vpnProfileDisplayName(activeProfile, profileNames) fun runCatchingUi(block: suspend () -> Unit) { busy = true @@ -154,7 +158,7 @@ fun TransferCenterDialog( } HorizontalDivider() - Text("Передача VPN ${activeProfile + 1}", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text("Передача $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) Text( "Ссылка содержит пароль подключения и VK-хеши. Передавайте её только тому, кому доверяете.", style = MaterialTheme.typography.bodySmall, @@ -169,7 +173,7 @@ fun TransferCenterDialog( runCatchingUi { val link = settingsStore.connectionLinkForProfile(activeProfile) val bitmap = withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) } - qrData = "VPN ${activeProfile + 1}" to bitmap + qrData = activeProfileLabel to bitmap } } TransferButton("Ссылка", Icons.Default.Share, busy) { @@ -181,7 +185,7 @@ fun TransferCenterDialog( runCatchingUi { val link = settingsStore.connectionLinkForProfile(activeProfile) val uri = withContext(Dispatchers.IO) { - TransferFiles.writeTransferText(context, "WDTT-Plus-VPN-${activeProfile + 1}.wdtt", link) + TransferFiles.writeTransferText(context, "WDTT-Plus-${activeProfileLabel.safeTransferFileName()}.wdtt", link) } shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") } @@ -495,6 +499,14 @@ private fun String.safeQrFileName(): String = .trim('_', '.', '-') .ifBlank { "qr" } +private fun String.safeTransferFileName(): String = + replace(Regex("[^\\p{L}\\p{N}._-]+"), "-") + .replace(Regex("-+"), "-") + .trim('_', '.', '-') + .take(48) + .trim('_', '.', '-') + .ifBlank { "VPN" } + private fun shareUri(context: Context, uri: Uri, mimeType: String, title: String) { val intent = Intent(Intent.ACTION_SEND).apply { type = mimeType diff --git a/app/src/test/java/com/wdtt/plus/ClientTransferCodecTest.kt b/app/src/test/java/com/wdtt/plus/ClientTransferCodecTest.kt new file mode 100644 index 0000000..db4898d --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/ClientTransferCodecTest.kt @@ -0,0 +1,57 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ClientTransferCodecTest { + @Test + fun clientTransfer_roundTripsOnlyPortableFields() { + val source = ClientTransferPayload( + password = "ABCDEFGHJKLMNPQR", + label = "Телефон папы", + vkHash = "abcdefghijklmnop,qrstuvwxyzABCDEF", + expiresAt = 1_900_000_000, + deactivated = true, + createdAt = 12345 + ) + + val encoded = ClientTransferCodec.encode(source) + + assertEquals(source, ClientTransferCodec.decode(encoded)) + assertTrue(ClientTransferCodec.isClientTransfer(encoded)) + assertFalse(encoded.contains("device_id")) + assertFalse(encoded.contains("down_bytes")) + assertFalse(encoded.contains("ports")) + assertFalse(encoded.contains("host")) + } + + @Test(expected = IllegalArgumentException::class) + fun clientTransfer_rejectsUnsafePassword() { + ClientTransferCodec.decode( + """{"format":"wdtt-plus-client","version":1,"password":"bad password","expires_at":0}""" + ) + } + + @Test + fun clientPasswordRules_matchServerAlphabet() { + assertEquals(null, ClientPasswordRules.validate("ABCDEFGHJKLMNPQR")) + assertTrue(ClientPasswordRules.validate("ABCDEFGHJKLMNPQ0") != null) + assertTrue(ClientPasswordRules.validate("short") != null) + } + + @Test(expected = IllegalArgumentException::class) + fun clientTransfer_rejectsUnknownVersion() { + ClientTransferCodec.decode( + """{"format":"wdtt-plus-client","version":99,"password":"ABCDEFGHJKLMNPQR","expires_at":0}""" + ) + } + + @Test(expected = IllegalArgumentException::class) + fun clientTransfer_rejectsBrokenHash() { + ClientTransferCodec.decode( + """{"format":"wdtt-plus-client","version":1,"password":"ABCDEFGHJKLMNPQR","vk_hash":"bad/path","expires_at":0}""" + ) + } +} diff --git a/bot.go b/bot.go index 3fc3baa..ef696e2 100644 --- a/bot.go +++ b/bot.go @@ -140,6 +140,127 @@ func normalizePasswordLabel(input string) string { return label } +func createBotClient( + wgDev *device.Device, + requestedPassword string, + days int, + expiresAt int64, + label string, + vkHash string, + ports string, + deactivated bool, +) (string, *PasswordEntry, error) { + dbMutex.Lock() + defer dbMutex.Unlock() + if cleanupExpiredPasswordsLocked(wgDev) > 0 { + saveDB() + } + if len(db.Passwords) >= maxGeneratedPasswords { + return "", nil, fmt.Errorf("лимит клиентов: максимум %d", maxGeneratedPasswords) + } + password := "" + if strings.TrimSpace(requestedPassword) != "" { + value, err := normalizeClientPassword(requestedPassword) + if err != nil { + return "", nil, err + } + if value == db.MainPassword { + return "", nil, errors.New("пароль клиента не должен совпадать с главным паролем") + } + if _, exists := db.Passwords[value]; exists { + return "", nil, errors.New("клиент с таким паролем уже существует") + } + password = value + } else { + for i := 0; i < 64; i++ { + candidate := generatePassword() + if candidate == db.MainPassword { + continue + } + if _, exists := db.Passwords[candidate]; !exists { + password = candidate + break + } + } + } + if password == "" { + return "", nil, errors.New("не удалось создать уникальный пароль") + } + if expiresAt < 0 { + if days < 0 || days > 365 { + return "", nil, errors.New("срок должен быть 0..365 дней") + } + if days > 0 { + expiresAt = time.Now().Add(time.Duration(days) * 24 * time.Hour).Unix() + } else { + expiresAt = 0 + } + } else if expiresAt > 0 && expiresAt <= time.Now().Unix() { + return "", nil, errors.New("срок переносимого клиента уже истёк") + } + normalizedPorts, err := parsePortsSpec(ports) + if err != nil { + return "", nil, err + } + normalizedHash := "" + if strings.TrimSpace(vkHash) != "" { + normalizedHash, err = normalizeVKHashesInput(vkHash) + if err != nil { + return "", nil, err + } + } + if !deactivated { + if err := serverWrapKeys.AddPassword(password); err != nil { + return "", nil, fmt.Errorf("не удалось добавить WRAP-ключ: %w", err) + } + } + entry := &PasswordEntry{ + ExpiresAt: expiresAt, + Label: normalizePasswordLabel(label), + VkHash: normalizedHash, + Ports: normalizedPorts, + IsDeactivated: deactivated, + } + db.Passwords[password] = entry + saveDB() + return password, entry, nil +} + +func changeBotClientPassword(wgDev *device.Device, oldPassword, requested string) (string, error) { + newPassword, err := normalizeClientPassword(requested) + if err != nil { + return "", err + } + dbMutex.Lock() + defer dbMutex.Unlock() + entry, exists := db.Passwords[oldPassword] + if !exists || entry == nil { + return "", errors.New("клиент не найден") + } + if newPassword == oldPassword { + return "", errors.New("новый пароль совпадает с текущим") + } + if newPassword == db.MainPassword { + return "", errors.New("пароль клиента не должен совпадать с главным паролем") + } + if _, exists := db.Passwords[newPassword]; exists { + return "", errors.New("клиент с таким паролем уже существует") + } + if !entry.IsDeactivated && !isPasswordExpired(entry) { + if err := serverWrapKeys.AddPassword(newPassword); err != nil { + return "", fmt.Errorf("не удалось добавить новый WRAP-ключ: %w", err) + } + } + delete(db.Passwords, oldPassword) + db.Passwords[newPassword] = entry + serverWrapKeys.RemovePassword(oldPassword) + if entry.DeviceID != "" { + removePeerFromWG(wgDev, db.Devices[entry.DeviceID]) + } + saveDB() + return newPassword, nil +} + func mdCode(value string) string { return strings.ReplaceAll(value, "`", "'") } @@ -1736,6 +1857,78 @@ func showPortsMenu(token string, adminID int64, messageID int, mainPassword bool )) } +func showNewClientPasswordMode(token string, adminID int64, messageID int) int { + return sendOrEditTelegram(token, adminID, messageID, + "🔐 *Пароль клиента*\n\nАвтоматический пароль безопаснее. Ручной режим нужен, например, чтобы перенести существующего клиента с другого сервера.", + inlineKeyboard( + []map[string]interface{}{inlineButton("🎲 Создать автоматически", "new_password_auto")}, + []map[string]interface{}{inlineButton("⌨️ Задать вручную", "new_password_manual")}, + []map[string]interface{}{inlineButton("◀️ Отмена", "mainmenu")}, + ), + ) +} + +func sendBotClientCreated(token string, adminID int64, messageID int, password string, entry *PasswordEntry, imported bool) int { + title := "✅ *Клиент создан*" + if imported { + title = "✅ *Клиент импортирован без перезапуска сервера*" + } + ttlText := "⏰ Бессрочный доступ" + if entry.ExpiresAt > 0 { + ttlText = fmt.Sprintf("⏰ Действует до %s", time.Unix(entry.ExpiresAt, 0).Format("02.01.2006")) + } + statusText := "📱 Ожидает первого подключения" + if entry.IsDeactivated { + statusText = "⏸ Доступ импортирован отключённым" + } + labelText := "" + if entry.Label != "" { + labelText = fmt.Sprintf("🏷 %s\n", mdCode(entry.Label)) + } + linkText := "" + if entry.VkHash != "" { + pts := strings.Split(entry.Ports, ",") + if len(pts) == 3 { + link := fmt.Sprintf("wdtt://%s:%s:%s:%s:%s:%s", getPublicIP(), pts[0], pts[1], pts[2], password, entry.VkHash) + linkText = fmt.Sprintf("\n\n🔗 *Быстрая ссылка:* `%s`", mdCode(link)) + } + } + return sendOrEditTelegram(token, adminID, messageID, + fmt.Sprintf("%s\n\n🔑 Пароль: `%s`\n%s%s\n%s%s", title, mdCode(password), labelText, ttlText, statusText, linkText), + inlineKeyboard( + []map[string]interface{}{inlineButton("🔍 Открыть клиента", "viewpass_"+password)}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")}, + ), + ) +} + +func showBotClientImportPreview(token string, adminID int64, messageID int, payload clientTransferPayload) int { + label := payload.Label + if label == "" { + label = "Без имени" + } + status := "активен" + if payload.Deactivated { + status = "отключён" + } + expires := "бессрочно" + if payload.ExpiresAt > 0 { + expires = time.Unix(payload.ExpiresAt, 0).Format("02.01.2006 15:04") + } + return sendOrEditTelegram(token, adminID, messageID, + fmt.Sprintf( + "📥 *Проверка импорта клиента*\n\nНазвание: `%s`\nПароль: `%s`\nСрок: `%s`\nСостояние: `%s`\nVK-хеши: `%s`\nПорты нового сервера: `%s`\n\nУстройство, WireGuard-ключи, трафик, история, адрес и старые порты не переносятся. Клиент будет добавлен наживую без перезапуска; старый сервер не изменится.", + mdCode(label), mdCode(maskPassword(payload.Password)), mdCode(expires), mdCode(status), + map[bool]string{true: "заданы", false: "не заданы"}[payload.VkHash != ""], mdCode(defaultPortsSpec()), + ), + inlineKeyboard( + []map[string]interface{}{inlineButton("📥 Импортировать", "confirm_import_client")}, + []map[string]interface{}{inlineButton("Отмена", "backlist")}, + ), + ) +} + func showLabelMenu(token string, adminID int64, messageID int) int { return sendOrEditTelegram(token, adminID, messageID, "🏷 Название ключа\n\nМожно оставить без имени или ввести короткое название, например `Дом`, `Друг`, `Ноутбук`.", @@ -1779,6 +1972,7 @@ func showPasswordEditMenu(token string, adminID int64, messageID int, pass strin mdCode(pass), mdCode(label), mdCode(ttl), mdCode(ports), mdCode(hash), ) return sendOrEditTelegram(token, adminID, messageID, text, inlineKeyboard( + []map[string]interface{}{inlineButton("🔐 Пароль", "edit_password_"+pass)}, []map[string]interface{}{inlineButton("🏷 Название", "edit_label_"+pass)}, []map[string]interface{}{inlineButton("⏰ Срок действия", "edit_exp_"+pass)}, []map[string]interface{}{inlineButton("🔑 VK-хеш/ссылка", "edit_hash_"+pass)}, @@ -1851,15 +2045,20 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { var waitingForPorts bool var waitingForHash bool var waitingForLabel bool + var waitingForNewClientPassword bool + var waitingForClientImport bool var waitingForSetting string var editMode string var editPassword string var targetPassword string var tempDays int - var tempPermanent bool var tempLabel string var tempPorts string // "dtls,wg,tun" + var tempHash string + var pendingClientImport *clientTransferPayload + var pendingPasswordChangeOld string + var pendingPasswordChangeNew string var promptMessageID int for { @@ -2007,6 +2206,10 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { "text": "✏️ Изменить", "callback_data": "editpass_" + pass, }) + kb = append(kb, map[string]interface{}{ + "text": "📤 Экспорт клиента", + "callback_data": "exportclient_" + pass, + }) kb = append(kb, map[string]interface{}{ "text": "◀️ Назад к списку", "callback_data": "backlist", @@ -2022,12 +2225,17 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { waitingForPorts = false waitingForHash = false waitingForLabel = false + waitingForNewClientPassword = false + waitingForClientImport = false waitingForSetting = "" targetPassword = "" tempDays = 0 - tempPermanent = false tempLabel = "" tempPorts = "" + tempHash = "" + pendingClientImport = nil + pendingPasswordChangeOld = "" + pendingPasswordChangeNew = "" editMode = "" editPassword = "" promptMessageID = sendMainMenu(token, adminID, menuMessageID) @@ -2036,6 +2244,8 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { waitingForPorts = false waitingForHash = false waitingForLabel = false + waitingForNewClientPassword = false + waitingForClientImport = false waitingForSetting = "" editMode = "" editPassword = "" @@ -2045,24 +2255,28 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { waitingForPorts = false waitingForHash = false waitingForLabel = false + waitingForNewClientPassword = false + waitingForClientImport = false waitingForSetting = "" editMode = "" editPassword = "" targetPassword = "" tempDays = 0 - tempPermanent = false tempLabel = "" tempPorts = "" + tempHash = "" + pendingClientImport = nil promptMessageID = startNewPasswordFlow(token, adminID, wgDev, &waitingForDays, menuMessageID) } else if strings.HasPrefix(data, "new_days_") { value := strings.TrimPrefix(data, "new_days_") waitingForPorts = false waitingForHash = false waitingForLabel = false + waitingForNewClientPassword = false + waitingForClientImport = false waitingForSetting = "" if value == "custom" { waitingForDays = true - tempPermanent = false promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "📅 Введите срок действия в днях.\n\n`0` — бессрочно, `1..365` — количество дней.", inlineKeyboard( []map[string]interface{}{inlineButton("◀️ Назад", "mainmenu")}, )) @@ -2076,9 +2290,139 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { continue } tempDays = days - tempPermanent = days == 0 waitingForDays = false promptMessageID = showLabelMenu(token, adminID, menuMessageID) + } else if data == "new_password_auto" { + waitingForNewClientPassword = false + password, entry, err := createBotClient(wgDev, "", tempDays, -1, tempLabel, tempHash, tempPorts, false) + if err != nil { + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "❌ "+mdCode(err.Error()), inlineKeyboard( + []map[string]interface{}{inlineButton("Повторить", "menu_new")}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + )) + continue + } + promptMessageID = sendBotClientCreated(token, adminID, menuMessageID, password, entry, false) + } else if data == "new_password_manual" { + waitingForNewClientPassword = true + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, + "⌨️ Введите пароль клиента из 16 символов. Допустимы безопасные латинские буквы и цифры без неоднозначных `0`, `1`, `I`, `i`, `O`, `o` и `l`.\n\nСервер проверит формат, уникальность и совпадение с главным паролем.", + inlineKeyboard([]map[string]interface{}{inlineButton("◀️ Отмена", "mainmenu")}), + ) + } else if data == "import_client" { + waitingForClientImport = true + pendingClientImport = nil + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, + "📥 *Импорт клиента*\n\nОтправьте текстовый код переноса, созданный в приложении или другом WDTT Plus-боте. Перед записью я проверю пароль, срок, лимит и покажу данные нового сервера.", + inlineKeyboard([]map[string]interface{}{inlineButton("Отмена", "backlist")}), + ) + } else if data == "confirm_import_client" { + if pendingClientImport == nil { + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "❌ Данные импорта потеряны. Отправьте код ещё раз.", inlineKeyboard( + []map[string]interface{}{inlineButton("📥 Импорт", "import_client")}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + )) + continue + } + payload := *pendingClientImport + password, entry, err := createBotClient(wgDev, payload.Password, 0, payload.ExpiresAt, payload.Label, payload.VkHash, defaultPortsSpec(), payload.Deactivated) + pendingClientImport = nil + if err != nil { + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "❌ Импорт отменён: "+mdCode(err.Error()), inlineKeyboard( + []map[string]interface{}{inlineButton("📥 Другой клиент", "import_client")}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + )) + continue + } + promptMessageID = sendBotClientCreated(token, adminID, menuMessageID, password, entry, true) + } else if strings.HasPrefix(data, "exportclient_") { + pass := strings.TrimPrefix(data, "exportclient_") + dbMutex.Lock() + entry := db.Passwords[pass] + transfer, err := encodeClientTransfer(pass, entry) + dbMutex.Unlock() + if err != nil { + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "❌ Экспорт не выполнен: "+mdCode(err.Error()), inlineKeyboard( + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + )) + continue + } + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, + fmt.Sprintf("📤 *Код переноса клиента*\n\n`%s`\n\nСодержит рабочий пароль, название, VK-хеши, срок и состояние. Устройство, ключи, адрес, порты, трафик и история не переносятся. Отправляйте код только себе или доверенному администратору.", mdCode(transfer)), + inlineKeyboard( + []map[string]interface{}{inlineButton("◀️ К клиенту", "viewpass_"+pass)}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + ), + ) + } else if strings.HasPrefix(data, "edit_password_") { + pass := strings.TrimPrefix(data, "edit_password_") + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, + fmt.Sprintf("🔐 *Смена пароля `%s`*\n\nСтарые ссылки перестанут работать, а текущее соединение клиента завершится. Название, срок, VK-хеши и привязка сохранятся. Изменение применяется без перезапуска сервера.", mdCode(pass)), + inlineKeyboard( + []map[string]interface{}{inlineButton("🎲 Новый автоматически", "change_pass_auto_"+pass)}, + []map[string]interface{}{inlineButton("⌨️ Ввести вручную", "change_pass_manual_"+pass)}, + []map[string]interface{}{inlineButton("◀️ Назад", "editpass_"+pass)}, + ), + ) + } else if strings.HasPrefix(data, "change_pass_auto_") { + pendingPasswordChangeOld = strings.TrimPrefix(data, "change_pass_auto_") + pendingPasswordChangeNew = "" + dbMutex.Lock() + for i := 0; i < 64; i++ { + candidate := generatePassword() + if candidate == db.MainPassword || candidate == pendingPasswordChangeOld { + continue + } + if _, exists := db.Passwords[candidate]; !exists { + pendingPasswordChangeNew = candidate + break + } + } + dbMutex.Unlock() + if pendingPasswordChangeNew == "" { + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "❌ Не удалось создать уникальный пароль.", inlineKeyboard( + []map[string]interface{}{inlineButton("Повторить", "edit_password_"+pendingPasswordChangeOld)}, + []map[string]interface{}{inlineButton("Отмена", "editpass_"+pendingPasswordChangeOld)}, + )) + continue + } + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, + fmt.Sprintf("⚠️ Заменить пароль клиента `%s` на `%s`?\n\nТекущее соединение этого клиента завершится, старые ссылки перестанут работать. Остальные клиенты не затрагиваются.", mdCode(pendingPasswordChangeOld), mdCode(pendingPasswordChangeNew)), + inlineKeyboard( + []map[string]interface{}{inlineButton("Изменить", "confirm_change_password")}, + []map[string]interface{}{inlineButton("Отмена", "editpass_"+pendingPasswordChangeOld)}, + ), + ) + } else if strings.HasPrefix(data, "change_pass_manual_") { + editMode = "password" + editPassword = strings.TrimPrefix(data, "change_pass_manual_") + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, + "⌨️ Введите новый пароль из 16 разрешённых символов. После проверки бот отдельно попросит подтверждение.", + inlineKeyboard([]map[string]interface{}{inlineButton("Отмена", "editpass_"+editPassword)}), + ) + } else if data == "confirm_change_password" { + if pendingPasswordChangeOld == "" || pendingPasswordChangeNew == "" { + promptMessageID = sendPasswordList(token, adminID, wgDev, menuMessageID) + continue + } + oldPassword := pendingPasswordChangeOld + newPassword, err := changeBotClientPassword(wgDev, oldPassword, pendingPasswordChangeNew) + pendingPasswordChangeOld = "" + pendingPasswordChangeNew = "" + if err != nil { + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "❌ Пароль не изменён: "+mdCode(err.Error()), inlineKeyboard( + []map[string]interface{}{inlineButton("◀️ К клиенту", "viewpass_"+oldPassword)}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + )) + continue + } + promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, + fmt.Sprintf("✅ Пароль изменён без перезапуска сервера.\n\nНовый пароль: `%s`\nСтарые ссылки больше не работают.", mdCode(newPassword)), + inlineKeyboard( + []map[string]interface{}{inlineButton("🔍 Открыть клиента", "viewpass_"+newPassword)}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + ), + ) } else if strings.HasPrefix(data, "editpass_") { editMode = "" editPassword = "" @@ -2629,12 +2973,18 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { waitingForPorts = false waitingForHash = false waitingForLabel = false + waitingForNewClientPassword = false + waitingForClientImport = false waitingForSetting = "" + pendingClientImport = nil + pendingPasswordChangeOld = "" + pendingPasswordChangeNew = "" promptMessageID = sendPasswordList(token, adminID, wgDev, menuMessageID) } else if data == "ports_def" { waitingForDays = false waitingForPorts = false waitingForLabel = false + waitingForNewClientPassword = false waitingForSetting = "" tempPorts = defaultPortsSpec() waitingForHash = true @@ -2646,6 +2996,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { waitingForPorts = true waitingForHash = false waitingForLabel = false + waitingForNewClientPassword = false waitingForSetting = "" promptMessageID = sendOrEditTelegram(token, adminID, menuMessageID, "⚙️ Укажите через запятую 3 порта (DTLS,WG,TUN):\n\nНапример: `56000,56001,9000`", inlineKeyboard( []map[string]interface{}{inlineButton("Стандартные порты", "ports_def")}, @@ -2669,14 +3020,19 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { waitingForPorts = false waitingForHash = false waitingForLabel = false + waitingForNewClientPassword = false + waitingForClientImport = false waitingForSetting = "" editMode = "" editPassword = "" targetPassword = "" tempDays = 0 - tempPermanent = false tempLabel = "" tempPorts = "" + tempHash = "" + pendingClientImport = nil + pendingPasswordChangeOld = "" + pendingPasswordChangeNew = "" if commandName == "/start" || commandName == "/help" { promptMessageID = sendMainMenu(token, adminID, promptMessageID) @@ -2690,6 +3046,63 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { continue } + if waitingForClientImport { + deleteTelegramMessage(token, adminID, msg.MessageID) + payload, err := decodeClientTransfer(cmd) + if err != nil { + promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, "❌ "+mdCode(err.Error())+"\n\nОтправьте корректный код переноса клиента.", inlineKeyboard( + []map[string]interface{}{inlineButton("Отмена", "backlist")}, + )) + continue + } + dbMutex.Lock() + if cleanupExpiredPasswordsLocked(wgDev) > 0 { + saveDB() + } + _, duplicate := db.Passwords[payload.Password] + mainConflict := payload.Password == db.MainPassword + limitReached := len(db.Passwords) >= maxGeneratedPasswords + dbMutex.Unlock() + if duplicate || mainConflict || limitReached { + reason := "на новом сервере уже есть клиент с таким паролем" + if mainConflict { + reason = "пароль клиента совпадает с главным паролем нового сервера" + } else if limitReached { + reason = "на новом сервере достигнут лимит клиентов" + } + promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, "❌ Импорт невозможен: "+reason+".", inlineKeyboard( + []map[string]interface{}{inlineButton("📥 Другой клиент", "import_client")}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + )) + continue + } + waitingForClientImport = false + pendingClientImport = &payload + promptMessageID = showBotClientImportPreview(token, adminID, promptMessageID, payload) + continue + } + + if waitingForNewClientPassword { + deleteTelegramMessage(token, adminID, msg.MessageID) + if _, err := normalizeClientPassword(cmd); err != nil { + promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, "❌ "+mdCode(err.Error())+"\n\nВведите пароль ещё раз.", inlineKeyboard( + []map[string]interface{}{inlineButton("◀️ Отмена", "mainmenu")}, + )) + continue + } + password, entry, err := createBotClient(wgDev, cmd, tempDays, -1, tempLabel, tempHash, tempPorts, false) + if err != nil { + promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, "❌ Клиент не создан: "+mdCode(err.Error()), inlineKeyboard( + []map[string]interface{}{inlineButton("Повторить", "menu_new")}, + []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, + )) + continue + } + waitingForNewClientPassword = false + promptMessageID = sendBotClientCreated(token, adminID, promptMessageID, password, entry, false) + continue + } + if waitingForSetting != "" { deleteTelegramMessage(token, adminID, msg.MessageID) mode := waitingForSetting @@ -2833,6 +3246,47 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { mode := editMode editMode = "" editPassword = "" + if mode == "password" { + newPassword, err := normalizeClientPassword(cmd) + if err != nil { + editMode = "password" + editPassword = pass + promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, "❌ "+mdCode(err.Error())+"\n\nВведите новый пароль ещё раз.", inlineKeyboard( + []map[string]interface{}{inlineButton("Отмена", "editpass_"+pass)}, + )) + continue + } + dbMutex.Lock() + _, oldExists := db.Passwords[pass] + _, duplicate := db.Passwords[newPassword] + mainConflict := newPassword == db.MainPassword + dbMutex.Unlock() + if !oldExists || duplicate || mainConflict || newPassword == pass { + reason := "новый пароль совпадает с текущим" + if !oldExists { + reason = "клиент не найден" + } else if duplicate { + reason = "клиент с таким паролем уже существует" + } else if mainConflict { + reason = "пароль совпадает с главным паролем" + } + promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, "❌ "+reason+".", inlineKeyboard( + []map[string]interface{}{inlineButton("Попробовать снова", "change_pass_manual_"+pass)}, + []map[string]interface{}{inlineButton("Отмена", "editpass_"+pass)}, + )) + continue + } + pendingPasswordChangeOld = pass + pendingPasswordChangeNew = newPassword + promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, + fmt.Sprintf("⚠️ Заменить пароль клиента `%s` на `%s`?\n\nТекущее соединение завершится, старые ссылки перестанут работать. Остальные клиенты не затрагиваются.", mdCode(pass), mdCode(newPassword)), + inlineKeyboard( + []map[string]interface{}{inlineButton("Изменить", "confirm_change_password")}, + []map[string]interface{}{inlineButton("Отмена", "editpass_"+pass)}, + ), + ) + continue + } dbMutex.Lock() entry, exists := db.Passwords[pass] @@ -2926,7 +3380,6 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { continue } tempDays = days - tempPermanent = days == 0 promptMessageID = showLabelMenu(token, adminID, promptMessageID) continue @@ -2992,73 +3445,8 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { continue } - dbMutex.Lock() - if cleanupExpiredPasswordsLocked(wgDev) > 0 { - saveDB() - } - if len(db.Passwords) >= maxGeneratedPasswords { - dbMutex.Unlock() - promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, fmt.Sprintf("❌ Лимит паролей: максимум %d активных. Удалите ненужный пароль через список доступов.", maxGeneratedPasswords), inlineKeyboard( - []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, - []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")}, - )) - continue - } - newPass := "" - for i := 0; i < 10; i++ { - candidate := generatePassword() - if _, exists := db.Passwords[candidate]; !exists { - newPass = candidate - break - } - } - if newPass == "" { - dbMutex.Unlock() - promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, "❌ Не удалось создать уникальный пароль.", inlineKeyboard( - []map[string]interface{}{inlineButton("Повторить", "menu_new")}, - []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")}, - )) - continue - } - if err := serverWrapKeys.AddPassword(newPass); err != nil { - dbMutex.Unlock() - promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, "❌ Не удалось создать WRAP-ключ для пароля.", inlineKeyboard( - []map[string]interface{}{inlineButton("Повторить", "menu_new")}, - []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")}, - )) - continue - } - expiresAt := int64(0) - if !tempPermanent { - expiresAt = time.Now().Add(time.Duration(tempDays) * 24 * time.Hour).Unix() - } - db.Passwords[newPass] = &PasswordEntry{ - ExpiresAt: expiresAt, - Label: tempLabel, - VkHash: hash, - Ports: tempPorts, - } - saveDB() - dbMutex.Unlock() - - ttlText := "⏰ Бессрочный доступ" - if !tempPermanent { - expDate := time.Unix(expiresAt, 0).Format("02.01.2006") - ttlText = fmt.Sprintf("⏰ Действует %d дн. (до %s)", tempDays, expDate) - } - srvIP := getPublicIP() - pts := strings.Split(tempPorts, ",") - link := fmt.Sprintf("wdtt://%s:%s:%s:%s:%s:%s", srvIP, pts[0], pts[1], pts[2], newPass, hash) - - labelText := "" - if tempLabel != "" { - labelText = fmt.Sprintf("🏷 %s\n", tempLabel) - } - promptMessageID = sendOrEditTelegram(token, adminID, promptMessageID, fmt.Sprintf("🔑 Новый пароль:\n`%s`\n\n%s%s\n📱 Ожидает первого подключения\n\n🔗 *Быстрая ссылка:* `%s`", mdCode(newPass), labelText, ttlText, mdCode(link)), inlineKeyboard( - []map[string]interface{}{inlineButton("➕ Ещё пароль", "menu_new")}, - []map[string]interface{}{inlineButton("🔐 К списку", "backlist")}, - []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")}, - )) + tempHash = hash + promptMessageID = showNewClientPasswordMode(token, adminID, promptMessageID) continue } } @@ -3121,6 +3509,7 @@ func sendPasswordList(token string, adminID int64, wgDev *device.Device, message } } keyboard = append(keyboard, []map[string]interface{}{inlineButton("➕ Новый пароль", "menu_new")}) + keyboard = append(keyboard, []map[string]interface{}{inlineButton("📥 Импорт клиента", "import_client")}) keyboard = append(keyboard, []map[string]interface{}{inlineButton("◀️ Главное меню", "mainmenu")}) replyMarkup := map[string]interface{}{"inline_keyboard": keyboard} return sendOrEditTelegram(token, adminID, messageID, txt, replyMarkup) diff --git a/client_transfer.go b/client_transfer.go new file mode 100644 index 0000000..2c2c9c7 --- /dev/null +++ b/client_transfer.go @@ -0,0 +1,105 @@ +package main + +import ( + "encoding/json" + "errors" + "strings" + "time" +) + +const ( + clientTransferFormat = "wdtt-plus-client" + clientTransferVersion = 1 +) + +type clientTransferPayload struct { + Format string `json:"format"` + Version int `json:"version"` + CreatedAt int64 `json:"created_at"` + Password string `json:"password"` + Label string `json:"label,omitempty"` + VkHash string `json:"vk_hash,omitempty"` + ExpiresAt int64 `json:"expires_at"` + Deactivated bool `json:"deactivated"` +} + +func encodeClientTransfer(password string, entry *PasswordEntry) (string, error) { + password, err := normalizeClientPassword(password) + if err != nil { + return "", err + } + if entry == nil { + return "", errors.New("данные клиента не найдены") + } + payload := clientTransferPayload{ + Format: clientTransferFormat, + Version: clientTransferVersion, + CreatedAt: time.Now().UnixMilli(), + Password: password, + Label: normalizePasswordLabel(entry.Label), + VkHash: strings.TrimSpace(entry.VkHash), + ExpiresAt: entry.ExpiresAt, + Deactivated: entry.IsDeactivated, + } + if payload.VkHash != "" { + normalized, err := normalizeTransferVKHashes(payload.VkHash) + if err != nil { + return "", err + } + payload.VkHash = normalized + } + data, err := json.Marshal(payload) + if err != nil { + return "", err + } + return string(data), nil +} + +func decodeClientTransfer(value string) (clientTransferPayload, error) { + var payload clientTransferPayload + if err := json.Unmarshal([]byte(strings.TrimSpace(value)), &payload); err != nil { + return payload, errors.New("данные клиента повреждены или имеют неверный формат") + } + if payload.Format != clientTransferFormat { + return payload, errors.New("это не перенос клиента WDTT Plus") + } + if payload.Version != clientTransferVersion { + return payload, errors.New("версия переноса клиента не поддерживается") + } + password, err := normalizeClientPassword(payload.Password) + if err != nil { + return payload, err + } + payload.Password = password + payload.Label = normalizePasswordLabel(payload.Label) + if len(payload.VkHash) > 4096 || strings.ContainsAny(payload.VkHash, "\x00\r") { + return payload, errors.New("поле VK-хешей повреждено") + } + if strings.TrimSpace(payload.VkHash) != "" { + normalized, err := normalizeTransferVKHashes(payload.VkHash) + if err != nil { + return payload, err + } + payload.VkHash = normalized + } + if payload.ExpiresAt < 0 { + return payload, errors.New("в переносе указан некорректный срок") + } + if payload.ExpiresAt > 0 && payload.ExpiresAt <= time.Now().Unix() { + return payload, errors.New("срок переносимого клиента уже истёк") + } + return payload, nil +} + +func normalizeTransferVKHashes(value string) (string, error) { + normalized, err := normalizeVKHashesInput(value) + if err != nil { + return "", err + } + for _, hash := range strings.Split(normalized, ",") { + if len(hash) < 16 { + return "", errors.New("VK-хеши в переносе имеют неверный формат") + } + } + return normalized, nil +} diff --git a/client_transfer_test.go b/client_transfer_test.go new file mode 100644 index 0000000..e1afbcd --- /dev/null +++ b/client_transfer_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "strings" + "testing" +) + +func TestClientTransferRoundTripOmitsServerState(t *testing.T) { + encoded, err := encodeClientTransfer("ABCDEFGHJKLMNPQR", &PasswordEntry{ + Label: "Телефон", + VkHash: "abcdefghijklmnop", + ExpiresAt: 1900000000, + DeviceID: "device-secret", + DownBytes: 123, + Ports: "56010,56011,9010", + IsDeactivated: true, + }) + if err != nil { + t.Fatal(err) + } + for _, forbidden := range []string{"device-secret", "down_bytes", "ports", "host"} { + if strings.Contains(encoded, forbidden) { + t.Fatalf("transfer leaked server-specific field %q: %s", forbidden, encoded) + } + } + payload, err := decodeClientTransfer(encoded) + if err != nil { + t.Fatal(err) + } + if payload.Password != "ABCDEFGHJKLMNPQR" || payload.Label != "Телефон" || !payload.Deactivated { + t.Fatalf("payload changed after round trip: %#v", payload) + } +} + +func TestClientTransferRejectsInvalidPassword(t *testing.T) { + _, err := decodeClientTransfer(`{"format":"wdtt-plus-client","version":1,"password":"bad password","expires_at":0}`) + if err == nil { + t.Fatal("invalid transfer password was accepted") + } +} + +func TestBotClientCreateAndPasswordChangeAreLive(t *testing.T) { + configDir := t.TempDir() + dbMutex.Lock() + db = &Database{ + MainPassword: "owner-secret", + DefaultPorts: "56000,56001,9000", + MaxPasswords: 10, + Passwords: make(map[string]*PasswordEntry), + Devices: make(map[string]*ClientDevice), + } + dbFile = configDir + "/passwords.json" + maxGeneratedPasswords = 10 + serverWrapKeys = newWrapKeyStore() + dbMutex.Unlock() + + oldPassword := "ABCDEFGHJKLMNPQR" + createdPassword, entry, err := createBotClient(nil, oldPassword, 30, -1, "Перенос", "abcdefghijklmnop", "56000,56001,9000", false) + if err != nil { + t.Fatal(err) + } + if createdPassword != oldPassword || entry.Label != "Перенос" || serverWrapKeys.Count() != 1 { + t.Fatalf("custom bot client was not applied live: password=%q entry=%#v keys=%d", createdPassword, entry, serverWrapKeys.Count()) + } + if _, _, err := createBotClient(nil, oldPassword, 30, -1, "Дубликат", "", "56000,56001,9000", false); err == nil { + t.Fatal("bot accepted a duplicate client password") + } + entry.DeviceID = "phone" + newPassword, err := changeBotClientPassword(nil, oldPassword, "RSTUVWXYZ2345678") + if err != nil { + t.Fatal(err) + } + if newPassword != "RSTUVWXYZ2345678" || serverWrapKeys.Count() != 1 { + t.Fatalf("bot password replacement was not live: password=%q keys=%d", newPassword, serverWrapKeys.Count()) + } + dbMutex.Lock() + defer dbMutex.Unlock() + if db.Passwords[oldPassword] != nil || db.Passwords[newPassword] == nil || db.Passwords[newPassword].DeviceID != "phone" { + t.Fatal("bot password replacement lost the client or its binding") + } +} diff --git a/server.go b/server.go index 3ba3ec4..b6e1c71 100644 --- a/server.go +++ b/server.go @@ -230,6 +230,19 @@ func generatePassword() string { return string(b) } +func normalizeClientPassword(input string) (string, error) { + password := strings.TrimSpace(input) + if len(password) != generatedPasswordLen { + return "", fmt.Errorf("пароль клиента должен содержать ровно %d символов", generatedPasswordLen) + } + for _, ch := range password { + if !strings.ContainsRune(passChars, ch) { + return "", errors.New("пароль клиента содержит недопустимые символы") + } + } + return password, nil +} + var publicIP string = "" func getPublicIP() string {