diff --git a/CHANGELOG.md b/CHANGELOG.md index af5ecfc..a39dcc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ Здесь фиксируются заметные пользовательские изменения WDTT Plus. +## v17 — 04.09.2026 + +### Готовые профили + +- Исправлен запуск готовых профилей на повышенной мощности: теперь приложение надёжнее набирает все разрешённые потоки и использует доступные резервные подключения при неудачной попытке. +- Обновление готового профиля теперь завершается понятным подтверждением. Приложение отдельно сообщает, были ли сохранены новые настройки или на устройстве уже находится актуальная версия профиля. +- После переноса на резервный сервер приложение запускает туннель только с заново прочитанными актуальными настройками профиля и больше не возвращает старый адрес подключения. +- Сообщение при неудачном подключении стало точнее и больше не указывает на неверный пароль без достаточных оснований. + +### Установка и обновление сервера + +- Исправлена первичная установка на чистый VPS: для неё безопасно создаётся новая база, тогда как обновление существующего сервера по-прежнему требует подтверждённую базу и сохраняет все данные. +- Исправлено повторное развёртывание после прерванной установки версии 16: приложение безопасно распознаёт такое состояние и позволяет явно начать установку заново. +- Проверки владельца установки теперь различают чистую установку, обновление с сохранением и полный сброс, не позволяя случайно применить один режим вместо другого. +- Встроенный Telegram-бот сервера продолжает работать после обновления с сохранением и использует ранее сохранённые настройки без повторного ввода. +- После обновления до версии 17 приложение напоминает администраторам обновить серверную часть с сохранением данных. + +### Диагностика + +- Серверный отчёт теперь явно показывает профиль, выбранный в момент запуска проверки. Общая диагностика при остановленном VPN также использует текущий выбранный профиль, а не последний ранее запущенный. + ## v16 — 04.09.2026 ### Ручной установщик сервера diff --git a/README.md b/README.md index 54d5027..ad9af65 100644 --- a/README.md +++ b/README.md @@ -309,7 +309,7 @@ Telegram-бот умеет посмотреть статус и диагност ./gradlew :app:prepareGithubReleaseArtifacts ``` -Она сначала удаляет прежний готовый набор, выполняет release-сборку и закрытый аудит, а затем создаёт `app/build/outputs/release-ready/` с четырьмя APK, standalone-архивом того же серверного бинарника, его внешней контрольной суммой и отдельным архивом WARP-менеджера. Если сервер внутри хотя бы одного APK, standalone-архива или текущих исходников отличается либо архив WARP не прошёл проверку, готовый каталог не создаётся. +Она сначала удаляет прежний готовый набор, выполняет release-сборку и закрытый аудит, а затем создаёт `app/build/outputs/release-ready/` ровно с шестью файлами: четырьмя APK, standalone-архивом того же серверного бинарника и его внешней контрольной суммой. Если сервер внутри хотя бы одного APK, standalone-архива или текущих исходников отличается, готовый каталог не создаётся. Самостоятельный WARP-менеджер остаётся отдельным подпроектом и в выпуск WDTT Plus автоматически не упаковывается. В `app/src/debug/java/com/wdtt/plus/WDTTPreviews.kt` находятся Compose Preview основных вкладок. Они входят только в debug source set и не попадают в release APK. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index b118e54..0ce0d32 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -46,7 +46,7 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") } -val appVersionName = "16" +val appVersionName = "17" val releaseApkBaseName = "WDTT-Plus" val localProperties = Properties() @@ -90,7 +90,7 @@ android { applicationId = "com.wdtt.plus" minSdk = 28 targetSdk = 35 - versionCode = 16 + versionCode = 17 versionName = appVersionName buildConfigField("String", "MOD_RELEASE_DATE", "\"04.09.2026\"") buildConfigField("String", "WDTT_PLUS_DOMAIN", buildConfigString(wdttPlusDomain)) diff --git a/app/src/main/assets/deploy.sh b/app/src/main/assets/deploy.sh index 2396f14..586fc55 100755 --- a/app/src/main/assets/deploy.sh +++ b/app/src/main/assets/deploy.sh @@ -2,20 +2,22 @@ # ============================================================================== # WDTT Plus Server — Универсальный установщик для VPS # Поддержка: Debian 11+, Ubuntu 20.04+, CentOS/RHEL/Fedora/AlmaLinux/Rocky -# Версия: 3.9 | Дата: 2026-09-02 +# Версия: 3.10 | Дата: 2026-09-04 # NAT: MASQUERADE через iptables # WG: порт 56001 (не конфликтует с существующим WG на 51820) # DTLS: порт 56000 # ============================================================================== set -euo pipefail -readonly SCRIPT_VERSION="3.9" +readonly SCRIPT_VERSION="3.10" readonly WDTT_DEPLOY_CONTRACT_VERSION="1" -readonly WDTT_SERVER_VERSION="16" +readonly WDTT_SERVER_VERSION="17" readonly WDTT_SERVER_BINARY_PATH="/usr/local/bin/wdtt-server" readonly WDTT_SYSTEMD_UNIT_PATH="/etc/systemd/system/wdtt.service" readonly WDTT_ANDROID_DEPLOY_MARKER="Managed by WDTT Plus Android deploy" readonly WDTT_ANDROID_CONTRACT_MARKER="WDTT deploy compatibility: 1" +readonly WDTT_STANDALONE_MARKER="Managed by WDTT Plus standalone server installer" +readonly WDTT_STANDALONE_OWNERSHIP_PATH="/var/lib/wdtt-server-installer/ownership" readonly LOG_FILE="/var/log/wdtt-install.log" readonly WG_PORT="${WDTT_WG_PORT:-56001}" readonly DTLS_PORT="${WDTT_DTLS_PORT:-56000}" @@ -27,6 +29,7 @@ readonly HANDSHAKE_RATE="${WDTT_HANDSHAKE_RATE:-24}" readonly MAX_CLIENT_MBPS="${WDTT_MAX_CLIENT_MBPS:-0}" readonly WG_BACKEND="${WDTT_WG_BACKEND:-auto}" readonly WDTT_PRESERVE_DATA="${WDTT_PRESERVE_DATA:-0}" +readonly WDTT_INSTALL_MODE="${WDTT_INSTALL_MODE:-}" readonly WDTT_IFACE="wdtt0" readonly WDTT_CONFIG_DIR="/etc/wdtt" readonly WDTT_ACCESS_DB="passwords.json" @@ -387,6 +390,43 @@ secure_preserved_config() { validate_deploy_data_mode() { local database="$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" + case "$WDTT_INSTALL_MODE" in + fresh) + [ "$WDTT_PRESERVE_DATA" = "0" ] || + die "Первичная установка несовместима с режимом сохранения" + if [ -e "$WDTT_SYSTEMD_UNIT_PATH" ] || [ -e "$WDTT_SERVER_BINARY_PATH" ] || + [ -e "$WDTT_CONFIG_DIR" ]; then + die "Первичная установка остановлена: после проверки появились следы WDTT" + fi + ;; + preserve) + [ "$WDTT_PRESERVE_DATA" = "1" ] || + die "Обновление с сохранением запущено без защиты данных" + if [ -f "$WDTT_STANDALONE_OWNERSHIP_PATH" ] && + grep -Fqx "${WDTT_STANDALONE_MARKER}" "$WDTT_STANDALONE_OWNERSHIP_PATH"; then + die "Обновление остановлено: сервер управляется standalone-инсталлером" + fi + [ -f "$WDTT_SYSTEMD_UNIT_PATH" ] && [ ! -L "$WDTT_SYSTEMD_UNIT_PATH" ] && + [ -x "$WDTT_SERVER_BINARY_PATH" ] && [ ! -L "$WDTT_SERVER_BINARY_PATH" ] && + [ -d "$WDTT_CONFIG_DIR" ] && [ ! -L "$WDTT_CONFIG_DIR" ] || + die "Обновление остановлено: признаки Android-установки изменились после проверки" + if ! grep -Fqx "# ${WDTT_ANDROID_DEPLOY_MARKER}" "$WDTT_SYSTEMD_UNIT_PATH"; then + [ -f "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] && + [ ! -L "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] && + grep -Eq '^ExecStart=/usr/local/bin/wdtt-server([[:space:]]|$)' "$WDTT_SYSTEMD_UNIT_PATH" && + grep -Eq '(^|[[:space:]])-config-dir[[:space:]]+/etc/wdtt([[:space:]]|$)' "$WDTT_SYSTEMD_UNIT_PATH" && + grep -Fq 'wdtt0' "$WDTT_SYSTEMD_UNIT_PATH" || + die "Обновление остановлено: не удалось подтвердить старую Android-установку" + fi + ;; + reset) + [ "$WDTT_PRESERVE_DATA" = "0" ] || + die "Полный сброс несовместим с режимом сохранения" + ;; + *) + die "Приложение не указало безопасный режим установки" + ;; + esac if [ -e "$database" ] && [ "$WDTT_PRESERVE_DATA" != "1" ]; then die "Найдена существующая база WDTT. Обновление разрешено только в режиме сохранения; явный сброс должен заранее удалить старую базу после подтверждения в приложении." fi diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt index 214e205..d54e3a2 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -164,7 +164,10 @@ private sealed interface WdttConnectFlow { val access: RemoteAccessCapability, val message: String ) : WdttConnectFlow - data class Complete(val message: String) : WdttConnectFlow + data class Complete( + val message: String, + val title: String = "Подключение WDTT Plus", + ) : WdttConnectFlow data class Failed( val message: String, val action: RemoteDocumentFailureAction? = null, @@ -839,7 +842,18 @@ class MainActivity : ComponentActivity() { } } if (shouldRestoreUiAfterBoundUpdate(isBoundUpdate)) { - wdttConnectFlow = null + val profileLabel = vpnProfileDisplayName( + profile, + store.profileNames.first(), + ) + val confirmation = boundProfileUpdateConfirmation( + profileLabel = profileLabel, + alreadyApplied = result?.alreadyApplied == true, + ) + wdttConnectFlow = WdttConnectFlow.Complete( + message = confirmation.message, + title = confirmation.title, + ) } else if ( existingRemoteProfile && store.tunnelProfileSnapshot(profile).vkHashes.isNotBlank() @@ -2290,7 +2304,15 @@ private fun WdttConnectActivationDialog( } }, modifier = Modifier.televisionDialogWidth(television), - title = { Text("Подключение WDTT Plus") }, + title = { + Text( + if (flow is WdttConnectFlow.Complete) { + flow.title + } else { + "Подключение WDTT Plus" + } + ) + }, text = { AnimatedContent( targetState = flow, diff --git a/app/src/main/java/com/wdtt/plus/RemoteProfileUpdatePresentation.kt b/app/src/main/java/com/wdtt/plus/RemoteProfileUpdatePresentation.kt new file mode 100644 index 0000000..1358d16 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/RemoteProfileUpdatePresentation.kt @@ -0,0 +1,22 @@ +package com.wdtt.plus + +internal data class BoundProfileUpdateConfirmation( + val title: String, + val message: String, +) + +internal fun boundProfileUpdateConfirmation( + profileLabel: String, + alreadyApplied: Boolean, +): BoundProfileUpdateConfirmation = + if (alreadyApplied) { + BoundProfileUpdateConfirmation( + title = "Профиль уже обновлён", + message = "Актуальные настройки профиля $profileLabel уже сохранены на этом устройстве.", + ) + } else { + BoundProfileUpdateConfirmation( + title = "Профиль обновлён", + message = "Новые настройки профиля $profileLabel сохранены. Можно подключаться.", + ) + } diff --git a/app/src/main/java/com/wdtt/plus/ServerMigration.kt b/app/src/main/java/com/wdtt/plus/ServerMigration.kt index 2b9613f..11cfc31 100644 --- a/app/src/main/java/com/wdtt/plus/ServerMigration.kt +++ b/app/src/main/java/com/wdtt/plus/ServerMigration.kt @@ -1,7 +1,7 @@ package com.wdtt.plus /** Версии приложения, для которых выпускалась новая обязательная серверная часть. */ -internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15, 16) +internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15, 16, 17) data class ServerMigrationState( val pendingLevel: Int, diff --git a/app/src/main/java/com/wdtt/plus/SettingsStore.kt b/app/src/main/java/com/wdtt/plus/SettingsStore.kt index 8f79eba..d5ea453 100644 --- a/app/src/main/java/com/wdtt/plus/SettingsStore.kt +++ b/app/src/main/java/com/wdtt/plus/SettingsStore.kt @@ -2855,6 +2855,44 @@ class SettingsStore(context: Context) { } } + /** + * Flushes editable launch options for one exact profile before an access refresh. + * A remotely managed profile keeps its connection endpoint and secret exclusively + * under the atomic remote-document transaction; stale UI state must never write + * those fields back after a server move. + */ + suspend fun saveTunnelOptionsBeforeStart( + profileIndex: Int, + peer: String, + preserveManagedConnection: Boolean, + vkHashes: String, + secondaryVkHash: String, + workersPerHash: Int, + protocol: String, + listenPort: Int, + sni: String = "", + noDns: Boolean = false, + captchaMode: String, + captchaSolveMethod: String, + ) { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + val managedNow = prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true + if (!(preserveManagedConnection || managedNow)) { + prefs[getProfileKey(PEER, profile)] = peer + } + prefs[getProfileKey(VK_HASHES, profile)] = vkHashes + prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = secondaryVkHash + prefs[getProfileKey(WORKERS_PER_HASH, profile)] = workersPerHash + prefs[getProfileKey(PROTOCOL, profile)] = protocol + prefs[getProfileKey(LISTEN_PORT, profile)] = listenPort + prefs[getProfileKey(SNI, profile)] = sni + prefs[getProfileKey(NO_DNS, profile)] = noDns + prefs[getProfileKey(CAPTCHA_MODE, profile)] = captchaMode + prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] = captchaSolveMethod + } + } + suspend fun applyImportedServerConnection( profileIndex: Int, host: String, diff --git a/app/src/main/java/com/wdtt/plus/TunnelManager.kt b/app/src/main/java/com/wdtt/plus/TunnelManager.kt index 110a97f..90eaf0f 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelManager.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelManager.kt @@ -416,6 +416,14 @@ internal fun isExpiredAccessAuthFailure(line: String): Boolean = internal const val WRAP_HANDSHAKE_RETRY_MESSAGE = "[WRAP] Отдельные каналы не ответили, выполняется повтор" + +internal fun wrapHandshakeTerminalMessage(rtNetwork: Boolean): String = + if (rtNetwork) { + "\uD83C\uDF10 Через сеть РТ не получен ответ WRAP. Обычно сеть не пропустила выбранный TURN/SNI; реже причина в пароле или совместимости WRAP. Воркеры остановлены." + } else { + "\uD83D\uDD0C Сервер не ответил на WRAP. Возможны проблемы с сервером или маршрутом, блокировка UDP/TURN, неверный пароль либо несовместимость WRAP. Воркеры остановлены." + } + internal const val RT_MASQUE_CONFIG_FILE_NAME = "rt-masque-v1.json" internal fun shouldUseRtMasque(rtNetwork: Boolean, rtMasque: Boolean): Boolean = @@ -1552,7 +1560,7 @@ object TunnelManager { if (params.configFirstStart) { cmd.add("-config-first-start=true") - if (totalWorkers == TUNNEL_WORKERS_PER_GROUP) { + if (shouldUseManagedHashFallback(params.profileMaxWorkers, hashCount)) { cmd.add("-hash-fallback=true") } } @@ -2517,11 +2525,8 @@ object TunnelManager { lastActiveAtMs == 0L && !isCaptchaInProgress() ) { - val wrapStopMessage = if (currentParams?.rtNetwork == true) { - "\uD83C\uDF10 Через сеть РТ не получен ответ WRAP. Обычно сеть не пропустила выбранный TURN/SNI; реже причина в пароле или совместимости WRAP. Воркеры остановлены." - } else { - "\uD83D\uDD12 Неверный пароль подключения или несовместимый WRAP. Воркеры остановлены." - } + val wrapStopMessage = + wrapHandshakeTerminalMessage(currentParams?.rtNetwork == true) handleCriticalError(wrapStopMessage) return@launch } else if ( diff --git a/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt b/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt index 9dc91a0..659ad49 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt @@ -87,6 +87,11 @@ internal fun displayedTunnelProfile( */ internal fun shouldUseConfigFirstStart(): Boolean = true +internal fun shouldUseManagedHashFallback( + profileMaxWorkers: Int, + hashCount: Int, +): Boolean = profileMaxWorkers >= TUNNEL_WORKERS_PER_GROUP && hashCount > 1 + suspend fun buildTunnelParamsFromSettings( context: Context, profileIndex: Int? = null, @@ -173,8 +178,11 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? { } } -suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? { - val params = buildTunnelParamsFromSettings(context) ?: return null +suspend fun buildTunnelStartIntentFromSettings( + context: Context, + profileIndex: Int? = null, +): Intent? { + val params = buildTunnelParamsFromSettings(context, profileIndex) ?: return null return Intent(context, TunnelService::class.java).apply { action = "START" putExtra("peer", params.peer) 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 edefa58..3a7ada6 100644 --- a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt @@ -159,7 +159,8 @@ private const val THREEPROXY_SOURCE_SHA256 = private const val THREEPROXY_SOURCE_URL = "https://github.com/3proxy/3proxy/archive/refs/tags/$THREEPROXY_VERSION.tar.gz" -private enum class DeployMode { +internal enum class DeployMode { + FreshInstall, PreserveData, ResetAll } @@ -479,6 +480,7 @@ private data class ExistingInstallInfo( val standaloneManaged: Boolean = false, val androidDeployManaged: Boolean = false, val legacyAndroidDeployCandidate: Boolean = false, + val incompleteAndroidDeployCandidate: Boolean = false, val checkError: String? = null, val comparison: DeployServerComparison? = null ) { @@ -491,17 +493,20 @@ internal enum class DeploymentOwnership { StandaloneInstaller, AndroidDeploy, LegacyAndroidDeploy, + IncompleteAndroidDeploy, UnknownExisting } internal fun existingInstallOwnershipFromFlags( standaloneManaged: Boolean, androidDeployManaged: Boolean, - legacyAndroidDeployCandidate: Boolean + legacyAndroidDeployCandidate: Boolean, + incompleteAndroidDeployCandidate: Boolean = false, ): DeploymentOwnership = when { standaloneManaged -> DeploymentOwnership.StandaloneInstaller androidDeployManaged -> DeploymentOwnership.AndroidDeploy legacyAndroidDeployCandidate -> DeploymentOwnership.LegacyAndroidDeploy + incompleteAndroidDeployCandidate -> DeploymentOwnership.IncompleteAndroidDeploy else -> DeploymentOwnership.UnknownExisting } @@ -516,7 +521,10 @@ internal fun existingInstallAllowsPreservingUpdate( internal fun existingInstallAllowsReset( ownership: DeploymentOwnership, checkSucceeded: Boolean -): Boolean = checkSucceeded && ownership == DeploymentOwnership.AndroidDeploy +): Boolean = checkSucceeded && ownership in setOf( + DeploymentOwnership.AndroidDeploy, + DeploymentOwnership.IncompleteAndroidDeploy, +) internal data class OutboundProfileForms( val localProxyPort: String, @@ -1951,7 +1959,7 @@ fun DeployTab( pendingDeployRequest = request existingInstallInfo = info } else { - launchDeploy(request, DeployMode.PreserveData) + launchDeploy(request, DeployMode.FreshInstall) } } catch (e: Exception) { val friendly = friendlyDeployError(e, "проверка сервера") @@ -6733,9 +6741,9 @@ private fun serverDiagnosticsErrorReport( private fun serverProfileDiagnosticItem(profileName: String, profileIndex: Int?): DeviceCheckItem { val number = profileIndex?.let { (it + 1).coerceAtLeast(1).toString() } ?: "?" return DeviceCheckItem( - title = "Активный VPN-профиль", + title = "Выбранный профиль", status = "профиль $number — $profileName", - details = "Диагностика собрана строго из текущего активного профиля приложения: его адреса сервера, логина, SSH-порта и выбранного способа входа.", + details = "Диагностика собрана строго из профиля, выбранного в приложении на момент запуска: его адреса сервера, логина, SSH-порта и способа входа.", recommendation = "Если нужно проверить другой сервер, сначала переключите VPN-профиль в приложении и запустите диагностику заново.", severity = DeviceCheckSeverity.Info ) @@ -10737,7 +10745,11 @@ private suspend fun checkExistingInstall( active = Regex("^ACTIVE=active$", RegexOption.MULTILINE).containsMatchIn(output), standaloneManaged = markerValue(output, "WDTT_STANDALONE_MANAGED") == "1", androidDeployManaged = markerValue(output, "WDTT_ANDROID_DEPLOY_MANAGED") == "1", - legacyAndroidDeployCandidate = markerValue(output, "WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE") == "1" + legacyAndroidDeployCandidate = markerValue(output, "WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE") == "1", + incompleteAndroidDeployCandidate = markerValue( + output, + "WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE" + ) == "1" ) } finally { try { session?.disconnect() } catch (_: Exception) {} @@ -10784,6 +10796,20 @@ internal fun standaloneInstallerOwnershipProbeScript(pathPrefix: String = ""): S else printf 'WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=0\n' fi + incomplete_extra='' + if [ -d "${'$'}config" ] && [ ! -L "${'$'}config" ]; then + incomplete_extra="${'$'}(find "${'$'}config" -mindepth 1 -maxdepth 1 ! -path "${'$'}passwords" -print -quit 2>/dev/null || true)" + fi + if [ ! -e "${'$'}ownership" ] && [ ! -e "${'$'}unit" ] && [ ! -e "${'$'}binary" ] && + [ -d "${'$'}config" ] && [ ! -L "${'$'}config" ] && + [ -f "${'$'}passwords" ] && [ ! -L "${'$'}passwords" ] && [ -s "${'$'}passwords" ] && + [ ! -e "${'$'}wg_keys" ] && [ -z "${'$'}incomplete_extra" ] && + [ "${'$'}(stat -c '%a' "${'$'}config" 2>/dev/null || true)" = "700" ] && + [ "${'$'}(stat -c '%a' "${'$'}passwords" 2>/dev/null || true)" = "600" ]; then + printf 'WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=1\n' + else + printf 'WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=0\n' + fi if [ -f "${'$'}unit" ] || [ -f "${'$'}binary" ] || [ -d "${'$'}config" ] || [ -f "${'$'}passwords" ] || [ -f "${'$'}wg_keys" ]; then printf 'WDTT_INSTALL_TRACE=1\n' @@ -10794,13 +10820,22 @@ internal fun standaloneInstallerOwnershipProbeScript(pathPrefix: String = ""): S } internal fun deploymentOwnershipFromProbe(output: String): DeploymentOwnership { + val requiredMarkers = listOf( + "WDTT_STANDALONE_MANAGED", + "WDTT_ANDROID_DEPLOY_MANAGED", + "WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE", + "WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE", + "WDTT_INSTALL_TRACE", + ) + if (requiredMarkers.any { markerValue(output, it) !in setOf("0", "1") }) { + throw IllegalStateException("не удалось безопасно проверить владельца установки. Изменяющая операция остановлена.") + } return when { - markerValue(output, "WDTT_STANDALONE_MANAGED") != "0" && - markerValue(output, "WDTT_STANDALONE_MANAGED") != "1" -> - throw IllegalStateException("не удалось безопасно проверить владельца установки. Изменяющая операция остановлена.") markerValue(output, "WDTT_STANDALONE_MANAGED") == "1" -> DeploymentOwnership.StandaloneInstaller markerValue(output, "WDTT_ANDROID_DEPLOY_MANAGED") == "1" -> DeploymentOwnership.AndroidDeploy markerValue(output, "WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE") == "1" -> DeploymentOwnership.LegacyAndroidDeploy + markerValue(output, "WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE") == "1" -> + DeploymentOwnership.IncompleteAndroidDeploy markerValue(output, "WDTT_INSTALL_TRACE") == "0" -> DeploymentOwnership.NoInstall markerValue(output, "WDTT_INSTALL_TRACE") == "1" -> DeploymentOwnership.UnknownExisting else -> throw IllegalStateException("не удалось безопасно проверить владельца установки. Изменяющая операция остановлена.") @@ -10812,23 +10847,44 @@ private fun deploymentOwnership(ssh: SSHClient): DeploymentOwnership { return deploymentOwnershipFromProbe(output) } -private fun assertDeploymentMayBeUpdated(ownership: DeploymentOwnership, mode: DeployMode) { - when (ownership) { - DeploymentOwnership.StandaloneInstaller -> throw IllegalStateException( +internal fun assertDeploymentMayBeUpdated( + ownership: DeploymentOwnership, + mode: DeployMode, +) { + when { + ownership == DeploymentOwnership.StandaloneInstaller -> throw IllegalStateException( "сервер управляется отдельным standalone-инсталлером. Android-приложение не обновляет " + "и не перезаписывает такую установку; используйте server-installer/install.sh на VPS." ) - DeploymentOwnership.AndroidDeploy, DeploymentOwnership.NoInstall -> Unit - DeploymentOwnership.LegacyAndroidDeploy -> if (mode == DeployMode.ResetAll) { + ownership == DeploymentOwnership.UnknownExisting -> throw IllegalStateException( + "на сервере есть неизвестная установка WDTT без безопасных признаков Android-деплоя. " + + "Изменяющая операция остановлена." + ) + mode == DeployMode.FreshInstall && ownership != DeploymentOwnership.NoInstall -> + throw IllegalStateException( + "первичная установка остановлена: на сервере появились следы WDTT. " + + "Повторите проверку и выберите безопасное действие для найденной установки." + ) + mode == DeployMode.PreserveData && ownership !in setOf( + DeploymentOwnership.AndroidDeploy, + DeploymentOwnership.LegacyAndroidDeploy, + ) -> throw IllegalStateException( + "обновление с сохранением разрешено только для подтверждённой Android-установки." + ) + ownership == DeploymentOwnership.LegacyAndroidDeploy && mode == DeployMode.ResetAll -> { throw IllegalStateException( "старая Android-установка без метки допускает только обновление с сохранением. " + "После успешного обновления появится метка, а сброс по-прежнему потребует отдельного подтверждения." ) } - DeploymentOwnership.UnknownExisting -> throw IllegalStateException( - "на сервере есть неизвестная установка WDTT без безопасных признаков Android-деплоя. " + - "Изменяющая операция остановлена." - ) + mode == DeployMode.ResetAll && ownership !in setOf( + DeploymentOwnership.AndroidDeploy, + DeploymentOwnership.IncompleteAndroidDeploy, + ) -> + throw IllegalStateException( + "полный сброс разрешён только для установки с подтверждённой меткой Android-деплоя." + ) + else -> Unit } } @@ -10841,7 +10897,9 @@ private fun assertAndroidDeployMayManageServer(ssh: SSHClient, operation: String DeploymentOwnership.LegacyAndroidDeploy -> throw IllegalStateException( "старая Android-установка без метки не допускает $operation. Сначала выполните обновление с сохранением." ) - DeploymentOwnership.NoInstall, DeploymentOwnership.UnknownExisting -> throw IllegalStateException( + DeploymentOwnership.NoInstall, + DeploymentOwnership.IncompleteAndroidDeploy, + DeploymentOwnership.UnknownExisting -> throw IllegalStateException( "не удалось безопасно подтвердить, что установка принадлежит Android-деплою. $operation остановлено." ) } @@ -13387,12 +13445,19 @@ private suspend fun performDeploy( if ( mode == DeployMode.PreserveData || importPlan != null || - (mode == DeployMode.ResetAll && ownership == DeploymentOwnership.AndroidDeploy) + (mode == DeployMode.ResetAll && ownership in setOf( + DeploymentOwnership.AndroidDeploy, + DeploymentOwnership.IncompleteAndroidDeploy, + )) ) { - onProgress(0.055f, "Проверка сохранённых данных...") - val currentDbJson = readRemotePasswordsJson(ssh)?.also { - validatePasswordsDbForPreserving(JSONObject(it), mainPass) - } + onProgress(0.055f, "Проверка сохранённых данных...") + val currentDbJson = readRemotePasswordsJson(ssh)?.also { + if (ownership == DeploymentOwnership.IncompleteAndroidDeploy) { + validatePasswordsDbStructure(JSONObject(it)) + } else { + validatePasswordsDbForPreserving(JSONObject(it), mainPass) + } + } if (mode == DeployMode.PreserveData && currentDbJson == null) { throw IllegalStateException( "обновление с сохранением остановлено: на сервере нет passwords.json; " + @@ -13437,6 +13502,11 @@ private suspend fun performDeploy( onProgress(0.08f, "Установка...") if (mode == DeployMode.ResetAll) { onProgress(0.075f, "Сброс старых данных...") + val resetOwnership = deploymentOwnership(ssh) + require(resetOwnership == ownership) { + "состояние установки изменилось после проверки; сброс остановлен" + } + assertDeploymentMayBeUpdated(resetOwnership, DeployMode.ResetAll) ssh.exec( rootCommand( "systemctl stop wdtt 2>/dev/null || true; " + @@ -13478,6 +13548,11 @@ private suspend fun performDeploy( val output = ssh.exec( rootCommand( "env WDTT_DTLS_PORT=$dtlsPort WDTT_WG_PORT=$wgPort WDTT_SSH_PORT=$port " + + "WDTT_INSTALL_MODE=${when (mode) { + DeployMode.FreshInstall -> "fresh" + DeployMode.PreserveData -> "preserve" + DeployMode.ResetAll -> "reset" + }} " + "WDTT_PRESERVE_DATA=${if (mode == DeployMode.PreserveData) 1 else 0} " + "${if (stagedDatabaseFile != null) "WDTT_STAGED_DB=/tmp/wdtt-passwords.json.new " else ""}" + "bash /tmp/deploy.sh" @@ -15701,7 +15776,8 @@ private fun ExistingInstallDialog( val ownership = existingInstallOwnershipFromFlags( standaloneManaged = info.standaloneManaged, androidDeployManaged = info.androidDeployManaged, - legacyAndroidDeployCandidate = info.legacyAndroidDeployCandidate + legacyAndroidDeployCandidate = info.legacyAndroidDeployCandidate, + incompleteAndroidDeployCandidate = info.incompleteAndroidDeployCandidate, ) val preservingUpdateAllowed = existingInstallAllowsPreservingUpdate( ownership = ownership, @@ -15795,6 +15871,12 @@ private fun ExistingInstallDialog( style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary ) + } else if (ownership == DeploymentOwnership.IncompleteAndroidDeploy) { + Text( + "Найден точный остаток незавершённой Android-установки: защищённая база есть, но служба, бинарник и WireGuard-ключи не были созданы. Обновление с сохранением недоступно; можно только явно начать установку с нуля.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary + ) } else if (info.hasAnyTrace) { Text( "Установка без подтверждённых признаков Android-деплоя. Чтобы не изменить чужой сервер, обновление, импорт, удаление и сброс заблокированы.", @@ -15864,6 +15946,8 @@ private fun ExistingInstallDialog( "С сохранением данных: обновится бинарник, серверные настройки будут взяты из приложения, а клиентские пароли, привязки устройств, история и ключи сохранятся. Перед изменением создаётся страховочная копия.\n\nЭто одноразовый путь миграции старого Android-деплоя. Сброс, удаление и импорт будут доступны только после успешного обновления и появления метки." } else if (ownership == DeploymentOwnership.AndroidDeploy) { "С сохранением данных: обновится бинарник, серверные настройки будут взяты из приложения, а клиентские пароли, привязки устройств, история и ключи сохранятся. Перед изменением создаётся страховочная копия.\n\nС нуля: данные WDTT Plus на сервере будут удалены, все выданные ссылки и привязки пропадут; затем сервер получит текущие поля приложения." + } else if (ownership == DeploymentOwnership.IncompleteAndroidDeploy) { + "Незавершённая установка не содержит работающего сервера. «Начать с нуля» сначала проверит базу и подготовит транзакционный откат, а затем заново установит сервер. Любые другие неизвестные следы по-прежнему блокируются." } else { "Владелец установки не подтверждён. Обновление, импорт, сброс и удаление заблокированы до успешной безопасной проверки." }, @@ -15923,6 +16007,7 @@ private fun ExistingInstallDialog( } if (showResetConfirmation) { ServerResetConfirmDialog( + incompleteInstall = ownership == DeploymentOwnership.IncompleteAndroidDeploy, onDismiss = { showResetConfirmation = false }, onConfirm = { showResetConfirmation = false @@ -15935,6 +16020,7 @@ private fun ExistingInstallDialog( @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ServerResetConfirmDialog( + incompleteInstall: Boolean = false, onDismiss: () -> Unit, onConfirm: () -> Unit ) { @@ -15953,8 +16039,11 @@ private fun ServerResetConfirmDialog( "Затем сервер будет заново установлен из текущих полей приложения." ) Text( - "Перед удалением приложение создаст проверенную страховочную копию. " + - "Для запуска непрерывно удерживайте кнопку 3 секунды.", + (if (incompleteInstall) { + "База будет проверена и сохранена для отката, если новая установка не запустится. " + } else { + "Перед удалением приложение создаст проверенную страховочную копию. " + }) + "Для запуска непрерывно удерживайте кнопку 3 секунды.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) diff --git a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt index ec3bdd7..b6c5902 100644 --- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt @@ -127,6 +127,7 @@ import com.wdtt.plus.SleepBatteryRuntimeState import com.wdtt.plus.TunnelManager import com.wdtt.plus.TrustedWifiManager import com.wdtt.plus.decodeStoredVpnPackages +import com.wdtt.plus.displayedTunnelProfile import com.wdtt.plus.trustedWifiAccessProblem import com.wdtt.plus.sleepBatteryModeItem import com.wdtt.plus.trustedWifiModeItem @@ -369,9 +370,15 @@ fun InfoTab( ) val selectedProfile = runCatching { settingsStore.activeProfile.first() }.getOrDefault(0) val savedTunnelProfile = runCatching { settingsStore.activeTunnelProfile.first() }.getOrNull() - val diagnosticProfile = TunnelManager.activeTunnelProfile.value - ?: savedTunnelProfile - ?: selectedProfile + val trustedWifiRuntime = TrustedWifiManager.state.value + val trustedWifiWaiting = trustedWifiRuntime.waiting || + runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false) + val diagnosticProfile = displayedTunnelProfile( + selectedProfile = selectedProfile, + activeTunnelProfile = TunnelManager.activeTunnelProfile.value ?: savedTunnelProfile, + running = TunnelManager.running.value, + trustedWifiWaiting = trustedWifiWaiting, + ) val profileNames = runCatching { settingsStore.profileNames.first() }.getOrDefault(emptyList()) val diagnosticProfileName = vpnProfileDisplayName(diagnosticProfile, profileNames) val tunnelProfile = runCatching { @@ -394,9 +401,6 @@ fun InfoTab( } val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrDefault(false) val trustedWifiSsids = runCatching { settingsStore.trustedWifiSsids.first() }.getOrDefault(emptyList()) - val trustedWifiRuntime = TrustedWifiManager.state.value - val trustedWifiWaiting = trustedWifiRuntime.waiting || - runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false) val trustedWifiWaitingSsid = trustedWifiRuntime.ssid.ifBlank { runCatching { settingsStore.trustedWifiWaitingSsid.first() }.getOrDefault("") } @@ -2175,9 +2179,16 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S val selectedProfileIndex = runCatching { settingsStore.activeProfile.first() }.getOrNull() val savedTunnelProfileIndex = runCatching { settingsStore.activeTunnelProfile.first() }.getOrNull() - val diagnosticProfileIndex = TunnelManager.activeTunnelProfile.value - ?: savedTunnelProfileIndex - ?: selectedProfileIndex + val trustedWifiWaiting = TrustedWifiManager.state.value.waiting || + runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false) + val diagnosticProfileIndex = selectedProfileIndex?.let { selected -> + displayedTunnelProfile( + selectedProfile = selected, + activeTunnelProfile = TunnelManager.activeTunnelProfile.value ?: savedTunnelProfileIndex, + running = TunnelManager.running.value, + trustedWifiWaiting = trustedWifiWaiting, + ) + } val activeProfile = diagnosticProfileIndex?.plus(1) val routingSettings = diagnosticProfileIndex?.let { profile -> runCatching { settingsStore.vpnRoutingSettingsForProfile(profile) }.getOrNull() @@ -2221,8 +2232,6 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S val loggingEnabled = runCatching { settingsStore.loggingEnabled.first() }.getOrNull() val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrNull() val trustedWifiCount = runCatching { settingsStore.trustedWifiSsids.first().size }.getOrNull() - val trustedWifiWaiting = TrustedWifiManager.state.value.waiting || - runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false) val sleepBatteryEnabled = runCatching { settingsStore.pauseVpnDuringSleep.first() }.getOrNull() val sleepBatteryPauseDelay = runCatching { settingsStore.pauseVpnDuringSleepDelayMinutes.first() }.getOrNull() val sleepBatteryMode = runCatching { settingsStore.sleepBatteryMode.first() }.getOrNull() 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 dd1df27..447637d 100644 --- a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt @@ -112,7 +112,6 @@ import com.wdtt.plus.DEFAULT_VK_CLIENT_IDS import com.wdtt.plus.DEFAULT_RT_TURN_SNI import com.wdtt.plus.ManlCaptchaWebViewManager import com.wdtt.plus.MainActivity -import com.wdtt.plus.CONFIG_FIRST_START_EXTRA import com.wdtt.plus.NativeClientStartupSecrets import com.wdtt.plus.RemoteContinuation import com.wdtt.plus.RemoteContinuationLauncher @@ -128,12 +127,11 @@ import com.wdtt.plus.TunnelService import com.wdtt.plus.TunnelStopCoordinator import com.wdtt.plus.TunnelStopResult import com.wdtt.plus.TunnelTransition -import com.wdtt.plus.TUNNEL_PROFILE_INDEX_EXTRA import com.wdtt.plus.VpnDnsSettingsSnapshot +import com.wdtt.plus.buildTunnelStartIntentFromSettings import com.wdtt.plus.normalizeTunnelWorkerCount import com.wdtt.plus.normalizeRtTurnSni import com.wdtt.plus.nativeClientStartupConfigLine -import com.wdtt.plus.shouldUseConfigFirstStart import com.wdtt.plus.TrustedWifiManager import com.wdtt.plus.VkJoinLink import com.wdtt.plus.WDTTColors @@ -621,76 +619,33 @@ fun SettingsTabContent( val showManualConnectionFields = false val effectiveServerDtlsPort = if (manualPortsEnabled) serverDtlsPortInput.toIntOrNull()?.coerceIn(1, 65535) ?: 56000 else 56000 val effectiveLocalPort = if (manualPortsEnabled) portInput.toIntOrNull()?.coerceIn(1, 65535) ?: 9000 else 9000 - var pendingStartAfterVpnPermission by remember { mutableStateOf(false) } + var pendingStartProfileAfterVpnPermission by remember { mutableStateOf(null) } - fun startTunnelService() { - val effectiveCaptchaMode = if (autoCaptchaEnabled) "auto" else "wv" - val effectiveCaptchaSolveMethod = if (autoCaptchaEnabled) "auto" else "manual" - val normalizedWorkers = normalizeTunnelWorkerCount(workersInput.toInt(), profileMaxWorkers) - saveJob?.cancel() + fun startTunnelService(profileIndex: Int) { scope.launch { - settingsStore.save( - peerInput, hashSlotsForStorage, "", - normalizedWorkers, "udp", effectiveLocalPort, sniInput, false - ) - settingsStore.saveCaptchaMode(effectiveCaptchaMode) - settingsStore.saveCaptchaSolveMethod(effectiveCaptchaSolveMethod) - } - - var finalPeer = "$peerInput:$effectiveServerDtlsPort" - var finalHashes = combinedHashes - var finalLocalPort = effectiveLocalPort - var finalPassword = savedConnectionPassword - - if (wdttLinkMode) { - if (parsedWdttLink != null) { - finalPeer = "${parsedWdttLink.host}:${parsedWdttLink.dtlsPort}" - finalLocalPort = parsedWdttLink.localPort - finalPassword = parsedWdttLink.password - finalHashes = parsedWdttLink.hashes + val intent = buildTunnelStartIntentFromSettings(context, profileIndex) + if (intent == null) { + TunnelManager.reportConnectionIssue( + "Профиль заполнен не полностью", + "Проверьте адрес, пароль подключения и VK-хеши." + ) + TunnelManager.clearTransition() + Toast.makeText(context, "Проверьте настройки профиля", Toast.LENGTH_LONG).show() + return@launch } + if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) + else context.startService(intent) } - - val intent = Intent(context, TunnelService::class.java).apply { - action = "START" - putExtra("peer", finalPeer) - putExtra("vk_hashes", finalHashes) - putExtra("secondary_vk_hash", "") - putExtra("workers_per_hash", normalizedWorkers) - putExtra("port", finalLocalPort) - putExtra("sni", sniInput) - putExtra("connection_password", finalPassword) - putExtra("vkcalls_preflight", vkCallsPreflight) - putExtra("rt_network", rtNetwork) - putExtra("rt_masque", rtMasque) - putExtra("rt_masque_server_bootstrap", effectiveRtMasqueServerBootstrap) - putExtra("rt_turn_sni", rtTurnSniInput) - putExtra("captcha_mode", effectiveCaptchaMode) - putExtra("captcha_solve_method", effectiveCaptchaSolveMethod) - putExtra("fingerprint", activeFingerprint) - putExtra("client_ids", activeClientIds) - putExtra("custom_vk_credentials_enabled", customVkCredentialsEnabled) - putExtra("custom_vk_client_id", customVkClientId) - putExtra("custom_vk_client_secret", customVkClientSecret) - putExtra("profile_max_workers", profileMaxWorkers) - putExtra( - CONFIG_FIRST_START_EXTRA, - shouldUseConfigFirstStart(), - ) - putExtra(TUNNEL_PROFILE_INDEX_EXTRA, activeProfile) - } - if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) - else context.startService(intent) } val vpnPermissionLauncher = rememberLauncherForActivityResult( ActivityResultContracts.StartActivityForResult() ) { - if (pendingStartAfterVpnPermission) { - pendingStartAfterVpnPermission = false + pendingStartProfileAfterVpnPermission?.let { profileIndex -> + pendingStartProfileAfterVpnPermission = null if (VpnService.prepare(context) == null) { TunnelManager.clearConnectionIssue() - startTunnelService() + startTunnelService(profileIndex) } else { TunnelManager.reportConnectionIssue( "VPN-разрешение не выдано", @@ -702,14 +657,14 @@ fun SettingsTabContent( } } - fun requestVpnAndStart() { + fun requestVpnAndStart(profileIndex: Int) { val vpnIntent = VpnService.prepare(context) if (vpnIntent != null) { - pendingStartAfterVpnPermission = true + pendingStartProfileAfterVpnPermission = profileIndex vpnPermissionLauncher.launch(vpnIntent) } else { TunnelManager.clearConnectionIssue() - startTunnelService() + startTunnelService(profileIndex) } } @@ -717,13 +672,35 @@ fun SettingsTabContent( TunnelManager.noteStartRequested() scope.launch { try { + val requestedProfile = activeProfile + val effectiveCaptchaMode = if (autoCaptchaEnabled) "auto" else "wv" + val effectiveCaptchaSolveMethod = if (autoCaptchaEnabled) "auto" else "manual" + val normalizedWorkers = normalizeTunnelWorkerCount( + workersInput.toInt(), + profileMaxWorkers, + ) + saveJob?.cancel() + settingsStore.saveTunnelOptionsBeforeStart( + profileIndex = requestedProfile, + peer = peerInput, + preserveManagedConnection = remoteManagedProfile, + vkHashes = hashSlotsForStorage, + secondaryVkHash = "", + workersPerHash = normalizedWorkers, + protocol = "udp", + listenPort = effectiveLocalPort, + sni = sniInput, + noDns = false, + captchaMode = effectiveCaptchaMode, + captchaSolveMethod = effectiveCaptchaSolveMethod, + ) when ( val decision = AccessLifecycleCoordinator.prepareStart( context, - activeProfile, + requestedProfile, ) ) { - AccessStartDecision.Allowed -> requestVpnAndStart() + AccessStartDecision.Allowed -> requestVpnAndStart(requestedProfile) is AccessStartDecision.Denied -> { TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS) TunnelManager.clearTransition() diff --git a/app/src/test/java/com/wdtt/plus/LogSeverityTest.kt b/app/src/test/java/com/wdtt/plus/LogSeverityTest.kt index e26e092..cfece30 100644 --- a/app/src/test/java/com/wdtt/plus/LogSeverityTest.kt +++ b/app/src/test/java/com/wdtt/plus/LogSeverityTest.kt @@ -16,6 +16,18 @@ class LogSeverityTest { assertFalse(WRAP_HANDSHAKE_RETRY_MESSAGE.contains("парол", ignoreCase = true)) } + @Test + fun wrapHandshakeTerminalMessage_doesNotPresentTimeoutAsBadPassword() { + val message = wrapHandshakeTerminalMessage(rtNetwork = false) + + assertEquals( + "\uD83D\uDD0C Сервер не ответил на WRAP. Возможны проблемы с сервером или маршрутом, блокировка UDP/TURN, " + + "неверный пароль либо несовместимость WRAP. Воркеры остановлены.", + message, + ) + assertFalse(message.startsWith("🔒 Неверный пароль")) + } + @Test fun repeatedTurnWorkerFailures_useOneRecoverableWarningKey() { val first = classifyRecoverableWorkerRetry( diff --git a/app/src/test/java/com/wdtt/plus/RemoteProfileUpdatePresentationTest.kt b/app/src/test/java/com/wdtt/plus/RemoteProfileUpdatePresentationTest.kt new file mode 100644 index 0000000..237b5d9 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/RemoteProfileUpdatePresentationTest.kt @@ -0,0 +1,34 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Test + +class RemoteProfileUpdatePresentationTest { + @Test + fun newlyAppliedUpdateHasExplicitConfirmation() { + val confirmation = boundProfileUpdateConfirmation( + profileLabel = "Чехия", + alreadyApplied = false, + ) + + assertEquals("Профиль обновлён", confirmation.title) + assertEquals( + "Новые настройки профиля Чехия сохранены. Можно подключаться.", + confirmation.message, + ) + } + + @Test + fun repeatedLinkConfirmsThatCurrentRevisionIsAlreadyStored() { + val confirmation = boundProfileUpdateConfirmation( + profileLabel = "Чехия", + alreadyApplied = true, + ) + + assertEquals("Профиль уже обновлён", confirmation.title) + assertEquals( + "Актуальные настройки профиля Чехия уже сохранены на этом устройстве.", + confirmation.message, + ) + } +} diff --git a/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt b/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt index 0caeef5..b31590c 100644 --- a/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt +++ b/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt @@ -156,6 +156,22 @@ class ServerMigrationTest { assertEquals(16, latestServerMigrationLevel(16)) } + @Test + fun updateFrom16To17RequiresServerMigration() { + val result = resolveServerMigrationInitialization( + currentVersionCode = 17, + isUpdatedInstall = true, + storedLastSeenAppVersionCode = 16, + storedPendingLevel = 16, + storedAcknowledgedLevel = 16, + legacyAcknowledgedLevel = 5 + ) + + assertEquals(17, result.pendingLevel) + assertEquals(16, result.acknowledgedLevel) + assertEquals(17, latestServerMigrationLevel(17)) + } + @Test fun reinstallSameVersionDoesNotCreateServerMigrationNotice() { val result = resolveServerMigrationInitialization( diff --git a/app/src/test/java/com/wdtt/plus/TunnelStartConfigTest.kt b/app/src/test/java/com/wdtt/plus/TunnelStartConfigTest.kt index d1785c2..22b1c15 100644 --- a/app/src/test/java/com/wdtt/plus/TunnelStartConfigTest.kt +++ b/app/src/test/java/com/wdtt/plus/TunnelStartConfigTest.kt @@ -1,9 +1,20 @@ package com.wdtt.plus import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test class TunnelStartConfigTest { + + @Test + fun managedProfileUsesSpareHashesAtMoreThanOneWorkerGroup() { + assertTrue(shouldUseManagedHashFallback(profileMaxWorkers = 18, hashCount = 4)) + assertTrue(shouldUseManagedHashFallback(profileMaxWorkers = 9, hashCount = 2)) + assertFalse(shouldUseManagedHashFallback(profileMaxWorkers = 0, hashCount = 4)) + assertFalse(shouldUseManagedHashFallback(profileMaxWorkers = 18, hashCount = 1)) + } + @Test fun `wireguard config is required before workers for every profile`() { assertEquals(true, shouldUseConfigFirstStart()) diff --git a/app/src/test/java/com/wdtt/plus/ui/DeployDataSafetyTest.kt b/app/src/test/java/com/wdtt/plus/ui/DeployDataSafetyTest.kt index 948160f..635ff91 100644 --- a/app/src/test/java/com/wdtt/plus/ui/DeployDataSafetyTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/DeployDataSafetyTest.kt @@ -18,6 +18,8 @@ class DeployDataSafetyTest { assertTrue("legacy free-form process arguments remain", "WDTT_ARGS" !in script) assertTrue("preserve mode must keep the whole config tree", "всё содержимое /etc/wdtt сохранено" in script) assertTrue("existing database reset guard is missing", "Найдена существующая база WDTT" in script) + assertTrue("deploy mode must be explicit", "WDTT_INSTALL_MODE" in script) + assertTrue("fresh install must reject new traces", "после проверки появились следы WDTT" in script) assertTrue("staged server version is not checked before replacement", "staged_version" in script) assertTrue("failed service start does not fail deployment", "Сервис wdtt не прошёл проверку запуска" in script) } @@ -34,10 +36,36 @@ class DeployDataSafetyTest { assertFalse("legacy reset phrase must not clutter the main dialog", "Для сброса введите СБРОСИТЬ" in source) assertTrue( "managed Android reset must prepare rollback", - "mode == DeployMode.ResetAll && ownership == DeploymentOwnership.AndroidDeploy" in source + "DeploymentOwnership.IncompleteAndroidDeploy" in source && + "prepareServerUpdateRollback(ssh)" in source ) } + @Test + fun `fresh and preserving deploy modes cannot be confused`() { + assertDeploymentMayBeUpdated(DeploymentOwnership.NoInstall, DeployMode.FreshInstall) + assertDeploymentMayBeUpdated(DeploymentOwnership.AndroidDeploy, DeployMode.PreserveData) + assertDeploymentMayBeUpdated(DeploymentOwnership.LegacyAndroidDeploy, DeployMode.PreserveData) + assertDeploymentMayBeUpdated(DeploymentOwnership.IncompleteAndroidDeploy, DeployMode.ResetAll) + + assertFails { assertDeploymentMayBeUpdated(DeploymentOwnership.NoInstall, DeployMode.PreserveData) } + assertFails { assertDeploymentMayBeUpdated(DeploymentOwnership.AndroidDeploy, DeployMode.FreshInstall) } + assertFails { assertDeploymentMayBeUpdated(DeploymentOwnership.UnknownExisting, DeployMode.FreshInstall) } + assertFails { assertDeploymentMayBeUpdated(DeploymentOwnership.StandaloneInstaller, DeployMode.PreserveData) } + assertFails { assertDeploymentMayBeUpdated(DeploymentOwnership.LegacyAndroidDeploy, DeployMode.ResetAll) } + assertFails { assertDeploymentMayBeUpdated(DeploymentOwnership.IncompleteAndroidDeploy, DeployMode.PreserveData) } + } + + private fun assertFails(block: () -> Unit) { + var failed = false + try { + block() + } catch (_: IllegalStateException) { + failed = true + } + assertTrue("unsafe deployment mode was accepted", failed) + } + @Test fun `dangerous server hold confirms once only after three uninterrupted seconds`() { val start = advanceDangerousServerHold( diff --git a/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt b/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt index fa2f07e..2be4114 100644 --- a/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt +++ b/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt @@ -322,6 +322,7 @@ class OutboundWireGuardTest { assertTrue("WDTT_ANDROID_DEPLOY_MANAGED=1" in script) assertTrue("Managed by WDTT Plus Android deploy" in script) assertTrue("WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=1" in script) + assertTrue("WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=1" in script) assertTrue("WDTT_INSTALL_TRACE=1" in script) assertTrue("-config-dir[[:space:]]+/etc/wdtt" in script) assertTrue("grep -Fq 'wdtt0'" in script) @@ -337,6 +338,7 @@ class OutboundWireGuardTest { assertEquals(1, Regex("(?m)^WDTT_STANDALONE_MANAGED=[01]$").findAll(output).count()) assertEquals(1, Regex("(?m)^WDTT_ANDROID_DEPLOY_MANAGED=[01]$").findAll(output).count()) assertEquals(1, Regex("(?m)^WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=[01]$").findAll(output).count()) + assertEquals(1, Regex("(?m)^WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=[01]$").findAll(output).count()) assertEquals(1, Regex("(?m)^WDTT_INSTALL_TRACE=[01]$").findAll(output).count()) deploymentOwnershipFromProbe(output) } @@ -382,6 +384,21 @@ class OutboundWireGuardTest { ) assertFalse(existingInstallAllowsReset(ownership = legacy, checkSucceeded = true)) + val incomplete = existingInstallOwnershipFromFlags( + standaloneManaged = false, + androidDeployManaged = false, + legacyAndroidDeployCandidate = false, + incompleteAndroidDeployCandidate = true + ) + assertFalse( + existingInstallAllowsPreservingUpdate( + ownership = incomplete, + checkSucceeded = true + ) + ) + assertTrue(existingInstallAllowsReset(ownership = incomplete, checkSucceeded = true)) + assertFalse(existingInstallAllowsReset(ownership = incomplete, checkSucceeded = false)) + val android = existingInstallOwnershipFromFlags( standaloneManaged = false, androidDeployManaged = true, @@ -430,6 +447,49 @@ class OutboundWireGuardTest { } } + @Test + fun ownershipProbe_allowsOnlyExactInterruptedAndroidFootprintToBeReset() { + val root = Files.createTempDirectory("wdtt-incomplete-owner-probe").toFile() + try { + val config = File(root, "etc/wdtt") + config.mkdirs() + assertTrue(config.setReadable(false, false)) + assertTrue(config.setWritable(false, false)) + assertTrue(config.setExecutable(false, false)) + assertTrue(config.setReadable(true, true)) + assertTrue(config.setWritable(true, true)) + assertTrue(config.setExecutable(true, true)) + val database = File(config, "passwords.json") + database.writeText("{\"passwords\":{},\"devices\":{}}\n") + assertTrue(database.setReadable(false, false)) + assertTrue(database.setWritable(false, false)) + assertTrue(database.setExecutable(false, false)) + assertTrue(database.setReadable(true, true)) + assertTrue(database.setWritable(true, true)) + + fun probe(): DeploymentOwnership { + val process = ProcessBuilder( + "bash", + "-c", + standaloneInstallerOwnershipProbeScript(root.absolutePath) + ).redirectErrorStream(true).start() + val output = process.inputStream.bufferedReader().use { it.readText() } + assertEquals(0, process.waitFor()) + return deploymentOwnershipFromProbe(output) + } + + val incomplete = probe() + assertEquals(DeploymentOwnership.IncompleteAndroidDeploy, incomplete) + assertFalse(existingInstallAllowsPreservingUpdate(incomplete, checkSucceeded = true)) + assertTrue(existingInstallAllowsReset(incomplete, checkSucceeded = true)) + + File(config, "foreign.conf").writeText("do-not-touch\n") + assertEquals(DeploymentOwnership.UnknownExisting, probe()) + } finally { + root.deleteRecursively() + } + } + @Test fun deploymentOwnership_allowsOnlyStrictLegacyAndroidShapeForPreserveMigration() { assertEquals( @@ -439,6 +499,7 @@ class OutboundWireGuardTest { WDTT_STANDALONE_MANAGED=0 WDTT_ANDROID_DEPLOY_MANAGED=0 WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=1 + WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=0 WDTT_INSTALL_TRACE=1 """.trimIndent() ) @@ -450,6 +511,7 @@ class OutboundWireGuardTest { WDTT_STANDALONE_MANAGED=0 WDTT_ANDROID_DEPLOY_MANAGED=0 WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=0 + WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=0 WDTT_INSTALL_TRACE=1 """.trimIndent() ) @@ -461,6 +523,7 @@ class OutboundWireGuardTest { WDTT_STANDALONE_MANAGED=0 WDTT_ANDROID_DEPLOY_MANAGED=0 WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=0 + WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=0 WDTT_INSTALL_TRACE=0 """.trimIndent() ) diff --git a/database_persistence_test.go b/database_persistence_test.go index 8b8a97b..78bb83a 100644 --- a/database_persistence_test.go +++ b/database_persistence_test.go @@ -163,6 +163,45 @@ func TestInitDBPreservesStoredDNSWithoutExplicitOverride(t *testing.T) { } } +func TestBotRuntimeCredentialsComeFromProtectedDatabaseAfterUpdate(t *testing.T) { + oldDB, oldDBFile := db, dbFile + t.Cleanup(func() { + db, dbFile = oldDB, oldDBFile + }) + dir := t.TempDir() + stored := testDatabase("owner-secret", 0) + stored.BotToken = "stored-bot-token" + stored.AdminID = "123456" + if err := persistDatabaseFile(filepath.Join(dir, "passwords.json"), stored); err != nil { + t.Fatal(err) + } + + // Version 16+ starts without secret command-line flags. The already stored + // values must still activate the internal bot after the service restarts. + if err := initDB(dir, "", "", "", ""); err != nil { + t.Fatalf("restart with stored bot credentials failed: %v", err) + } + token, adminID := botRuntimeCredentials() + if token != "stored-bot-token" || adminID != "123456" { + t.Fatalf("stored bot credentials were not selected: token=%t admin=%q", token != "", adminID) + } +} + +func TestBotRuntimeCredentialsUseExplicitFirstInstallValues(t *testing.T) { + oldDB, oldDBFile := db, dbFile + t.Cleanup(func() { + db, dbFile = oldDB, oldDBFile + }) + dir := t.TempDir() + if err := initDB(dir, "owner-secret", "654321", "first-install-token", ""); err != nil { + t.Fatalf("first install failed: %v", err) + } + token, adminID := botRuntimeCredentials() + if token != "first-install-token" || adminID != "654321" { + t.Fatalf("first-install bot credentials were not selected: token=%t admin=%q", token != "", adminID) + } +} + func TestInitDBValidatesExplicitDNSOverride(t *testing.T) { oldDB, oldDBFile := db, dbFile t.Cleanup(func() { diff --git a/go_client/group.go b/go_client/group.go index 35bd430..27279b0 100644 --- a/go_client/group.go +++ b/go_client/group.go @@ -60,6 +60,38 @@ func workerDistributionByHash(workerCount, hashCount int) []int { return distribution } +func workerHashCandidates(hashes []string, hashIndex, requestedWorkers int, fallback bool) []string { + if len(hashes) == 0 { + return nil + } + primary := ((hashIndex % len(hashes)) + len(hashes)) % len(hashes) + if !fallback || len(hashes) == 1 { + return []string{hashes[primary]} + } + + groupCount := requestedWorkers / workersPerGroup + if groupCount < 1 { + groupCount = 1 + } + primaryCount := min(groupCount, len(hashes)) + result := make([]string, 0, len(hashes)) + result = append(result, hashes[primary]) + + // Prefer hashes that have no primary group. With 18 workers and four + // hashes this gives group 1 hash 3 as its first reserve and group 2 hash 4, + // so one degraded group does not move onto the other group's live hash. + unusedCount := len(hashes) - primaryCount + for offset := 0; offset < unusedCount; offset++ { + index := primaryCount + (primary+offset)%unusedCount + result = append(result, hashes[index]) + } + for offset := 1; offset < primaryCount; offset++ { + index := (primary + offset) % primaryCount + result = append(result, hashes[index]) + } + return result +} + // startPacer распределяет первичные подключения всех групп по общей шкале // времени. Это позволяет готовить группы параллельно, не создавая всплеск из // десятков одновременных DTLS/TURN-handshake. @@ -238,6 +270,15 @@ func workerRetryDelayAfterCredentialRefresh(err error, result credentialRefreshR return refreshedCredsRetryMin + time.Duration(slot)*refreshedCredsRetrySlot + jitter } +func shouldRotateTurnCandidateAfterSessionError(err error) bool { + if err == nil { + return false + } + message := strings.ToUpper(err.Error()) + return strings.Contains(message, "WRAP_AUTH_TIMEOUT") || + strings.Contains(message, "DTLS ХЕНДШЕЙК") +} + type workerPolicyRetryGate struct { mu sync.Mutex blockedUntil time.Time @@ -432,16 +473,7 @@ func WorkerGroup( } } - hashCandidates := []string{tp.Hashes[hashIndex%len(tp.Hashes)]} - if hashFallback && len(tp.Hashes) > 1 { - hashCandidates = make([]string, 0, len(tp.Hashes)) - for offset := 0; offset < len(tp.Hashes); offset++ { - hashCandidates = append( - hashCandidates, - tp.Hashes[(hashIndex+offset)%len(tp.Hashes)], - ) - } - } + hashCandidates := workerHashCandidates(tp.Hashes, hashIndex, requestedWorkers, hashFallback) selectedHash := 0 hash := hashCandidates[selectedHash] log.Printf("[ГРУППА #%d] Запрос реквизитов подключения", groupID) @@ -595,6 +627,7 @@ func WorkerGroup( shouldGetConfig := getConfig attempt := 0 + turnCandidateRetry := 0 for { if ctx.Err() != nil { @@ -624,7 +657,8 @@ func WorkerGroup( configDelivered, sessErr := RunSession(ctx, tp, peer, d, localPort, getConf, cc, requireConfig, onConfigDelivered, wid, &credsSnapshot, deviceID, password, deviceInfo, - transportSession, stats, turnStreamFirst, turnCapacityGate.reset) + transportSession, stats, turnStreamFirst, turnCandidateRetry, + turnCapacityGate.reset) refreshResult := credentialRefreshNone if getConf { @@ -639,6 +673,10 @@ func WorkerGroup( if ctx.Err() != nil { return } + relayHandshakeFailed := shouldRotateTurnCandidateAfterSessionError(sessErr) + if relayHandshakeFailed { + turnCandidateRetry++ + } if maxWorkers, limited := workerPolicyLimit(sessErr); limited { if shouldRetryWorkerPolicy(maxWorkers, requestedWorkers) { startedRound, round, waitErr := policyRetryGate.wait(ctx, wid) @@ -697,9 +735,23 @@ func WorkerGroup( return } continue + } else if relayHandshakeFailed && + hashFallback && + len(credsSnapshot.TurnURLs) > 0 && + turnCandidateRetry%len(credsSnapshot.TurnURLs) == 0 { + log.Printf("[ВОРКЕР #%d] Ошибка (попытка %d): %s", wid, attempt, errStr) + log.Printf( + "[ВОРКЕР #%d] [TURN] Все relay-пути текущего VK-хеша не провели DTLS; пробуем резервный хеш", + wid, + ) + refreshResult = refreshCreds("TURN relay handshake timeout", credsRevision) } else { log.Printf("[ВОРКЕР #%d] Ошибка (попытка %d): %s", wid, attempt, errStr) } + if refreshResult == credentialRefreshApplied || + refreshResult == credentialRefreshSuperseded { + turnCandidateRetry = 0 + } // Если ошибка STUN (credentials invalid), воркер не сможет переподключиться. Завершаем. isStunDeath := strings.Contains(errStrLower, "error 29") || diff --git a/go_client/group_test.go b/go_client/group_test.go index 8537561..4494ab1 100644 --- a/go_client/group_test.go +++ b/go_client/group_test.go @@ -81,6 +81,29 @@ func TestWorkerDistributionByHashUsesAllHashesWithoutOverloadingOne(t *testing.T } } +func TestWorkerHashCandidatesPreferUnusedManagedProfileHashes(t *testing.T) { + hashes := []string{"hash-1", "hash-2", "hash-3", "hash-4"} + + first := workerHashCandidates(hashes, 0, 18, true) + second := workerHashCandidates(hashes, 1, 18, true) + if !reflect.DeepEqual(first, []string{"hash-1", "hash-3", "hash-4", "hash-2"}) { + t.Fatalf("first group candidates = %v", first) + } + if !reflect.DeepEqual(second, []string{"hash-2", "hash-4", "hash-3", "hash-1"}) { + t.Fatalf("second group candidates = %v", second) + } + if first[1] == second[1] { + t.Fatalf("independent groups unexpectedly share first reserve: %v / %v", first, second) + } +} + +func TestWorkerHashCandidatesKeepOrdinaryProfileOnPrimaryHash(t *testing.T) { + hashes := []string{"hash-1", "hash-2", "hash-3", "hash-4"} + if got := workerHashCandidates(hashes, 1, 18, false); !reflect.DeepEqual(got, []string{"hash-2"}) { + t.Fatalf("ordinary profile candidates = %v", got) + } +} + func TestStartPacerWaitHonorsCancellation(t *testing.T) { pacer := newStartPacer(time.Hour) if err := pacer.wait(context.Background()); err != nil { @@ -376,6 +399,28 @@ func TestWrapHandshakeTimeoutAllowsFourFlightsBeforeFastRetry(t *testing.T) { } } +func TestTurnCandidateRotationIsLimitedToPostAllocateHandshakeFailures(t *testing.T) { + for _, err := range []error{ + errors.New("WRAP_AUTH_TIMEOUT: отдельный DTLS-канал не ответил вовремя"), + errors.New("DTLS хендшейк до VPS example.test:56000 не прошёл: timeout"), + } { + if !shouldRotateTurnCandidateAfterSessionError(err) { + t.Fatalf("expected TURN candidate rotation for %q", err) + } + } + + for _, err := range []error{ + nil, + errors.New("TURN Allocate: error 508 Insufficient Capacity"), + errors.New("401 Unauthorized"), + errors.New("use of closed network connection"), + } { + if shouldRotateTurnCandidateAfterSessionError(err) { + t.Fatalf("unexpected TURN candidate rotation for %v", err) + } + } +} + func TestConfigFirstStartGateBlocksEveryWorkerExceptTheConfigWorker(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/go_client/main.go b/go_client/main.go index 76bcfba..0052dd9 100644 --- a/go_client/main.go +++ b/go_client/main.go @@ -355,7 +355,7 @@ func main() { hashFallback := flag.Bool( "hash-fallback", false, - "использовать остальные VK-хеши как резерв единственной группы", + "использовать остальные VK-хеши как резерв групп", ) deviceID := flag.String("device-id", "unknown", "уникальный ID устройства") @@ -515,7 +515,7 @@ func main() { } *numW = (*numW / workersPerGroup) * workersPerGroup useConfigFirstStart := *configFirstStart - useHashFallback := *hashFallback && *numW == workersPerGroup + useHashFallback := *hashFallback var masqueManager *warpMasqueManager if *turnStreamFirst && *rtMasque { diff --git a/go_client/session.go b/go_client/session.go index 1630d5f..c7b20cc 100644 --- a/go_client/session.go +++ b/go_client/session.go @@ -387,6 +387,7 @@ func RunSession( deviceID, password, deviceInfo, transportSession string, stats *Stats, preferTURNStream bool, + turnCandidateRetry int, onTURNAllocated func(), ) (bool, error) { configDelivered := false @@ -394,9 +395,10 @@ func RunSession( if len(creds.TurnURLs) == 0 { return false, fmt.Errorf("нет TURN URL в учетных данных") } - candidates := sessionTURNCandidatesWithPreference( + candidates := sessionTURNCandidatesForAttempt( creds.TurnURLs, sessionID, + turnCandidateRetry, tp, preferTURNStream, ) diff --git a/go_client/turn_endpoint.go b/go_client/turn_endpoint.go index 727291a..928966b 100644 --- a/go_client/turn_endpoint.go +++ b/go_client/turn_endpoint.go @@ -160,11 +160,27 @@ func sessionTURNCandidatesWithPreference( sessionID int, tp *TurnParams, preferStream bool, +) []turnEndpoint { + return sessionTURNCandidatesForAttempt(rawURLs, sessionID, 0, tp, preferStream) +} + +// sessionTURNCandidatesForAttempt rotates only the first TURN candidate after +// a relay accepted Allocate but did not carry the following DTLS handshake. +// The initial attempt keeps the historical endpoint order unchanged. +func sessionTURNCandidatesForAttempt( + rawURLs []string, + sessionID int, + retryOffset int, + tp *TurnParams, + preferStream bool, ) []turnEndpoint { if len(rawURLs) == 0 { return nil } - selectedIndex := sessionID % len(rawURLs) + if retryOffset < 0 { + retryOffset = 0 + } + selectedIndex := (sessionID + retryOffset) % len(rawURLs) if selectedIndex < 0 { selectedIndex = 0 } diff --git a/go_client/turn_endpoint_test.go b/go_client/turn_endpoint_test.go index 863a3e6..5d2f2f1 100644 --- a/go_client/turn_endpoint_test.go +++ b/go_client/turn_endpoint_test.go @@ -122,3 +122,25 @@ func TestSessionTURNCandidatesApplyOverride(t *testing.T) { } } } + +func TestSessionTURNCandidatesRotateAfterRelayHandshakeTimeout(t *testing.T) { + raw := []string{ + "turn:one.example:3478?transport=udp", + "turn:two.example:3478?transport=udp", + "turn:three.example:3478?transport=udp", + } + + initial := sessionTURNCandidatesForAttempt(raw, 1, 0, nil, false) + retry := sessionTURNCandidatesForAttempt(raw, 1, 1, nil, false) + wrapped := sessionTURNCandidatesForAttempt(raw, 1, len(raw), nil, false) + + if initial[0].Host != "two.example" { + t.Fatalf("initial candidate changed: %#v", initial) + } + if retry[0].Host != "three.example" { + t.Fatalf("retry did not rotate candidate: %#v", retry) + } + if wrapped[0].Host != initial[0].Host { + t.Fatalf("candidate rotation did not wrap: initial=%#v wrapped=%#v", initial, wrapped) + } +} diff --git a/server-installer/README.md b/server-installer/README.md index 670e5d3..f747ea2 100644 --- a/server-installer/README.md +++ b/server-installer/README.md @@ -4,8 +4,8 @@ из Linux-терминала, без передачи SSH-логина, root-пароля или приватного ключа Android-приложению. -Текущая версия автономного установщика — `0.19.0`. Она совместима только с -`wdtt-server` версии `16` и контрактом Android-деплоя `1`. Номера версий у +Текущая версия автономного установщика — `0.19.1`. Она совместима только с +`wdtt-server` версии `17` и контрактом Android-деплоя `1`. Номера версий у скрипта и сервера разные по замыслу: важна именно эта совместимая комбинация. ```bash @@ -23,7 +23,7 @@ VK-хеш. Для установки нужен совместимый комплект: - `install.sh`; -- исполняемый бинарник `wdtt-server` версии `16` для Linux `amd64` +- исполняемый бинарник `wdtt-server` версии `17` для Linux `amd64` (`x86_64`); - `SHA256SUMS` для проверки скрипта и бинарника. @@ -41,8 +41,8 @@ VK-хеш. На странице выпуска WDTT Plus в разделе **Assets**, рядом с APK, публикуются: ```text -WDTT-Plus-server-v16-installer-0.19.0-linux-amd64.tar.gz -WDTT-Plus-server-v16-installer-0.19.0-linux-amd64.tar.gz.sha256 +WDTT-Plus-server-v17-installer-0.19.1-linux-amd64.tar.gz +WDTT-Plus-server-v17-installer-0.19.1-linux-amd64.tar.gz.sha256 ``` При канонической предрелизной подготовке эти файлы создаются вместе с четырьмя @@ -57,9 +57,9 @@ app/build/outputs/release-ready/ архив: ```bash -sha256sum -c WDTT-Plus-server-v16-installer-0.19.0-linux-amd64.tar.gz.sha256 -tar -xzf WDTT-Plus-server-v16-installer-0.19.0-linux-amd64.tar.gz -cd WDTT-Plus-server-v16-installer-0.19.0-linux-amd64 +sha256sum -c WDTT-Plus-server-v17-installer-0.19.1-linux-amd64.tar.gz.sha256 +tar -xzf WDTT-Plus-server-v17-installer-0.19.1-linux-amd64.tar.gz +cd WDTT-Plus-server-v17-installer-0.19.1-linux-amd64 ``` После распаковки внутри находятся три согласованных файла: @@ -70,7 +70,7 @@ wdtt-server SHA256SUMS ``` -Это статический Linux `amd64`-файл `wdtt-server` версии `16`; внешние +Это статический Linux `amd64`-файл `wdtt-server` версии `17`; внешние динамические библиотеки ему не нужны. Проверьте внутренние файлы и их версии: ```bash @@ -80,7 +80,7 @@ bash install.sh --version ``` Проверка должна сообщить `install.sh: OK`, `wdtt-server: OK`, версию -установщика `0.19.0` и версию сервера `16`. +установщика `0.19.1` и версию сервера `17`. Готовые бинарник и контрольные суммы публикуются как файлы конкретного выпуска, но не хранятся в истории Git. Так пользователь получает проверенный @@ -375,7 +375,7 @@ VPS. Пока сервер принадлежит ручному установ ### Резервные копии после ручной установки -Совместимый `wdtt-server` v16 поддерживает тот же менеджер резервных копий и +Совместимый `wdtt-server` v17 поддерживает тот же менеджер резервных копий и после установки через этот скрипт. Управление находится в Android-приложении: **«Деплой» → «Резервные копии и перенос»**. Для административных действий нужны SSH-доступ к VPS и главный пароль WDTT; обычное VPN-подключение по-прежнему @@ -711,14 +711,12 @@ git diff --check -- server-installer/install.sh server-installer/README.md - повторно собирает `wdtt-server` из текущих корневых Go-исходников; - требует побайтового совпадения исходной сборки, `assets/server`, standalone- бинарника и `assets/server` во всех четырёх APK; -- создаёт детерминированный серверный архив и его внешний `.sha256`, а также - отдельный проверяемый архив самостоятельного WARP-менеджера; +- создаёт детерминированный серверный архив и его внешний `.sha256`; - распаковывает архив в безопасный временный каталог и проверяет точный состав, права, версии и внутренний `SHA256SUMS`; - очищает старый набор, а затем атомарно создаёт - `app/build/outputs/release-ready/` ровно с семью файлами выпуска: четырьмя - APK, серверным архивом, его внешней контрольной суммой и отдельным архивом - WARP-менеджера. + `app/build/outputs/release-ready/` ровно с шестью файлами выпуска: четырьмя + APK, серверным архивом и его внешней контрольной суммой. Если сборка, аудит или любая сверка завершается ошибкой, нового `release-ready` не появляется. Поэтому прежний набор нельзя случайно принять @@ -729,7 +727,7 @@ git diff --check -- server-installer/install.sh server-installer/README.md ./gradlew :app:verifyGithubReleaseArtifacts ``` -На GitHub нужно загружать только семь файлов из `release-ready`, не смешивая +На GitHub нужно загружать только шесть файлов из `release-ready`, не смешивая их с результатами прежних сборок или файлами непосредственно из `app/build/outputs/apk/release/named/`. @@ -837,6 +835,8 @@ SSH нужен только для ручной установки, админи ## Версии ручного установщика +- `0.19.1` — добавлена совместимость с `wdtt-server` v17; данные, ключи и + резервные копии при обновлении сохраняются по прежним правилам. - `0.19.0` — добавлена двусторонняя безопасная передача владения: `handoff-android` проверяет ручную службу, создаёт полную транзакционную копию, сохраняет данные, ключи и пользовательские снимки, устанавливает diff --git a/server-installer/compatibility-contract.env b/server-installer/compatibility-contract.env index 947cbd4..1b7c71c 100644 --- a/server-installer/compatibility-contract.env +++ b/server-installer/compatibility-contract.env @@ -1,7 +1,7 @@ # Canonical compatibility contract for Android deploy and standalone installer. # Changing any value requires updating both paths; the build guard enforces it. WDTT_DEPLOY_CONTRACT_VERSION="1" -WDTT_SERVER_VERSION="16" +WDTT_SERVER_VERSION="17" WDTT_SERVER_BINARY_PATH="/usr/local/bin/wdtt-server" WDTT_SYSTEMD_UNIT_PATH="/etc/systemd/system/wdtt.service" WDTT_CONFIG_DIRECTORY="/etc/wdtt" diff --git a/server-installer/install.sh b/server-installer/install.sh index 7cb4ca9..87e28f7 100755 --- a/server-installer/install.sh +++ b/server-installer/install.sh @@ -23,8 +23,8 @@ ensure_utf8_locale() { ensure_utf8_locale -readonly INSTALLER_VERSION="0.19.0" -readonly SUPPORTED_SERVER_VERSION="16" +readonly INSTALLER_VERSION="0.19.1" +readonly SUPPORTED_SERVER_VERSION="17" readonly DEPLOY_COMPATIBILITY_VERSION="1" readonly MANAGED_MARKER="Managed by WDTT Plus standalone server installer" readonly ANDROID_DEPLOY_MARKER="Managed by WDTT Plus Android deploy" diff --git a/server-installer/release_bundle.sh b/server-installer/release_bundle.sh index aa44e5d..42c9bf5 100755 --- a/server-installer/release_bundle.sh +++ b/server-installer/release_bundle.sh @@ -11,9 +11,6 @@ readonly CONTRACT="$SCRIPT_DIR/compatibility-contract.env" readonly LOCAL_SERVER="$SCRIPT_DIR/wdtt-server" readonly LOCAL_SUMS="$SCRIPT_DIR/SHA256SUMS" readonly SERVER_ASSET="$REPOSITORY_ROOT/app/src/main/assets/server" -readonly WARP_DIR="$REPOSITORY_ROOT/warp-interface-manager" -readonly WARP_SCRIPT="$WARP_DIR/warp-interface-manager.sh" -readonly WARP_README="$WARP_DIR/README.md" readonly APK_DIR="$REPOSITORY_ROOT/app/build/outputs/apk/release/named" readonly OUTPUTS_ROOT="$REPOSITORY_ROOT/app/build/outputs" readonly READY_DIR="$OUTPUTS_ROOT/release-ready" @@ -103,15 +100,6 @@ validate_versions() { BUNDLE_NAME="WDTT-Plus-server-v${WDTT_SERVER_VERSION}-installer-${INSTALLER_VERSION}-linux-amd64" ARCHIVE_NAME="$BUNDLE_NAME.tar.gz" ARCHIVE_SUM_NAME="$ARCHIVE_NAME.sha256" - require_regular_file "$WARP_SCRIPT" - require_regular_file "$WARP_README" - WARP_VERSION="$(sed -n 's/^VERSION="\([0-9][0-9.]*\)"$/\1/p' "$WARP_SCRIPT")" - [[ "$WARP_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || - die "не удалось однозначно прочитать версию WARP-менеджера" - grep -Fqx "Документация соответствует версии скрипта \`$WARP_VERSION\`." "$WARP_README" || - die "README WARP-менеджера не соответствует версии $WARP_VERSION" - WARP_BUNDLE_NAME="warp-interface-manager-v${WARP_VERSION}" - WARP_ARCHIVE_NAME="$WARP_BUNDLE_NAME.tar.gz" } validate_linux_server() { @@ -162,8 +150,7 @@ expected_release_files() { "WDTT-Plus-v${APP_VERSION}-universal-release.apk" \ "WDTT-Plus-v${APP_VERSION}-x86_64-release.apk" \ "$ARCHIVE_NAME" \ - "$ARCHIVE_SUM_NAME" \ - "$WARP_ARCHIVE_NAME" | + "$ARCHIVE_SUM_NAME" | LC_ALL=C sort } @@ -231,47 +218,6 @@ verify_archive() { validate_linux_server "$extracted/wdtt-server" } -verify_warp_archive() { - local release_dir="$1" - local archive="$release_dir/$WARP_ARCHIVE_NAME" - local members expected_members extract_root extracted - require_regular_file "$archive" - members="$(tar -tzf "$archive")" - expected_members="$(printf '%s\n' \ - "$WARP_BUNDLE_NAME/" \ - "$WARP_BUNDLE_NAME/README.md" \ - "$WARP_BUNDLE_NAME/SHA256SUMS" \ - "$WARP_BUNDLE_NAME/warp-interface-manager.sh")" - [[ "$members" == "$expected_members" ]] || - die "архив WARP-менеджера содержит неожиданные пути или неполный комплект" - - extract_root="$TEMP_ROOT/warp-extracted" - install -d -m 0700 "$extract_root" - tar --no-same-owner --same-permissions -xzf "$archive" -C "$extract_root" - extracted="$extract_root/$WARP_BUNDLE_NAME" - [[ -d "$extracted" && ! -L "$extracted" ]] || - die "архив WARP-менеджера не создал ожидаемый каталог" - require_regular_file "$extracted/README.md" - require_regular_file "$extracted/SHA256SUMS" - require_regular_file "$extracted/warp-interface-manager.sh" - [[ "$(stat -c '%a' "$extracted/README.md")" == "644" ]] || - die "у README.md в WARP-архиве должны быть права 644" - [[ "$(stat -c '%a' "$extracted/SHA256SUMS")" == "644" ]] || - die "у SHA256SUMS в WARP-архиве должны быть права 644" - [[ "$(stat -c '%a' "$extracted/warp-interface-manager.sh")" == "755" ]] || - die "у WARP-скрипта в архиве должны быть права 755" - cmp -s "$WARP_README" "$extracted/README.md" || - die "в WARP-архив попал другой README.md" - cmp -s "$WARP_SCRIPT" "$extracted/warp-interface-manager.sh" || - die "в WARP-архив попал другой скрипт" - ( - cd "$extracted" - sha256sum -c SHA256SUMS >/dev/null - ) || die "внутренние суммы WARP-архива не совпали" - [[ "$("$extracted/warp-interface-manager.sh" --version | awk '{ print $NF }')" == "$WARP_VERSION" ]] || - die "версия WARP-скрипта изменилась внутри архива" -} - verify_apks() { local release_dir="$1" abi apk extracted_server for abi in arm64-v8a armeabi-v7a x86_64 universal; do @@ -298,7 +244,6 @@ verify_release_set() { verify_source_and_local_files verify_exact_release_file_set "$release_dir" verify_archive "$release_dir" - verify_warp_archive "$release_dir" verify_apks "$release_dir" } @@ -348,38 +293,6 @@ create_archive() { chmod 0644 "$release_stage/$ARCHIVE_NAME" "$release_stage/$ARCHIVE_SUM_NAME" } -create_warp_archive() { - local release_stage="$1" - local content_root="$TEMP_ROOT/warp-content" - local bundle_dir="$content_root/$WARP_BUNDLE_NAME" - local archive_pending="$release_stage/$WARP_ARCHIVE_NAME.new" - local epoch - epoch="${SOURCE_DATE_EPOCH:-$(git -C "$REPOSITORY_ROOT" log -1 --format=%ct)}" - [[ "$epoch" =~ ^[0-9]+$ ]] || die "SOURCE_DATE_EPOCH должен быть Unix-временем" - install -d -m 0755 "$bundle_dir" - install -m 0644 "$WARP_README" "$bundle_dir/README.md" - install -m 0755 "$WARP_SCRIPT" "$bundle_dir/warp-interface-manager.sh" - ( - cd "$bundle_dir" - sha256sum README.md warp-interface-manager.sh >SHA256SUMS - ) - chmod 0644 "$bundle_dir/SHA256SUMS" - ( - cd "$content_root" - LC_ALL=C tar \ - --sort=name \ - --mtime="@$epoch" \ - --owner=0 \ - --group=0 \ - --numeric-owner \ - --format=posix \ - --pax-option=delete=atime,delete=ctime \ - -cf - "$WARP_BUNDLE_NAME" | gzip -n >"$archive_pending" - ) - mv -f "$archive_pending" "$release_stage/$WARP_ARCHIVE_NAME" - chmod 0644 "$release_stage/$WARP_ARCHIVE_NAME" -} - copy_release_apks() { local release_stage="$1" abi source target for abi in arm64-v8a armeabi-v7a x86_64 universal; do @@ -434,7 +347,6 @@ prepare_release() { die "временный каталог уже существует" install -d -m 0755 "$release_stage" create_archive "$release_stage" - create_warp_archive "$release_stage" copy_release_apks "$release_stage" verify_release_set "$release_stage" replace_ready_directory "$release_stage" diff --git a/server-installer/tests/compatibility_test.sh b/server-installer/tests/compatibility_test.sh index cad4e2e..a65c34e 100644 --- a/server-installer/tests/compatibility_test.sh +++ b/server-installer/tests/compatibility_test.sh @@ -147,12 +147,14 @@ require_text "$ANDROID_BUILD" 'mustRunAfter(invalidateGithubReleaseArtifacts)' reject_text "$DEPLOY_TAB" 'context.assets.open("server-installer.sh")' reject_text "$DEPLOY_TAB" 'ssh.upload(installerFile, "/tmp/wdtt-server-installer.sh"' reject_text "$DEPLOY_TAB" '"bash /tmp/wdtt-server-installer.sh install "' -require_text "$DEPLOY_TAB" 'DeploymentOwnership.StandaloneInstaller -> throw IllegalStateException(' +require_text "$DEPLOY_TAB" 'ownership == DeploymentOwnership.StandaloneInstaller -> throw IllegalStateException(' require_text "$DEPLOY_TAB" 'Android-приложение не обновляет' require_text "$DEPLOY_TAB" 'используйте server-installer/install.sh на VPS' require_text "$DEPLOY_TAB" 'assertAndroidDeployMayManageServer(ssh, "удаления")' require_text "$DEPLOY_TAB" 'enabled = resetAllowed' -require_text "$DEPLOY_TAB" 'checkSucceeded && ownership == DeploymentOwnership.AndroidDeploy' +require_text "$DEPLOY_TAB" 'checkSucceeded && ownership in setOf(' +require_text "$DEPLOY_TAB" 'DeploymentOwnership.IncompleteAndroidDeploy' +require_text "$DEPLOY_TAB" 'incompleteAndroidDeployCandidate' probe_source="$( sed -n \ diff --git a/server-installer/tests/install_test.sh b/server-installer/tests/install_test.sh index 96c3b9d..41adc06 100755 --- a/server-installer/tests/install_test.sh +++ b/server-installer/tests/install_test.sh @@ -38,7 +38,7 @@ new_sandbox() { make_fake_binary() { local target="$1" local build_id="$2" - local reported_version="${3:-16}" + local reported_version="${3:-17}" cat >"$target" <"$output" - [[ "$("$INSTALLER" --version)" == "0.19.0" ]] || + [[ "$("$INSTALLER" --version)" == "0.19.1" ]] || fail "команда --version вернула неожиданный результат" ! grep -Fq "install.sh start" "$output" || fail "справка показывает alias start как отдельный основной сценарий" @@ -330,7 +330,7 @@ test_wizard_on_android_deploy_is_guidance_not_failure() { tr -d '\r' <"$output" >"$clean" grep -Fq "На сервере уже обнаружен совместимый Android-деплой." "$clean" || fail "мастер не объяснил найденный Android-деплой" - grep -Fq "✓ Совместимость подтверждена: контракт 1, wdtt-server 16." "$clean" || + grep -Fq "✓ Совместимость подтверждена: контракт 1, wdtt-server 17." "$clean" || fail "мастер не показал краткую совместимость" grep -Fq "Сейчас изменений на сервере не выполнено." "$clean" || fail "мастер не подтвердил отсутствие изменений" @@ -1223,7 +1223,9 @@ test_parallel_installer_is_rejected() { exec 8>"$lock_path" flock -x 8 printf 'locked\n' >"$lock_ready" - sleep 2 + # Keep the lock long enough for slow/loaded CI hosts to reach the + # competing invocation without turning this into a timing race. + sleep 10 ) & locker=$! for ((attempt = 0; attempt < 100; attempt++)); do @@ -1598,20 +1600,20 @@ test_installer_version_difference_triggers_update() { run_installer "$root" install --binary "$binary" --yes >"$output" - grep -Fq "установщик: 0.19.0" "$output" || + grep -Fq "установщик: 0.19.1" "$output" || fail "план не показал версию запущенного установщика" grep -Fq "установлен: 0.2.0" "$output" || fail "план не показал прежнюю установленную версию" - grep -Fxq "installer_version=0.19.0" "$ownership" || + grep -Fxq "installer_version=0.19.1" "$ownership" || fail "повтор не обновил версию в метке владения" find "$root/var/lib/wdtt-server-installer/backups" -mindepth 1 -maxdepth 1 \ -type d | grep -q . || fail "различие версий ошибочно обработано как no-op" run_installer "$root" status >"$output" - grep -Fq "Версия этого установщика: 0.19.0" "$output" || + grep -Fq "Версия этого установщика: 0.19.1" "$output" || fail "status не показывает версию файла" - grep -Fq "Установлено версией: 0.19.0" "$output" || + grep -Fq "Установлено версией: 0.19.1" "$output" || fail "status не показывает установленную версию" grep -Fq "Версии установщика: совпадают" "$output" || fail "status не сравнивает версии" @@ -1631,7 +1633,7 @@ test_rejects_incompatible_server_version() { make_config "$config" "SafeOwnerPassword42" expect_failure "$output" run_installer "$root" check --binary "$binary" --config "$config" - grep -Fq "Поддерживается wdtt-server версии 16" "$output" || + grep -Fq "Поддерживается wdtt-server версии 17" "$output" || fail "несовместимая версия сервера отклонена без понятной ошибки" pass "несовместимая версия wdtt-server отклоняется" } diff --git a/server.go b/server.go index ac57249..0aebbde 100644 --- a/server.go +++ b/server.go @@ -43,7 +43,7 @@ import ( ) const ( - wdttServerVersion = "16" + wdttServerVersion = "17" wgIfaceName = "wdtt0" wgServerAddr = "10.66.66.1" wgServerCIDR = wgServerAddr + "/24" @@ -701,6 +701,19 @@ func initDB(dir, mainPass, adminID, botToken, dnsValue string) error { return nil } +// botRuntimeCredentials returns the values persisted in the protected database. +// Deploy updates intentionally do not put these values back into systemd or the +// process command line, so every restart must use the database as the runtime +// source of truth. +func botRuntimeCredentials() (string, string) { + dbMutex.Lock() + defer dbMutex.Unlock() + if db == nil { + return "", "" + } + return strings.TrimSpace(db.BotToken), strings.TrimSpace(db.AdminID) +} + func saveDB() error { if err := persistDatabaseFile(dbFile, db); err != nil { log.Printf("[DB] сохранение отклонено: %v", err) @@ -1624,7 +1637,8 @@ func main() { go statsLoop(ctx, *configDir) go systemMetricsLoop(ctx) go expiredPasswordJanitor(ctx, wgDev) - go botLoop(*botToken, *adminID, wgDev) + storedBotToken, storedAdminID := botRuntimeCredentials() + go botLoop(storedBotToken, storedAdminID, wgDev) addr, _ := net.ResolveUDPAddr("udp", *listen) cert, _ := selfsign.GenerateSelfSigned()