diff --git a/CHANGELOG.md b/CHANGELOG.md index 4940ed0..04f225b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,34 @@ Здесь фиксируются заметные пользовательские изменения WDTT Plus. +## v14 — 03.08.2026 + +### Сеть РТ и MASQUE + +- Добавлен отдельный режим «Сеть РТ» для мобильной сети Ростелекома с белыми списками. Он сначала пробует TURN/TLS с настраиваемым SNI, затем TURN/TCP ко всем адресам VK с разделением первого STUN-запроса и оставляет UDP последним резервом. Режим выключен по умолчанию и не меняет обычные подключения других операторов и Wi-Fi. +- Внутри «Сети РТ» доступен экспериментальный резерв MASQUE: WARP CONNECT-IP проверяется сначала по HTTP/2 через TCP/443, затем по HTTP/3 через QUIC/443. Регистрация WARP хранится в приватном каталоге приложения и повторно используется после перезапуска и выключения рубильников. +- Если прямой TLS к API Cloudflare недоступен, первую регистрацию WARP можно провести через SSH-сервер, указанный в разделе «Деплой». На сервер ничего не устанавливается, а обычный трафик WDTT, TURN и MASQUE через него не направляется; вероятнее всего, для этого нужен сервер за пределами РФ. +- Параметры SNI, MASQUE и регистрации через сервер перенесены в отдельное окно. Добавлены подробные инструкции, согласие с условиями Cloudflare, безопасный сброс сохранённой регистрации и поэтапные русские сообщения диагностики. + +### VPN и энергопотребление + +- В боковых настройках появилась необязательная «Экономия батареи во сне»: при выключенном экране VPN и системный VPN-интерфейс безопасно останавливаются, интернет идёт напрямую, а после пробуждения прежнее подключение обычно восстанавливается автоматически. +- Обычный режим стал устойчивее после сна и смены мобильной сети или Wi-Fi: краткая потеря статистики больше не вызывает преждевременное пересоздание VPN, а действительно пропавший системный интерфейс восстанавливается только после подтверждения на рабочей сети. +- Счётчики трафика текущей сессии больше не обнуляются в журнале после внутреннего перезапуска транспорта. +- Ожидание доверенной Wi-Fi теперь учитывает ещё не завершившийся запуск VPN и не позволяет службе преждевременно остановиться во время перехода. + +### Диагностика и интерфейс + +- Проверка устройства определяет оператора именно выбранной Android data-SIM. Если сеть или SIM меняется во время проверки, устаревшие результаты отбрасываются, а диагностика автоматически повторяется на новой сети. +- Отчёт поддержки дополнен состоянием «Сети РТ», MASQUE и локальной регистрации WARP; дублирующиеся сведения о сети убраны. +- Блок настроек туннеля стал компактнее: уменьшена высота «Мощности», «Быстрого VKCalls», «Авто капчи» и «Сети РТ». + +### Совместимость + +- Обновлены Android- и Go-компоненты WireGuard, а также сетевые зависимости нативного клиента. +- 64-битные нативные библиотеки собираются и проверяются с выравниванием для страниц памяти 16 КиБ. Это исправляет запуск на новых устройствах Android с таким размером страницы без повышения минимальной версии Android. +- При обновлении приложения до версии 14 вкладка «Деплой» напоминает обновить отличающуюся серверную часть с сохранением данных. + ## v13 — 30.07.2026 ### Сервер diff --git a/app/build.gradle.kts b/app/build.gradle.kts index d02ee57..cd03da0 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -46,7 +46,7 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") } -val appVersionName = "13" +val appVersionName = "14" val releaseApkBaseName = "WDTT-Plus" val localProperties = Properties() @@ -90,9 +90,9 @@ android { applicationId = "com.wdtt.plus" minSdk = 28 targetSdk = 35 - versionCode = 13 + versionCode = 14 versionName = appVersionName - buildConfigField("String", "MOD_RELEASE_DATE", "\"30.07.2026\"") + buildConfigField("String", "MOD_RELEASE_DATE", "\"03.08.2026\"") buildConfigField("String", "WDTT_PLUS_DOMAIN", buildConfigString(wdttPlusDomain)) manifestPlaceholders["wdttPlusDomain"] = wdttPlusDomain manifestPlaceholders["appLabel"] = "WDTT Plus" @@ -249,11 +249,15 @@ tasks.register("buildNativeClient") { mkdir -p "${'$'}jni_dir/${'$'}abi" if [ -n "${'$'}goarm" ]; then env GOOS=android GOARCH="${'$'}goarch" GOARM="${'$'}goarm" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \ - go build -buildvcs=false -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \ + go build -buildvcs=false -trimpath \ + -ldflags="-s -w -checklinkname=0 -linkmode=external -extldflags=-Wl,-z,max-page-size=16384" \ + -buildmode=pie \ -o "${'$'}jni_dir/${'$'}abi/libclient.so" . else env GOOS=android GOARCH="${'$'}goarch" CGO_ENABLED=1 CC="${'$'}ndk_bin/${'$'}cc" \ - go build -buildvcs=false -trimpath -ldflags="-s -w -checklinkname=0" -buildmode=pie \ + go build -buildvcs=false -trimpath \ + -ldflags="-s -w -checklinkname=0 -linkmode=external -extldflags=-Wl,-z,max-page-size=16384" \ + -buildmode=pie \ -o "${'$'}jni_dir/${'$'}abi/libclient.so" . fi } @@ -269,6 +273,62 @@ tasks.register("buildNativeClient") { ) } +val verify16KbNativeLibraries = tasks.register("verify16KbNativeLibraries") { + group = "verification" + description = "Verifies 16 KiB LOAD alignment for every 64-bit Android native library." + dependsOn("mergeReleaseNativeLibs") + + val mergedNativeLibs = layout.buildDirectory.dir( + "intermediates/merged_native_libs/release/mergeReleaseNativeLibs/out/lib" + ) + inputs.dir(mergedNativeLibs) + + commandLine( + "bash", + "-lc", + """ + set -euo pipefail + lib_root="${'$'}1" + sdk_dir="${'$'}2" + readelf_bin="$(command -v readelf || true)" + if [ -z "${'$'}readelf_bin" ] && [ -n "${'$'}sdk_dir" ]; then + readelf_bin="$(ls -d "${'$'}sdk_dir"/ndk/*/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf 2>/dev/null | sort -V | tail -n 1)" + fi + if [ -z "${'$'}readelf_bin" ] || [ ! -x "${'$'}readelf_bin" ]; then + echo "readelf is required to verify Android native page alignment." >&2 + exit 1 + fi + found=0 + for abi in arm64-v8a x86_64; do + abi_dir="${'$'}lib_root/${'$'}abi" + [ -d "${'$'}abi_dir" ] || continue + while IFS= read -r -d '' library; do + found=1 + while IFS= read -r alignment; do + value=${'$'}((alignment)) + if [ "${'$'}value" -lt 16384 ]; then + echo "Native library is not compatible with 16 KiB pages: ${'$'}library (LOAD align=${'$'}alignment)" >&2 + exit 1 + fi + done < <("${'$'}readelf_bin" -lW "${'$'}library" | awk '${'$'}1 == "LOAD" { print ${'$'}NF }') + done < <(find "${'$'}abi_dir" -type f -name '*.so' -print0) + done + if [ "${'$'}found" -ne 1 ]; then + echo "No 64-bit Android native libraries found under ${'$'}lib_root." >&2 + exit 1 + fi + echo "All 64-bit Android native libraries use 16 KiB-compatible LOAD alignment." + """.trimIndent(), + "bash", + mergedNativeLibs.get().asFile.absolutePath, + androidSdkDir.orEmpty(), + ) +} + +tasks.matching { it.name == "packageRelease" }.configureEach { + dependsOn(verify16KbNativeLibraries) +} + tasks.matching { it.name.startsWith("merge") && (it.name.endsWith("NativeLibs") || it.name.endsWith("JniLibFolders")) @@ -389,7 +449,7 @@ dependencies { implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7") implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7") implementation("androidx.datastore:datastore-preferences:1.1.1") - implementation("com.wireguard.android:tunnel:1.0.20230706") + implementation("com.wireguard.android:tunnel:1.0.20260102") implementation("com.github.mwiede:jsch:0.2.16") implementation("org.bouncycastle:bcprov-jdk18on:1.79") implementation("com.journeyapps:zxing-android-embedded:4.3.0") diff --git a/app/src/main/assets/masque-third-party-notice.txt b/app/src/main/assets/masque-third-party-notice.txt new file mode 100644 index 0000000..1ab0793 --- /dev/null +++ b/app/src/main/assets/masque-third-party-notice.txt @@ -0,0 +1,25 @@ +Cloudflare WARP MASQUE interoperability code is adapted from +https://github.com/Diniboy1123/usque +commit 6aa03fc97d12848dce34eedbd187fb1077b5d1ea. + +The MIT License (MIT) + +Copyright © 2025, github.com/Diniboy1123 + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the “Software”), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt index 753f9ea..b6294db 100644 --- a/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycle.kt @@ -98,6 +98,10 @@ data class AccessLifecycleStatus( val detailLabel: String = "", val detailValue: String = "", val actionIcon: String = "", + val continuationAvailable: Boolean? = null, + val continuationExpiresAtSeconds: Long? = null, + val dismissible: Boolean? = null, + val dismissedMessage: String = "", val severity: AccessLifecycleSeverity = AccessLifecycleSeverity.NORMAL, val checkedAtMillis: Long = System.currentTimeMillis(), val profileRevision: Long = 0, @@ -125,6 +129,10 @@ data class AccessLifecycleUiState( val detailLabel: String = "", val detailValue: String = "", val actionIcon: String = "", + val continuationAvailable: Boolean? = null, + val continuationExpiresAtSeconds: Long? = null, + val dismissible: Boolean? = null, + val dismissedMessage: String = "", val severity: AccessLifecycleSeverity, val checkedAtMillis: Long, ) { @@ -140,6 +148,10 @@ data class AccessLifecycleUiState( detailLabel = "", detailValue = "", actionIcon = "", + continuationAvailable = null, + continuationExpiresAtSeconds = null, + dismissible = null, + dismissedMessage = "", severity = AccessLifecycleSeverity.NORMAL, checkedAtMillis = 0, ) @@ -157,9 +169,29 @@ internal fun accessLifecycleDismissalSignature( lifecycle.message, lifecycle.detailLabel, lifecycle.detailValue, + lifecycle.continuationAvailable, + lifecycle.continuationExpiresAtSeconds, + lifecycle.dismissible, + lifecycle.dismissedMessage, ).joinToString("|") } +internal fun accessLifecycleCanDismiss(lifecycle: AccessLifecycleUiState): Boolean = + lifecycle.dismissible ?: ( + lifecycle.allowConnect && lifecycle.severity == AccessLifecycleSeverity.WARNING + ) + +internal fun boundContinuationAvailable( + hasCredential: Boolean, + hasEndpoint: Boolean, + remoteAvailability: Boolean?, + expiresAtSeconds: Long? = null, + nowSeconds: Long = System.currentTimeMillis() / 1_000L, +): Boolean = hasCredential && + hasEndpoint && + remoteAvailability != false && + (expiresAtSeconds == null || expiresAtSeconds == 0L || expiresAtSeconds > nowSeconds) + internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState { val current = status return AccessLifecycleUiState( @@ -173,6 +205,10 @@ internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState { detailLabel = current?.detailLabel.orEmpty(), detailValue = current?.detailValue.orEmpty(), actionIcon = current?.actionIcon.orEmpty(), + continuationAvailable = current?.continuationAvailable, + continuationExpiresAtSeconds = current?.continuationExpiresAtSeconds, + dismissible = current?.dismissible, + dismissedMessage = current?.dismissedMessage.orEmpty(), severity = current?.severity ?: AccessLifecycleSeverity.NORMAL, checkedAtMillis = current?.checkedAtMillis ?: 0, ) diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt index 0f11b62..49253fd 100644 --- a/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycleCoordinator.kt @@ -3,12 +3,14 @@ package com.wdtt.plus import android.content.Context import android.os.Build import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext import java.util.TimeZone sealed interface AccessLifecycleRefreshResult { @@ -35,6 +37,14 @@ object AccessLifecycleCoordinator { context: Context, profileIndex: Int, force: Boolean = false, + ): AccessLifecycleRefreshResult = withContext(Dispatchers.IO) { + refreshProfileOnWorker(context, profileIndex, force) + } + + private suspend fun refreshProfileOnWorker( + context: Context, + profileIndex: Int, + force: Boolean = false, ): AccessLifecycleRefreshResult { val appContext = context.applicationContext val profile = profileIndex.coerceIn(0, 2) @@ -60,7 +70,9 @@ object AccessLifecycleCoordinator { val current = store.accessLifecycleForProfile(profile) val currentNow = System.currentTimeMillis() if (!current.capability.available) return@withLock AccessLifecycleRefreshResult.Unmanaged - syncPendingProfileValues(store, profile, current.capability) + if (current.status?.continuationAvailable != false) { + syncPendingProfileValues(store, profile, current.capability) + } if ( !force && current.status != null && @@ -104,6 +116,20 @@ object AccessLifecycleCoordinator { ) { return@withLock AccessLifecycleRefreshResult.Unmanaged } + if (received.continuationAvailable != false) { + try { + syncPendingProfileValues(store, profile, effectiveCapability) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + TunnelManager.noteAccessLifecycleEvent( + key = "profile_${profile}_values_sync_failed", + message = error.message + ?: "Не удалось обновить сохранённые данные профиля", + warning = true, + ) + } + } val profileUpdated = applyProfileUpdateIfNeeded( appContext = appContext, store = store, @@ -478,22 +504,17 @@ object AccessLifecycleCoordinator { require(binding.isNotBlank() && delivery.binding == binding) { "Обновление относится к другому профилю." } - val applied = store.applyWdttDeepLink( + val applied = store.applyRemoteDocumentDelivery( plan = WdttDeepLinkApplyPlan( link = delivery.document, targetProfile = profile, requiresConfirmation = false, storeAsLink = false, ), - resetRemoteContinuation = false, - profileMaxWorkers = delivery.profileMaxWorkers, - remoteManaged = null, - preserveVkHashes = true, + delivery = delivery, + isBoundUpdate = true, ) require(applied != null) { "Не удалось применить обновление профиля." } - if (delivery.access.available) { - store.saveRemoteAccessCapability(delivery.access, profile) - } store.saveAppliedAccessProfileRevision(profile, update.revision) requestTunnelProfileRuntimeUpdate(profile) TunnelManager.noteAccessLifecycleEvent( diff --git a/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt b/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt index 2953e1d..bbb2545 100644 --- a/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt +++ b/app/src/main/java/com/wdtt/plus/AccessLifecycleGateway.kt @@ -246,6 +246,17 @@ object AccessLifecycleGateway { val actionIcon = action?.optString("icon").orEmpty().trim().take(32) .takeIf { it == "update" } .orEmpty() + val continuationAvailable = root.optJSONObject("continuation") + ?.takeIf { it.has("available") } + ?.optBoolean("available", false) + val continuationExpiresAtSeconds = root.optJSONObject("continuation") + ?.takeIf { it.has("expires") } + ?.optLong("expires", 0L) + ?.coerceAtLeast(0L) + val dismissible = root + .takeIf { it.has("dismissible") } + ?.optBoolean("dismissible", false) + val dismissedMessage = root.optString("dismissed_message").trim().take(400) val title = root.optString("title").trim().take(120) val message = root.optString("message").trim().take(400) val detail = root.optJSONObject("detail") @@ -281,6 +292,10 @@ object AccessLifecycleGateway { detailLabel = detailLabel, detailValue = detailValue, actionIcon = actionIcon, + continuationAvailable = continuationAvailable, + continuationExpiresAtSeconds = continuationExpiresAtSeconds, + dismissible = dismissible, + dismissedMessage = dismissedMessage, severity = severity, profileRevision = revision, profileUpdate = update, diff --git a/app/src/main/java/com/wdtt/plus/ClientNetworkDiagnostics.kt b/app/src/main/java/com/wdtt/plus/ClientNetworkDiagnostics.kt index 9494c44..ef580a5 100644 --- a/app/src/main/java/com/wdtt/plus/ClientNetworkDiagnostics.kt +++ b/app/src/main/java/com/wdtt/plus/ClientNetworkDiagnostics.kt @@ -9,6 +9,7 @@ import android.net.NetworkCapabilities import android.os.Build import android.os.CancellationSignal import android.os.SystemClock +import android.telephony.SubscriptionManager import android.telephony.TelephonyManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.CancellationException @@ -111,6 +112,12 @@ private val vkHttpsTargets = listOf( ) suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiagnosticsReport = + collectClientNetworkDiagnostics(context, retryOnNetworkChange = true) + +private suspend fun collectClientNetworkDiagnostics( + context: Context, + retryOnNetworkChange: Boolean +): ClientNetworkDiagnosticsReport = withContext(Dispatchers.IO) { val connectivityManager = context.getSystemService(ConnectivityManager::class.java) val diagnosticNetwork = connectivityManager?.let { selectDiagnosticNetwork(context, it) } @@ -138,6 +145,28 @@ suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiag Triple(systemDns.await(), clientDns.await(), vkHttps.await()) } + val networkAfterProbes = selectDiagnosticNetwork(context, connectivityManager) + if (networkAfterProbes?.network != diagnosticNetwork.network) { + if (retryOnNetworkChange && networkAfterProbes != null) { + val retried = collectClientNetworkDiagnostics( + context, + retryOnNetworkChange = false + ) + return@withContext retried.copy( + summaryLines = listOf( + "Сеть изменилась во время диагностики; проверки автоматически повторены на новой сети" + ) + retried.summaryLines, + items = listOf(networkChangeItem(retried = true)) + retried.items + ) + } + return@withContext ClientNetworkDiagnosticsReport( + summaryLines = listOf( + "Сеть изменилась во время диагностики; результаты устаревшей сети отброшены" + ), + items = listOf(networkChangeItem(retried = false)) + ) + } + val primaryDnsResults = dnsResults.filter { it.label in primaryVkDiagnosticHosts } val reserveDnsResults = dnsResults.filter { it.label in reserveVkDiagnosticHosts } val primaryDnsOk = primaryDnsResults.count { it.success } @@ -287,18 +316,45 @@ private fun selectDiagnosticNetwork(context: Context, connectivityManager: Conne private fun mobileOperatorSummary(context: Context, capabilities: NetworkCapabilities): String { if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return "не применяется" return runCatching { - val telephonyManager = context.getSystemService(TelephonyManager::class.java) - val network = telephonyManager?.networkOperatorName.orEmpty().trim() - val sim = telephonyManager?.simOperatorName.orEmpty().trim() - val names = listOf(network, sim).filter(String::isNotBlank).distinct() + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + return@runCatching "не определён для выбранной сети на этой версии Android" + } + val dataSubscriptionId = SubscriptionManager.getDefaultDataSubscriptionId() + if (dataSubscriptionId < 0) { + return@runCatching "не определён для выбранной data-SIM" + } + val baseManager = context.getSystemService(TelephonyManager::class.java) + val manager = baseManager?.createForSubscriptionId(dataSubscriptionId) + ?: return@runCatching "телефонная служба недоступна" + val names = listOf(manager.networkOperatorName, manager.simOperatorName) + .map(String::trim) + .filter(String::isNotBlank) + .distinct() buildString { append(names.joinToString(" / ").ifBlank { "не определён" }) append(", roaming=") - append(telephonyManager?.isNetworkRoaming ?: false) + append(manager.isNetworkRoaming) + append(", основная data-SIM") } }.getOrDefault("недоступен") } +private fun networkChangeItem(retried: Boolean): DeviceCheckItem = DeviceCheckItem( + title = "Смена сети во время диагностики", + status = if (retried) "проверки повторены" else "результаты отброшены", + details = if (retried) { + "Android сменил физическую сеть или мобильную data-SIM во время проверки. " + + "Результаты старой сети не использованы; пункты ниже относятся к новой сети." + } else { + "Android сменил физическую сеть или мобильную data-SIM, поэтому ошибки старого " + + "сетевого дескриптора (например ENONET/ENETUNREACH) не считаются отказом DNS или устройства." + }, + recommendation = if (retried) "" else + "Дождитесь устойчивого подключения к нужной сети и повторите проверку устройства.", + severity = if (retried) DeviceCheckSeverity.Info else DeviceCheckSeverity.Warning, + action = if (retried) null else DeviceCheckAction.NetworkSettings +) + private fun buildNetworkPathItem(network: DiagnosticNetwork): DeviceCheckItem { val capabilities = network.capabilities val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) @@ -542,6 +598,8 @@ private fun buildRecentNetworkEventsItem(): DeviceCheckItem? { entry.key.startsWith("vk_credentials_") || entry.key.startsWith("vk_legacy_") || entry.key.startsWith("turn_") || + entry.key.startsWith("rt_") || + entry.key.startsWith("masque_") || entry.key.startsWith("worker_turn_") } .take(12) diff --git a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt index a74a9d7..840f900 100644 --- a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt +++ b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt @@ -16,6 +16,7 @@ import android.provider.Settings import android.system.Os import android.system.OsConstants import android.webkit.WebView +import org.json.JSONObject import java.io.File import java.text.SimpleDateFormat import java.util.Date @@ -97,6 +98,70 @@ data class DeviceCompatibilityReport( } } +internal enum class RtMasqueEnrollmentState { + Missing, + Ready, + Invalid, +} + +internal fun inspectRtMasqueEnrollment(file: File): RtMasqueEnrollmentState { + if (!file.isFile) return RtMasqueEnrollmentState.Missing + if (file.length() !in 1L..128L * 1024L) return RtMasqueEnrollmentState.Invalid + return runCatching { + val json = JSONObject(file.readText(Charsets.UTF_8)) + val requiredFields = listOf( + "private_key", + "endpoint_v4", + "endpoint_pub_key", + "ipv4", + ) + if ( + json.optInt("version", -1) != 1 || + requiredFields.any { json.optString(it).isBlank() } + ) { + RtMasqueEnrollmentState.Invalid + } else { + RtMasqueEnrollmentState.Ready + } + }.getOrDefault(RtMasqueEnrollmentState.Invalid) +} + +internal fun pageSizeCompatibilityItem( + pageSize: Long?, + processIs64Bit: Boolean, +): DeviceCheckItem = when { + pageSize == null || pageSize <= 0L -> DeviceCheckItem( + title = "Страница памяти", + status = "не удалось определить", + details = "Android не вернул размер страницы памяти.", + recommendation = "Если VPN не стартует на новом устройстве, скопируйте отчёт через «Проверить устройство».", + severity = DeviceCheckSeverity.Info, + firstLaunchRelevant = false, + ) + pageSize == 16L * 1024L && processIs64Bit -> DeviceCheckItem( + title = "Страница памяти", + status = "16 КиБ · поддерживается", + details = "Устройство использует страницы памяти 16 КиБ. Все 64-битные нативные библиотеки release-сборки WDTT Plus проверяются на совместимое LOAD-выравнивание.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = true, + ) + pageSize > 4096L -> DeviceCheckItem( + title = "Страница памяти", + status = "$pageSize байт · требуется проверка", + details = "Android использует нестандартный для этой ABI размер страницы памяти, который нельзя подтвердить как штатный 16-КиБ режим текущей 64-битной сборки.", + recommendation = "Если туннель не стартует, установите подходящий APK и отправьте отчёт из «Проверить устройство».", + severity = DeviceCheckSeverity.Warning, + firstLaunchRelevant = true, + ) + else -> DeviceCheckItem( + title = "Страница памяти", + status = "$pageSize байт", + details = "Размер страницы памяти поддерживается текущей нативной сборкой.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = true, + ) +} + object DeviceCompatibility { const val APP_VERSION_ITEM_TITLE = "Версия WDTT Plus" private const val MIN_RECOMMENDED_SDK = 29 @@ -112,7 +177,7 @@ object DeviceCompatibility { val items = buildList { add(androidVersionItem()) add(abiItem()) - add(nativeClientItem(appContext)) + add(nativeComponentsItem(appContext)) nativeRuntimeSafetyItem()?.let(::add) add(pageSizeItem()) add(memoryClassItem(appContext, workersPerHash)) @@ -231,30 +296,27 @@ object DeviceCompatibility { ) } - private fun nativeClientItem(context: Context): DeviceCheckItem { + private fun nativeComponentsItem(context: Context): DeviceCheckItem { val nativeLibraryDir = context.applicationInfo.nativeLibraryDir.orEmpty() val nativeClient = File(nativeLibraryDir, "libclient.so") + val wireGuardBackend = File(nativeLibraryDir, "libwg-go.so") + val missing = buildList { + if (!nativeClient.isFile || nativeClient.length() <= 0L) add("libclient.so") + if (!wireGuardBackend.isFile || wireGuardBackend.length() <= 0L) add("libwg-go.so") + } return when { - !nativeClient.isFile -> DeviceCheckItem( - title = "Нативный клиент", - status = "libclient.so не найден", - details = "Android-часть запустилась, но нативный Go-клиент, который поднимает TURN/DTLS транспорт, в установленном APK не найден.", + missing.isNotEmpty() -> DeviceCheckItem( + title = "Нативные компоненты", + status = "не найдены: ${missing.joinToString()}", + details = "В установленном APK отсутствует или повреждён нативный клиент TURN/DTLS либо WireGuard backend системного VPN.", recommendation = "Переустановите APK нужной ABI или universal APK из официального релиза WDTT Plus.", severity = DeviceCheckSeverity.Error, firstLaunchRelevant = true ) - nativeClient.length() <= 0L -> DeviceCheckItem( - title = "Нативный клиент", - status = "libclient.so пустой", - details = "Файл нативного клиента найден, но его размер равен нулю.", - recommendation = "Переустановите APK; текущая установка выглядит повреждённой.", - severity = DeviceCheckSeverity.Error, - firstLaunchRelevant = true - ) else -> DeviceCheckItem( - title = "Нативный клиент", - status = "найден", - details = "libclient.so найден в установленном APK, размер: ${formatMiB(nativeClient.length())}.", + title = "Нативные компоненты", + status = "клиент и WireGuard найдены", + details = "libclient.so: ${formatMiB(nativeClient.length())}; libwg-go.so: ${formatMiB(wireGuardBackend.length())}.", severity = DeviceCheckSeverity.Ok, firstLaunchRelevant = true ) @@ -263,29 +325,56 @@ object DeviceCompatibility { private fun pageSizeItem(): DeviceCheckItem { val pageSize = runCatching { Os.sysconf(OsConstants._SC_PAGESIZE) }.getOrNull() + return pageSizeCompatibilityItem(pageSize, android.os.Process.is64Bit()) + } + + fun rtNetworkModeItem(context: Context, profile: TunnelProfileSnapshot): DeviceCheckItem { + val enrollment = inspectRtMasqueEnrollment( + File(context.filesDir, RT_MASQUE_CONFIG_FILE_NAME) + ) return when { - pageSize == null || pageSize <= 0L -> DeviceCheckItem( - title = "Страница памяти", - status = "не удалось определить", - details = "Android не вернул размер страницы памяти.", - recommendation = "Если VPN не стартует на новом устройстве, скопируйте отчёт через «Проверить устройство».", + !profile.rtNetwork -> DeviceCheckItem( + title = "Режим Сеть РТ", + status = "выключен", + details = "Используется обычный порядок транспортов; настройки РТ этого профиля не влияют на подключение.", severity = DeviceCheckSeverity.Info, - firstLaunchRelevant = false ) - pageSize > 4096L -> DeviceCheckItem( - title = "Страница памяти", - status = "$pageSize байт", - details = "Устройство использует страницу памяти больше 4 KB. Для новых Android-устройств с 16 KB page size нужна отдельная проверка нативной библиотеки.", - recommendation = "Запуск не блокируется. Если туннель не стартует, отправьте отчёт из «Проверить устройство» — это важный сценарий для будущей совместимости.", + !profile.rtMasque -> DeviceCheckItem( + title = "Режим Сеть РТ", + status = "TURN/TLS и TCP включены · MASQUE выключен", + details = "Для активного профиля включён только основной механизм Сети РТ. Регистрация WARP не требуется.", + severity = DeviceCheckSeverity.Ok, + ) + profile.rtMasqueServerBootstrap && !profile.rtMasqueServerAccessReady -> DeviceCheckItem( + title = "Режим Сеть РТ", + status = "«Через сервер» настроен не полностью", + details = "MASQUE включён, но в активном профиле нет полного SSH-доступа из раздела «Деплой».", + recommendation = "Заполните адрес и пароль либо приватный SSH-ключ в «Деплой» или выключите «Через сервер».", severity = DeviceCheckSeverity.Warning, - firstLaunchRelevant = true + ) + enrollment == RtMasqueEnrollmentState.Invalid -> DeviceCheckItem( + title = "Режим Сеть РТ", + status = "регистрация WARP повреждена", + details = "Локальный файл регистрации MASQUE не содержит корректной структуры версии 1. Секретные поля в отчёт не включены.", + recommendation = "Остановите VPN и выполните «Сбросить регистрацию WARP» в инструкции MASQUE.", + severity = DeviceCheckSeverity.Warning, + ) + enrollment == RtMasqueEnrollmentState.Missing -> DeviceCheckItem( + title = "Режим Сеть РТ", + status = "MASQUE включён · регистрация ещё не создана", + details = "При следующем запуске VPN приложение попробует зарегистрировать отдельное устройство WARP. Прямые TURN-пути продолжат работать во время подготовки.", + recommendation = if (profile.rtMasqueServerBootstrap) { + "Если прямой TLS Cloudflare недоступен, приложение сможет использовать SSH-выход активного профиля." + } else { + "Если регистрация не выполняется, проверьте журнал MASQUE; при необходимости настройте «Через сервер»." + }, + severity = DeviceCheckSeverity.Info, ) else -> DeviceCheckItem( - title = "Страница памяти", - status = "$pageSize байт", - details = "Обычный размер страницы памяти для текущей нативной сборки.", + title = "Режим Сеть РТ", + status = "MASQUE готов", + details = "Структура сохранённой регистрации WARP корректна; при запуске её дополнительно проверит нативный клиент.", severity = DeviceCheckSeverity.Ok, - firstLaunchRelevant = true ) } } diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt index 50dbec5..e37822b 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -124,6 +124,11 @@ internal fun shouldHandleIncomingIntent( private sealed interface WdttConnectFlow { data class Progress(val message: String) : WdttConnectFlow + data class SelectAttachmentProfile( + val link: RemoteDocumentLink, + val candidates: List, + val selectedProfile: Int, + ) : WdttConnectFlow data class SelectProfile( val plan: WdttDeepLinkApplyPlan, val delivery: RemoteDocumentDelivery @@ -264,7 +269,9 @@ class MainActivity : ComponentActivity() { wdttDeepLinkMessage = message }, onSelectWdttDeepLinkOverwriteProfile = { profile -> - pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan?.copy(targetProfile = profile) + pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan?.let { plan -> + if (profile in plan.blockedProfiles) plan else plan.copy(targetProfile = profile) + } }, onConfirmWdttDeepLinkOverwrite = { plan -> pendingWdttDeepLinkPlan = null @@ -276,7 +283,31 @@ class MainActivity : ComponentActivity() { }, onSelectWdttConnectProfile = { profile -> (wdttConnectFlow as? WdttConnectFlow.SelectProfile)?.let { flow -> - wdttConnectFlow = flow.copy(plan = flow.plan.copy(targetProfile = profile)) + if (profile !in flow.plan.blockedProfiles) { + wdttConnectFlow = flow.copy( + plan = flow.plan.copy(targetProfile = profile) + ) + } + } + }, + onSelectWdttAttachmentProfile = { profile -> + (wdttConnectFlow as? WdttConnectFlow.SelectAttachmentProfile)?.let { flow -> + if (flow.candidates.any { it.profileIndex == profile }) { + wdttConnectFlow = flow.copy(selectedProfile = profile) + } + } + }, + onConfirmWdttAttachmentProfile = { + (wdttConnectFlow as? WdttConnectFlow.SelectAttachmentProfile)?.let { flow -> + flow.candidates.firstOrNull { + it.profileIndex == flow.selectedProfile + }?.let { candidate -> + receiveRemoteDocument( + flow.link, + candidate.document, + candidate.profileIndex, + ) + } } }, onConfirmWdttConnectProfile = { plan -> @@ -496,19 +527,106 @@ class MainActivity : ComponentActivity() { receiveRemoteDocument(link) } - private fun receiveRemoteDocument(link: RemoteDocumentLink) { + private fun receiveRemoteDocument( + link: RemoteDocumentLink, + localDocument: String? = null, + attachmentProfile: Int? = null, + ) { if (!remoteDocumentRequests.add(link.url)) return lifecycleScope.launch { try { + var requestedAttachmentProfile = attachmentProfile wdttConnectFlow = WdttConnectFlow.Progress("Проверяем ссылку и получаем доступ...") - val delivery = RemoteDocumentGateway.receive( - link = link, - device = settingsStore.getOrCreateConnectDeviceId(), - label = vkHashDeviceName(), - client = BuildConfig.VERSION_NAME, - system = Build.VERSION.RELEASE.orEmpty(), - localBindings = settingsStore.remoteDocumentBindings(), - ) + suspend fun request( + document: String?, + profileAttachment: Boolean = false, + ): RemoteDocumentDelivery = + RemoteDocumentGateway.receive( + link = link, + device = settingsStore.getOrCreateConnectDeviceId(), + label = vkHashDeviceName(), + client = BuildConfig.VERSION_NAME, + system = Build.VERSION.RELEASE.orEmpty(), + localBindings = settingsStore.remoteDocumentBindings(), + localDocument = document, + profileAttachment = profileAttachment, + ) + val delivery = try { + request( + localDocument, + profileAttachment = attachmentProfile != null, + ) + } catch (error: RemoteDocumentFailure) { + if (!error.profileAttachmentRequired || localDocument != null) throw error + val candidates = settingsStore.remoteAttachmentCandidates() + val selection = resolveRemoteAttachmentCandidates( + candidates = candidates, + ) + when { + candidates.isEmpty() -> { + wdttConnectFlow = WdttConnectFlow.Failed( + "Все локальные профили уже заняты действующими удалёнными " + + "разрешениями или готовыми профилями. Освободите обычный " + + "профиль и откройте ссылку снова." + ) + return@launch + } + else -> { + wdttConnectFlow = WdttConnectFlow.SelectAttachmentProfile( + link = link, + candidates = selection.choices, + selectedProfile = selection.choices.first().profileIndex, + ) + return@launch + } + } + } + if (delivery.kind == RemoteDocumentKind.ATTACHMENT) { + val profile = requestedAttachmentProfile + ?: settingsStore.profileForRemoteBinding(delivery.binding) + if ( + profile == null || + !settingsStore.applyRemoteCapabilityAttachment(profile, delivery) + ) { + wdttConnectFlow = WdttConnectFlow.Failed( + "Не удалось сохранить разрешение в выбранном профиле." + ) + return@launch + } + val confirmedStatus = when ( + val confirmation = AccessLifecycleCoordinator.refreshProfile( + this@MainActivity, + profile, + force = true, + ) + ) { + is AccessLifecycleRefreshResult.Success -> confirmation.status + is AccessLifecycleRefreshResult.Cached -> confirmation.status + else -> { + wdttConnectFlow = WdttConnectFlow.Failed( + "Разрешение сохранено в выбранном профиле, но сервер пока " + + "не подтвердил привязку. Проверьте интернет и обновите " + + "карточку профиля." + ) + return@launch + } + } + val confirmedContinuation = + if (confirmedStatus?.continuationAvailable == false) { + RemoteContinuation( + available = false, + message = delivery.continuation.message, + ) + } else { + delivery.continuation + } + wdttConnectFlow = WdttConnectFlow.SelectHashes( + profile = profile, + continuation = confirmedContinuation, + access = delivery.access, + ) + return@launch + } wdttConnectFlow = WdttConnectFlow.Progress("Доступ получен. Подготавливаем VPN-профиль...") var boundProfile: Int? = null for (binding in listOf(delivery.binding, delivery.access.binding)) { @@ -516,6 +634,13 @@ class MainActivity : ComponentActivity() { boundProfile = settingsStore.profileForRemoteBinding(binding) if (boundProfile != null) break } + if ( + boundProfile == null && + delivery.kind == RemoteDocumentKind.BASE && + requestedAttachmentProfile != null + ) { + boundProfile = requestedAttachmentProfile + } if (boundProfile == null && delivery.kind == RemoteDocumentKind.BASE) { boundProfile = settingsStore.profileForConnectionDocument(delivery.document) } @@ -567,7 +692,10 @@ class MainActivity : ComponentActivity() { lifecycleScope.launch { val store = SettingsStore(this@MainActivity) runCatching { - store.createWdttDeepLinkApplyPlan(link) + store.createWdttDeepLinkApplyPlan( + link, + allowOmittedConnection = delivery?.kind == RemoteDocumentKind.UPDATE, + ) }.onSuccess { basePlan -> val plan = basePlan?.let { if (preferredProfile == null) it else it.copy( @@ -684,24 +812,17 @@ class MainActivity : ComponentActivity() { } if (fromRemoteDocument) { val profile = result?.targetProfile ?: plan.targetProfile - if (delivery?.access?.available == true) { + if (delivery?.access?.available == true || isBoundUpdate) { lifecycleScope.launch { AccessLifecycleCoordinator.refreshProfile( this@MainActivity, profile, - force = delivery.access.initialStatus == null, + force = isBoundUpdate || delivery?.access?.initialStatus == null, ) } } - if (isBoundUpdate) { - val profileLabel = vpnProfileDisplayName(profile, store.profileNames.first()) - wdttConnectFlow = WdttConnectFlow.Complete( - if (result?.alreadyApplied == true) { - "Обновление профиля $profileLabel уже применено." - } else { - "Профиль $profileLabel обновлён. Новые данные уже видны в настройках туннеля." - } - ) + if (shouldRestoreUiAfterBoundUpdate(isBoundUpdate)) { + wdttConnectFlow = null } else if ( existingRemoteProfile && store.tunnelProfileSnapshot(profile).vkHashes.isNotBlank() @@ -737,7 +858,13 @@ class MainActivity : ComponentActivity() { } private fun startConnectAction(profile: Int, continuation: RemoteContinuation) { - connectActionJob?.cancel() + // The dialog can deliver two taps before Compose has rendered the + // ExternalAction state. Do not cancel an already running preparation + // and start a second browser/login flow: VK treats those parallel + // attempts as repeated authentication requests and may answer with + // its flood-control error [9]. A fresh attempt is available through + // the explicit Back/Retry path after the current job finishes. + if (connectActionJob?.isActive == true) return val access = (wdttConnectFlow as? WdttConnectFlow.SelectHashes) ?.access ?: RemoteAccessCapability.Unavailable @@ -792,7 +919,8 @@ class MainActivity : ComponentActivity() { ) val target = RemoteContinuationLauncher.begin( capability = continuation, - device = settingsStore.getOrCreateConnectDeviceId() + device = settingsStore.getOrCreateConnectDeviceId(), + localDocument = settingsStore.remoteActionProfileDocument(profile), ) launchRemoteContinuation(target) wdttConnectFlow = WdttConnectFlow.Complete( @@ -1251,6 +1379,8 @@ private fun MainScreen( onSelectWdttDeepLinkOverwriteProfile: (Int) -> Unit = {}, onConfirmWdttDeepLinkOverwrite: (WdttDeepLinkApplyPlan) -> Unit = {}, onCancelWdttDeepLinkOverwrite: () -> Unit = {}, + onSelectWdttAttachmentProfile: (Int) -> Unit = {}, + onConfirmWdttAttachmentProfile: () -> Unit = {}, onSelectWdttConnectProfile: (Int) -> Unit = {}, onConfirmWdttConnectProfile: (WdttDeepLinkApplyPlan) -> Unit = {}, onContinueLimitedWdttSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit = { _, _ -> }, @@ -1283,7 +1413,8 @@ private fun MainScreen( val scope = rememberCoroutineScope() val updateCheckMutex = remember { Mutex() } val settingsReady by settingsStore.settingsReady.collectAsStateWithLifecycle(initialValue = false) - val startupSettings by settingsStore.activeTunnelProfileUiSnapshot.collectAsStateWithLifecycle() + val startupSettings by + settingsStore.activeTunnelProfileContentUiSnapshot.collectAsStateWithLifecycle() if (!settingsReady || startupSettings == null) { Box(modifier = Modifier.fillMaxSize()) { AppBackdrop(modifier = Modifier.matchParentSize()) @@ -1768,6 +1899,7 @@ private fun MainScreen( // Floating theme toolbar overlay FloatingToolbar( + settingsStore = settingsStore, activeProfile = activeProfile, profileNames = profileNames, onActiveProfileChange = { profile -> @@ -1990,6 +2122,8 @@ private fun MainScreen( WdttConnectActivationDialog( flow = flow, profileNames = profileNames, + onSelectAttachmentProfile = onSelectWdttAttachmentProfile, + onConfirmAttachmentProfile = onConfirmWdttAttachmentProfile, onSelectProfile = onSelectWdttConnectProfile, onConfirmProfile = onConfirmWdttConnectProfile, onContinueLimitedSetup = onContinueLimitedWdttSetup, @@ -2032,16 +2166,24 @@ private fun MainScreen( repeat(3) { profile -> FilterChip( selected = plan.targetProfile == profile, + enabled = profile !in plan.blockedProfiles, onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) }, label = { Text(vpnProfileDisplayName(profile, profileNames)) } ) } } - Text("Будет полностью заменено подключение в профиле $profileLabel.") + if (plan.blockedProfiles.size == 3) { + Text("Все профили защищены действующим удалённым доступом. Сначала освободите один из них.") + } else { + Text("Будет полностью заменено подключение в профиле $profileLabel.") + } } }, confirmButton = { - TextButton(onClick = { onConfirmWdttDeepLinkOverwrite(plan) }) { + TextButton( + enabled = plan.targetProfile !in plan.blockedProfiles, + onClick = { onConfirmWdttDeepLinkOverwrite(plan) }, + ) { Text("Да") } }, @@ -2058,6 +2200,8 @@ private fun MainScreen( private fun WdttConnectActivationDialog( flow: WdttConnectFlow, profileNames: List, + onSelectAttachmentProfile: (Int) -> Unit, + onConfirmAttachmentProfile: () -> Unit, onSelectProfile: (Int) -> Unit, onConfirmProfile: (WdttDeepLinkApplyPlan) -> Unit, onContinueLimitedSetup: (WdttDeepLinkApplyPlan, RemoteDocumentDelivery) -> Unit, @@ -2073,7 +2217,8 @@ private fun WdttConnectActivationDialog( var selectedHashMethod by rememberSaveable { mutableStateOf(null) } var helpMethod by rememberSaveable { mutableStateOf(null) } var unavailableAutoMessage by rememberSaveable { mutableStateOf(null) } - val canDismiss = flow is WdttConnectFlow.Complete || + val canDismiss = flow is WdttConnectFlow.SelectAttachmentProfile || + flow is WdttConnectFlow.Complete || flow is WdttConnectFlow.Failed AlertDialog( onDismissRequest = { @@ -2110,6 +2255,41 @@ private fun WdttConnectActivationDialog( Text(state.message) } } + is WdttConnectFlow.SelectAttachmentProfile -> { + val selectedCandidate = state.candidates.first { + it.profileIndex == state.selectedProfile + } + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + "Найдено несколько изменённых обычных профилей. " + + "Выберите, к какому из них привязать разрешение. " + + "Готовые профили здесь недоступны." + ) + state.candidates.forEach { candidate -> + FilterChip( + selected = state.selectedProfile == candidate.profileIndex, + onClick = { + onSelectAttachmentProfile(candidate.profileIndex) + }, + label = { + Text("${candidate.displayName} · ${candidate.sourceLabel}") + }, + ) + } + Text( + if (selectedCandidate.sourceLabel.contains("Деплой")) { + "Если подключение в «Деплое» заполнено полностью, при запуске " + + "будут использованы только адрес, порты и главный пароль. " + + "SSH-логин, SSH-пароль и ключи не передаются." + } else { + "Можно выбрать даже частично заполненный профиль и закончить " + + "его настройку позже. Подключение не заменяется." + }, + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + ) + } + } is WdttConnectFlow.SelectProfile -> { val incomingName = WdttDeepLink.parse( state.plan.link, @@ -2124,13 +2304,20 @@ private fun WdttConnectActivationDialog( repeat(3) { profile -> FilterChip( selected = state.plan.targetProfile == profile, + enabled = profile !in state.plan.blockedProfiles, onClick = { onSelectProfile(profile) }, label = { Text(vpnProfileDisplayName(profile, profileNames)) } ) } } Text( - "Подключение в выбранном профиле будет полностью заменено.", + if (state.plan.blockedProfiles.size == 3) { + "Все профили защищены действующим готовым доступом. " + + "Ни один из них нельзя перезаписать." + } else { + "Подключение в выбранном профиле будет полностью заменено. " + + "Действующие готовые профили недоступны для выбора." + }, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall, ) @@ -2141,7 +2328,7 @@ private fun WdttConnectActivationDialog( "Автоматическое получение VK-хешей сейчас недоступно." } Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Перед добавлением профиля обратите внимание:") + Text("Перед продолжением обратите внимание:") Text(reason) Text( "Это ограничение относится только к автоматическому получению " + @@ -2153,25 +2340,13 @@ private fun WdttConnectActivationDialog( } is WdttConnectFlow.SelectHashes -> { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Выберите способ заполнения VK-хешей для нового профиля.") - if (state.access.exchange.actionAvailable) { - HashMethodRow( - title = state.access.exchange.label.ifBlank { - "Вернуть хеши" - }, - body = state.access.exchange.message.ifBlank { - "Восстановить сохранённые хеши этого профиля" - }, - onHelp = { helpMethod = "restore" }, - onClick = { - onRestoreSavedHashes(state.profile, state.access) - } - ) - } + Text("Выберите способ заполнения VK-хешей для профиля.") HashMethodRow( title = "Получить автоматически", body = if (state.continuation.available) { - "Войти в VK при необходимости и создать ссылки" + state.continuation.message.ifBlank { + "Войти в VK при необходимости и создать ссылки" + } } else { "Недоступно — нажмите, чтобы узнать, что делать" }, @@ -2192,6 +2367,20 @@ private fun WdttConnectActivationDialog( onHelp = { helpMethod = "manual" }, onClick = { selectedHashMethod = "manual" } ) + if (state.access.exchange.actionAvailable) { + HashMethodRow( + title = state.access.exchange.label.ifBlank { + "Вернуть хеши" + }, + body = state.access.exchange.message.ifBlank { + "Восстановить сохранённые хеши этого профиля" + }, + onHelp = { helpMethod = "restore" }, + onClick = { + onRestoreSavedHashes(state.profile, state.access) + } + ) + } if (selectedHashMethod == "manual") { OutlinedTextField( value = manualHashes, @@ -2211,8 +2400,16 @@ private fun WdttConnectActivationDialog( }, confirmButton = { when (flow) { + is WdttConnectFlow.SelectAttachmentProfile -> { + TextButton(onClick = onConfirmAttachmentProfile) { + Text("Продолжить") + } + } is WdttConnectFlow.SelectProfile -> { - TextButton(onClick = { onConfirmProfile(flow.plan) }) { + TextButton( + enabled = flow.plan.targetProfile !in flow.plan.blockedProfiles, + onClick = { onConfirmProfile(flow.plan) }, + ) { Text("Сохранить") } } @@ -2256,6 +2453,11 @@ private fun WdttConnectActivationDialog( }, dismissButton = { when (flow) { + is WdttConnectFlow.SelectAttachmentProfile -> { + TextButton(onClick = onDismiss) { + Text("Отмена") + } + } is WdttConnectFlow.SelectProfile -> { TextButton(onClick = onDismiss) { Text("Позже") @@ -2310,7 +2512,7 @@ private fun WdttConnectActivationDialog( } "restore" -> { "WDTT Plus безопасно вернёт хеши, ранее сохранённые именно для " + - "этого готового профиля. Хеши других ваших профилей не используются." + "этого профиля. Значения других профилей не используются." } else -> { "Создайте или скопируйте до четырёх ссылок-приглашений VK Звонков, " + diff --git a/app/src/main/java/com/wdtt/plus/RemoteActionCatalog.kt b/app/src/main/java/com/wdtt/plus/RemoteActionCatalog.kt index aa54cea..17f3eb4 100644 --- a/app/src/main/java/com/wdtt/plus/RemoteActionCatalog.kt +++ b/app/src/main/java/com/wdtt/plus/RemoteActionCatalog.kt @@ -3,6 +3,8 @@ package com.wdtt.plus import android.content.Context import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import org.json.JSONObject import java.net.HttpURLConnection @@ -81,6 +83,7 @@ object RemoteActionCatalogGateway { private const val CACHE_TTL_MS = 10 * 60 * 1000L private const val MAX_RESPONSE_CHARS = 32 * 1024 private val placements = setOf("tunnel", "profile", "about") + private val fetchMutex = Mutex() @Volatile private var cachedAt = 0L @@ -91,21 +94,24 @@ object RemoteActionCatalogGateway { fun hasFreshCache(): Boolean = System.currentTimeMillis() - cachedAt in 0 until CACHE_TTL_MS - fun cached(): RemoteActionCatalog = - if (hasFreshCache()) cachedCatalog else RemoteActionCatalog.Empty + fun cached(): RemoteActionCatalog = cachedCatalog suspend fun fetch(force: Boolean = false): RemoteActionCatalog { val now = System.currentTimeMillis() if (!force && now - cachedAt in 0 until CACHE_TTL_MS) return cachedCatalog return withContext(Dispatchers.IO) { - val current = System.currentTimeMillis() - if (!force && current - cachedAt in 0 until CACHE_TTL_MS) { - return@withContext cachedCatalog + fetchMutex.withLock { + val current = System.currentTimeMillis() + if (!force && current - cachedAt in 0 until CACHE_TTL_MS) { + return@withLock cachedCatalog + } + runCatching { request() } + .onSuccess { received -> + cachedCatalog = received + cachedAt = current + } + cachedCatalog } - val received = runCatching { request() }.getOrDefault(RemoteActionCatalog.Empty) - cachedCatalog = received - cachedAt = current - received } } diff --git a/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt b/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt index 1288608..7c900d8 100644 --- a/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt +++ b/app/src/main/java/com/wdtt/plus/RemoteContinuationLauncher.kt @@ -29,17 +29,25 @@ data class RemoteLaunchTarget( } object RemoteContinuationLauncher { - suspend fun begin(capability: RemoteContinuation, device: String): RemoteLaunchTarget { + suspend fun begin( + capability: RemoteContinuation, + device: String, + localDocument: String? = null, + ): RemoteLaunchTarget { require(capability.available && opaqueValue(capability.key)) { "Автоматическое заполнение недоступно для этого профиля." } require(safeServiceUrl(capability.url)) { "Автоматическое заполнение сейчас недоступно." } require(validDevice(device)) { "Не удалось определить текущее устройство." } return withContext(Dispatchers.IO) { - val payload = JSONObject() + val request = JSONObject() .put("key", capability.key.trim()) .put("device", device.trim()) .put("return_transport", "auth_tab") + attachmentDocumentForRequest(localDocument)?.let { document -> + request.put("profile", document) + } + val payload = request .toString() .toByteArray(Charsets.UTF_8) var connection: HttpURLConnection? = null @@ -164,6 +172,11 @@ object RemoteContinuationLauncher { internal fun browserLaunchUrls(target: RemoteLaunchTarget): List = ( + // The primary URL is for the preferred native VK handler. When + // that handler is unavailable, the backend-provided mobile login + // URL is the proven browser entry: it preserves the opaque `to` + // state through an unauthenticated VK login and immediately + // continues to the Mini App for an existing browser session. if (target.handlerPackages().isNotEmpty() && target.fallbackUrl.isNotBlank()) { listOf(target.fallbackUrl, target.primaryUrl) } else { diff --git a/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt b/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt index 3759bc9..4e74cb5 100644 --- a/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt +++ b/app/src/main/java/com/wdtt/plus/RemoteDocumentGateway.kt @@ -21,6 +21,7 @@ data class RemoteDocumentFailureAction( class RemoteDocumentFailure( message: String, val action: RemoteDocumentFailureAction? = null, + val profileAttachmentRequired: Boolean = false, ) : IllegalStateException(message) data class RemoteContinuation( @@ -33,7 +34,8 @@ data class RemoteContinuation( enum class RemoteDocumentKind { BASE, - UPDATE + UPDATE, + ATTACHMENT, } data class RemoteDocumentDelivery( @@ -49,7 +51,11 @@ data class RemoteDocumentDelivery( internal fun RemoteDocumentDelivery.shouldPreserveLocalVkHashes( existingProfileRedelivery: Boolean = false, ): Boolean { - val deliveredHashes = WdttDeepLink.parse(document, allowMissingHashes = true) + val deliveredHashes = WdttDeepLink.parse( + document, + allowMissingHashes = true, + allowOmittedConnection = kind == RemoteDocumentKind.UPDATE, + ) ?.hashes .orEmpty() return deliveredHashes.isBlank() && @@ -64,7 +70,24 @@ internal fun RemoteDocumentDelivery.requiresInitialContinuationWarning( ): Boolean = kind == RemoteDocumentKind.BASE && !continuation.available && - !existingProfileHasVkHashes + !existingProfileHasVkHashes + +internal fun attachmentDocumentForRequest(localDocument: String?): String? = + localDocument + ?.trim() + ?.takeIf { document -> + document.length <= 4 * 1024 && + document.startsWith("wdtt://connect?", ignoreCase = true) && + WdttDeepLink.parse(document, allowMissingHashes = true) + ?.let { it.hashes.isBlank() } == true + } + +internal fun eligibleRemoteAttachmentDocument( + localDocument: String?, + alreadyManaged: Boolean, +): String? = if (alreadyManaged) null else attachmentDocumentForRequest(localDocument) + +internal fun profileAttachmentRequired(value: String?): Boolean = value?.trim() == "1" object RemoteDocumentGateway { private const val MAX_RESPONSE_CHARS = 32 * 1024 @@ -95,6 +118,8 @@ object RemoteDocumentGateway { client: String, system: String, localBindings: Collection? = null, + localDocument: String? = null, + profileAttachment: Boolean = false, ): RemoteDocumentDelivery { require(extractLink(link.url) != null) { "Ссылка повреждена или неполна." } require(validDevice(device)) { "Не удалось определить текущее устройство." } @@ -113,6 +138,11 @@ object RemoteDocumentGateway { .take(6) request.put("bindings", JSONArray(bindings)) } + attachmentDocumentForRequest(localDocument) + ?.let { request.put("profile", it) } + if (profileAttachment) { + request.put("attach", true) + } val payload = request .toString() .toByteArray(Charsets.UTF_8) @@ -135,6 +165,9 @@ object RemoteDocumentGateway { "Ссылка недоступна. Получите новую ссылку подключения." }, failure.second, + profileAttachmentRequired = profileAttachmentRequired( + connection.getHeaderField("X-WDTT-Profile-Required") + ), ) } parse(body) @@ -161,11 +194,20 @@ object RemoteDocumentGateway { val kind = when (root.optString("type").trim()) { "base" -> RemoteDocumentKind.BASE "update" -> RemoteDocumentKind.UPDATE + "attachment" -> RemoteDocumentKind.ATTACHMENT else -> throw IllegalStateException("WDTT Plus вернул неподдерживаемый тип данных.") } val document = root.optString("document").trim() - val documentParts = WdttDeepLink.parse(document, allowMissingHashes = true) - if (documentParts == null) { + val documentParts = document + .takeIf(String::isNotBlank) + ?.let { + WdttDeepLink.parse( + it, + allowMissingHashes = true, + allowOmittedConnection = kind == RemoteDocumentKind.UPDATE, + ) + } + if (kind != RemoteDocumentKind.ATTACHMENT && documentParts == null) { throw IllegalStateException("WDTT Plus вернул неполные данные подключения.") } val binding = root.optString("binding").trim().takeIf(::opaqueValue).orEmpty() @@ -203,7 +245,7 @@ object RemoteDocumentGateway { } when (kind) { RemoteDocumentKind.BASE -> { - if (documentParts.hashes.isNotBlank()) { + if (documentParts?.hashes?.isNotBlank() == true) { throw IllegalStateException( "Ссылка подключения содержит лишние данные. Получите новую ссылку." ) @@ -219,6 +261,19 @@ object RemoteDocumentGateway { ) } } + RemoteDocumentKind.ATTACHMENT -> { + if ( + document.isNotBlank() || + binding.isBlank() || + !available || + !accessAvailable || + accessBinding != binding + ) { + throw IllegalStateException( + "WDTT Plus вернул неполное разрешение для выбранного профиля." + ) + } + } } val workers = root.optJSONObject("limits")?.optInt("workers", 0) ?.takeIf { diff --git a/app/src/main/java/com/wdtt/plus/SecureStringStore.kt b/app/src/main/java/com/wdtt/plus/SecureStringStore.kt index 0e49ab9..86810a4 100644 --- a/app/src/main/java/com/wdtt/plus/SecureStringStore.kt +++ b/app/src/main/java/com/wdtt/plus/SecureStringStore.kt @@ -12,11 +12,6 @@ import javax.crypto.spec.GCMParameterSpec class SecureStringStore(context: Context) { private val appContext = context.applicationContext - private val decryptedCache = object : LinkedHashMap(32, 0.75f, true) { - override fun removeEldestEntry( - eldest: MutableMap.MutableEntry? - ): Boolean = size > 64 - } companion object { private const val KEY_ALIAS = "wdtt.settings.secrets" @@ -24,6 +19,11 @@ class SecureStringStore(context: Context) { private const val TRANSFORMATION = "AES/GCM/NoPadding" private const val GCM_TAG_BITS = 128 private const val VERSION_PREFIX = "v1:" + private val decryptedCache = object : LinkedHashMap(64, 0.75f, true) { + override fun removeEldestEntry( + eldest: MutableMap.MutableEntry? + ): Boolean = size > 128 + } } private val keyStore: KeyStore by lazy { diff --git a/app/src/main/java/com/wdtt/plus/ServerMigration.kt b/app/src/main/java/com/wdtt/plus/ServerMigration.kt index a339eba..1408692 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) +internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14) 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 2459a8f..1af6f55 100644 --- a/app/src/main/java/com/wdtt/plus/SettingsStore.kt +++ b/app/src/main/java/com/wdtt/plus/SettingsStore.kt @@ -100,7 +100,8 @@ data class WdttDeepLinkApplyPlan( val link: String, val targetProfile: Int, val requiresConfirmation: Boolean, - val storeAsLink: Boolean + val storeAsLink: Boolean, + val blockedProfiles: Set = emptySet(), ) data class WdttDeepLinkApplyResult( @@ -110,6 +111,15 @@ data class WdttDeepLinkApplyResult( val alreadyApplied: Boolean = false, ) +internal fun shouldPreserveConnectionSettingsForRemoteUpdate( + isBoundUpdate: Boolean, + remoteManaged: Boolean, + incomingHost: String, + incomingPassword: String, +): Boolean = isBoundUpdate && ( + !remoteManaged || incomingHost.isBlank() && incomingPassword.isBlank() +) + internal data class InterfaceRoleProfileState( val role: String, val rememberedRole: String?, @@ -152,6 +162,11 @@ data class TunnelProfileSnapshot( val sni: String, val protocol: String, val vkCallsPreflight: Boolean, + val rtNetwork: Boolean = false, + val rtMasque: Boolean = false, + val rtMasqueServerBootstrap: Boolean = false, + val rtMasqueServerAccessReady: Boolean = false, + val rtTurnSni: String = DEFAULT_RT_TURN_SNI, val captchaMode: String, val captchaSolveMethod: String, val fingerprint: String, @@ -161,6 +176,68 @@ data class TunnelProfileSnapshot( val customVkClientSecret: String, ) +data class RemoteAttachmentCandidate( + val profileIndex: Int, + val displayName: String, + val sourceLabel: String, + val document: String, + val modified: Boolean, +) + +internal data class RemoteAttachmentSelection( + val choices: List = emptyList(), +) + +internal data class RemoteAttachmentDocument( + val document: String, + val sourceLabel: String, +) + +internal fun selectRemoteAttachmentDocument( + tunnelParts: WdttLinkParts, + deployParts: WdttLinkParts, + profileName: String, + maxWorkers: Int, + alreadyManaged: Boolean, +): RemoteAttachmentDocument? { + if (alreadyManaged) return null + for ((parts, sourceLabel) in listOf(tunnelParts to "Туннель", deployParts to "Деплой")) { + val document = WdttTransferCodec.buildConnectionLink( + parts.copy( + hashes = "", + profileName = profileName, + maxWorkers = maxWorkers, + ) + ) + eligibleRemoteAttachmentDocument(document, alreadyManaged = false)?.let { + return RemoteAttachmentDocument(it, sourceLabel) + } + } + return null +} + +internal fun resolveRemoteAttachmentCandidates( + candidates: List, +): RemoteAttachmentSelection = RemoteAttachmentSelection(choices = candidates) + +internal fun canReplaceRemoteAttachment( + hasAttachment: Boolean, + remoteManaged: Boolean, + continuationAvailable: Boolean?, + dismissible: Boolean?, +): Boolean = + hasAttachment && + !remoteManaged && + continuationAvailable == false && + dismissible == true + +internal fun shouldRestoreUiAfterBoundUpdate(isBoundUpdate: Boolean): Boolean = isBoundUpdate + +internal fun protectsRemoteProfileFromReplacement( + remoteManagedProfile: Boolean, + allowConnect: Boolean?, +): Boolean = remoteManagedProfile && allowConnect != false + /** * One atomic DataStore projection for the visible Tunnel tab. * @@ -192,6 +269,11 @@ data class ActiveTunnelProfileUiSnapshot( val customVkClientId: String, val customVkClientSecret: String, val vkCallsPreflight: Boolean, + val rtNetwork: Boolean = false, + val rtMasque: Boolean = false, + val rtMasqueServerBootstrap: Boolean = false, + val rtMasqueServerAccessStatus: SshProfileAccessStatus, + val rtTurnSni: String = DEFAULT_RT_TURN_SNI, val remoteActionKey: String, val remoteActionUrl: String, val remoteManaged: Boolean, @@ -202,12 +284,51 @@ data class ActiveTunnelProfileUiSnapshot( val profileMaxWorkers: Int, ) +data class ActiveTunnelAccessUiSnapshot( + val profileIndex: Int, + val lifecycle: AccessLifecycleUiState, + val dismissedSignature: String, +) + +internal fun ActiveTunnelProfileUiSnapshot.withoutTransientAccessState(): + ActiveTunnelProfileUiSnapshot = copy( + accessLifecycle = AccessLifecycleUiState.Unmanaged, + accessLifecycleDismissedSignature = "", + ) + +internal fun existingProfileValuesForRemoteAttachment( + linkMode: Boolean, + storedLink: String, + manualValues: String, +): String { + val storedValues = if (linkMode) { + WdttDeepLink.parse(storedLink, allowMissingHashes = true)?.hashes.orEmpty() + } else { + manualValues + } + return storedValues + .split(",") + .map(VkJoinLink::extractHash) + .filter(VkJoinLink::isValidHash) + .distinct() + .take(4) + .joinToString(",") +} + object WdttDeepLink { - fun parse(value: String, allowMissingHashes: Boolean = false): WdttLinkParts? { - return validate(value, allowMissingHashes).parts + fun parse( + value: String, + allowMissingHashes: Boolean = false, + allowOmittedConnection: Boolean = false, + ): WdttLinkParts? { + return validate(value, allowMissingHashes, allowOmittedConnection).parts } - fun validate(value: String, allowMissingHashes: Boolean = false): WdttDeepLinkValidation { + fun validate( + value: String, + allowMissingHashes: Boolean = false, + allowOmittedConnection: Boolean = false, + ): WdttDeepLinkValidation { val clean = WdttTransferCodec.extractWdttLink(value) ?: value.trim() val errors = mutableListOf() val warnings = mutableListOf() @@ -250,7 +371,12 @@ object WdttDeepLink { } val host = modernParts?.host?.trim() ?: parts[0].trim() - if (!isValidTunnelHost(host)) { + val password = modernParts?.password?.trim() ?: parts[4].trim() + val connectionOmitted = allowOmittedConnection && + modernParts != null && + host.isBlank() && + password.isBlank() + if (!connectionOmitted && !isValidTunnelHost(host)) { errors += "Адрес сервера пустой или неверный. Нужен домен или IPv4 без https://, порта и пути." } @@ -258,8 +384,7 @@ object WdttDeepLink { val wgPort = validatePort((modernParts?.wgPort ?: parts[2]).toString(), "WG-порт", errors) val localPort = validatePort((modernParts?.localPort ?: parts[3]).toString(), "локальный порт", errors) - val password = modernParts?.password?.trim() ?: parts[4].trim() - if (password.isBlank()) { + if (!connectionOmitted && password.isBlank()) { errors += "Не указан пароль туннеля." } @@ -396,6 +521,7 @@ class SettingsStore(context: Context) { private val TRUSTED_WIFI_SSIDS = stringPreferencesKey("trusted_wifi_ssids") private val TRUSTED_WIFI_WAITING = booleanPreferencesKey("trusted_wifi_waiting") private val TRUSTED_WIFI_WAITING_SSID = stringPreferencesKey("trusted_wifi_waiting_ssid") + private val PAUSE_VPN_DURING_SLEEP = booleanPreferencesKey("pause_vpn_during_sleep") private val WDTT_LINK = stringPreferencesKey("wdtt_link") private val WDTT_LINK_MODE = booleanPreferencesKey("wdtt_link_mode") private val CONNECTION_INPUT_METHOD = stringPreferencesKey("connection_input_method") @@ -460,6 +586,13 @@ class SettingsStore(context: Context) { private val ACCESS_SEVERITY = stringPreferencesKey("access_severity") private val ACCESS_ALLOW_CONNECT = booleanPreferencesKey("access_allow_connect") private val ACCESS_ACTION_AVAILABLE = booleanPreferencesKey("access_action_available") + private val ACCESS_CONTINUATION_AVAILABLE = + booleanPreferencesKey("access_continuation_available") + private val ACCESS_CONTINUATION_EXPIRES_AT = + longPreferencesKey("access_continuation_expires_at") + private val ACCESS_DISMISSIBLE = booleanPreferencesKey("access_dismissible") + private val ACCESS_DISMISSED_MESSAGE = + stringPreferencesKey("access_dismissed_message") private val ACCESS_CHECKED_AT = longPreferencesKey("access_checked_at") private val ACCESS_LAST_ATTEMPT_AT = longPreferencesKey("access_last_attempt_at") private val ACCESS_PROFILE_REVISION = longPreferencesKey("access_profile_revision") @@ -517,6 +650,10 @@ class SettingsStore(context: Context) { // ═══ Captcha Solve Mode ═══ private val VKCALLS_PREFLIGHT = booleanPreferencesKey("vkcalls_preflight") + private val RT_NETWORK = booleanPreferencesKey("rt_network") + private val RT_MASQUE = booleanPreferencesKey("rt_masque") + private val RT_MASQUE_SERVER_BOOTSTRAP = booleanPreferencesKey("rt_masque_server_bootstrap") + private val RT_TURN_SNI = stringPreferencesKey("rt_turn_sni") private val CAPTCHA_MODE = stringPreferencesKey("captcha_mode") // "auto", "wv", or "rjs" private val CAPTCHA_SOLVE_METHOD = stringPreferencesKey("captcha_solve_method") // "manual" or "auto" private val CAPTCHA_WBV_SOLVE_METHOD = stringPreferencesKey("captcha_wbv_solve_method") // "manual" or "auto" @@ -608,6 +745,7 @@ class SettingsStore(context: Context) { ACCESS_DETAIL_VALUE, ACCESS_ACTION_ICON, ACCESS_SEVERITY, + ACCESS_DISMISSED_MESSAGE, ACCESS_LIFECYCLE_DISMISSED_SIGNATURE, PROTOCOL, SNI, @@ -645,6 +783,7 @@ class SettingsStore(context: Context) { CAPTCHA_MODE, CAPTCHA_SOLVE_METHOD, CAPTCHA_WBV_SOLVE_METHOD, + RT_TURN_SNI, WDTT_LINK, CONNECTION_INPUT_METHOD, SELECTED_FINGERPRINT, @@ -667,6 +806,7 @@ class SettingsStore(context: Context) { ACCESS_LAST_ATTEMPT_AT, ACCESS_PROFILE_REVISION, ACCESS_ACTION_LAUNCHED_AT, + ACCESS_CONTINUATION_EXPIRES_AT, ) private val PROFILE_BOOLEAN_KEYS = listOf( MANUAL_PORTS_ENABLED, @@ -677,10 +817,15 @@ class SettingsStore(context: Context) { REMOTE_MANAGED_PROFILE, REMOTE_CARD_DISMISSED, VKCALLS_PREFLIGHT, + RT_NETWORK, + RT_MASQUE, + RT_MASQUE_SERVER_BOOTSTRAP, DETAILED_LOGS, CUSTOM_VK_CREDENTIALS_ENABLED, ACCESS_ALLOW_CONNECT, ACCESS_ACTION_AVAILABLE, + ACCESS_CONTINUATION_AVAILABLE, + ACCESS_DISMISSIBLE, PROFILE_VALUES_SYNC_PENDING, PROFILE_EXCHANGE_ACTION_AVAILABLE, ) @@ -766,6 +911,12 @@ class SettingsStore(context: Context) { profile ), vkCallsPreflight = it[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true, + rtNetwork = it[getProfileKey(RT_NETWORK, profile)] ?: false, + rtMasque = it[getProfileKey(RT_MASQUE, profile)] ?: false, + rtMasqueServerBootstrap = + it[getProfileKey(RT_MASQUE_SERVER_BOOTSTRAP, profile)] ?: false, + rtMasqueServerAccessStatus = deploySshAccessStatus(it, profile), + rtTurnSni = it[getProfileKey(RT_TURN_SNI, profile)] ?: DEFAULT_RT_TURN_SNI, remoteActionKey = readSecret( it, REMOTE_ACTION_KEY_ENCRYPTED, @@ -774,10 +925,7 @@ class SettingsStore(context: Context) { ), remoteActionUrl = it[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty(), remoteManaged = - it[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true || - it[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty().isNotBlank() || - it[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty().isNotBlank() || - it[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].orEmpty().isNotBlank(), + it[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true, cachedRemoteAction = readCachedRemoteAction(it, profile), remoteCardDismissed = it[getProfileKey(REMOTE_CARD_DISMISSED, profile)] ?: false, @@ -793,6 +941,26 @@ class SettingsStore(context: Context) { .flowOn(Dispatchers.IO) .stateIn(storeScope, SharingStarted.Eagerly, null) + val activeTunnelProfileContentUiSnapshot: StateFlow = + activeTunnelProfileUiSnapshot + .map { snapshot -> snapshot?.withoutTransientAccessState() } + .distinctUntilChanged() + .stateIn(storeScope, SharingStarted.Eagerly, null) + + val activeTunnelAccessUiSnapshot: StateFlow = + activeTunnelProfileUiSnapshot + .map { snapshot -> + snapshot?.let { + ActiveTunnelAccessUiSnapshot( + profileIndex = it.profileIndex, + lifecycle = it.accessLifecycle, + dismissedSignature = it.accessLifecycleDismissedSignature, + ) + } + } + .distinctUntilChanged() + .stateIn(storeScope, SharingStarted.Eagerly, null) + init { storeScope.launch { preferencesFlow.first() @@ -820,6 +988,32 @@ class SettingsStore(context: Context) { } } + private fun deploySshAccessStatus( + prefs: Preferences, + profile: Int, + ): SshProfileAccessStatus { + val privateKey = readSecret( + prefs, + DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, + DEPLOY_SSH_PRIVATE_KEY, + profile, + ) + val authMode = prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] + ?.takeIf { it == "password" || it == "key" } + ?: if (privateKey.isNotBlank()) "key" else "password" + return sshProfileAccessStatus( + host = prefs[getProfileKey(DEPLOY_IP, profile)].orEmpty().trim(), + authMode = authMode, + password = readSecret( + prefs, + DEPLOY_PASSWORD_ENCRYPTED, + DEPLOY_PASSWORD, + profile, + ), + privateKey = privateKey, + ) + } + val activeTunnelProfile: Flow = preferencesFlow.map { prefs -> prefs[ACTIVE_TUNNEL_PROFILE]?.takeIf { it in 0 until VPN_PROFILE_COUNT } } @@ -841,6 +1035,9 @@ class SettingsStore(context: Context) { val trustedWifiWaitingSsid: Flow = preferencesFlow.map { sanitizeTrustedWifiSsid(it[TRUSTED_WIFI_WAITING_SSID].orEmpty()) } + val pauseVpnDuringSleep: Flow = preferencesFlow.map { + it[PAUSE_VPN_DURING_SLEEP] ?: false + } val wdttLink: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(WDTT_LINK, profile)] ?: "" @@ -878,10 +1075,7 @@ class SettingsStore(context: Context) { } val remoteManagedProfile: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 - prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true || - prefs[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty().isNotBlank() || - prefs[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty().isNotBlank() || - prefs[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].orEmpty().isNotBlank() + prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true } val activeAccessLifecycle: Flow = preferencesFlow.map { prefs -> val profile = (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1) @@ -1032,6 +1226,18 @@ class SettingsStore(context: Context) { val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true } + val rtNetwork: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(RT_NETWORK, profile)] ?: false + } + val rtMasque: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(RT_MASQUE, profile)] ?: false + } + val rtMasqueServerBootstrap: Flow = preferencesFlow.map { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(RT_MASQUE_SERVER_BOOTSTRAP, profile)] ?: false + } val captchaMode: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto" @@ -1494,6 +1700,12 @@ class SettingsStore(context: Context) { } } + suspend fun savePauseVpnDuringSleep(enabled: Boolean) { + dataStore.edit { prefs -> + prefs[PAUSE_VPN_DURING_SLEEP] = enabled + } + } + suspend fun saveWdttLink(link: String) { dataStore.edit { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 @@ -1506,19 +1718,34 @@ class SettingsStore(context: Context) { } } - suspend fun createWdttDeepLinkApplyPlan(link: String): WdttDeepLinkApplyPlan? { - WdttDeepLink.parse(link, allowMissingHashes = true) ?: return null + suspend fun createWdttDeepLinkApplyPlan( + link: String, + allowOmittedConnection: Boolean = false, + ): WdttDeepLinkApplyPlan? { + WdttDeepLink.parse( + link, + allowMissingHashes = true, + allowOmittedConnection = allowOmittedConnection, + ) ?: return null val cleanLink = link.trim() return appContext.dataStore.data.map { prefs -> val activeProfile = (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1) val freeProfile = (0 until VPN_PROFILE_COUNT).firstOrNull { profile -> - prefs.isTunnelProfileEmpty(profile) + prefs.isTunnelProfileEmpty(profile) && !prefs.hasRemoteAttachment(profile) } + val blockedProfiles = (0 until VPN_PROFILE_COUNT) + .filterTo(mutableSetOf()) { profile -> + prefs.protectsRemoteProfileFromReplacement(profile) + } + val fallbackProfile = (0 until VPN_PROFILE_COUNT) + .firstOrNull { it !in blockedProfiles } + ?: activeProfile WdttDeepLinkApplyPlan( link = cleanLink, - targetProfile = freeProfile ?: activeProfile, + targetProfile = freeProfile ?: fallbackProfile, requiresConfirmation = freeProfile == null, - storeAsLink = false + storeAsLink = false, + blockedProfiles = blockedProfiles, ) }.first() } @@ -1550,6 +1777,12 @@ class SettingsStore(context: Context) { sni = prefs[getProfileKey(SNI, profile)].orEmpty(), protocol = prefs[getProfileKey(PROTOCOL, profile)] ?: "udp", vkCallsPreflight = prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true, + rtNetwork = prefs[getProfileKey(RT_NETWORK, profile)] ?: false, + rtMasque = prefs[getProfileKey(RT_MASQUE, profile)] ?: false, + rtMasqueServerBootstrap = + prefs[getProfileKey(RT_MASQUE_SERVER_BOOTSTRAP, profile)] ?: false, + rtMasqueServerAccessReady = deploySshAccessStatus(prefs, profile).available, + rtTurnSni = prefs[getProfileKey(RT_TURN_SNI, profile)] ?: DEFAULT_RT_TURN_SNI, captchaMode = prefs[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto", captchaSolveMethod = prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto", fingerprint = prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox", @@ -1600,6 +1833,127 @@ class SettingsStore(context: Context) { }.first() } + /** Returns ordinary local slots that can accept one generic remote attachment. */ + suspend fun remoteAttachmentCandidates(): List = + appContext.dataStore.data.map { prefs -> + val names = (0 until VPN_PROFILE_COUNT).map { index -> + prefs[getProfileKey(PROFILE_NAME, index)].orEmpty() + } + (0 until VPN_PROFILE_COUNT).mapNotNull { profile -> + if ( + prefs.hasRemoteAttachment(profile) && + !prefs.canReplaceRemoteAttachment(profile) + ) { + return@mapNotNull null + } + val tunnelModified = !prefs.isTunnelProfileEmpty(profile) + val deployModified = prefs.isDeployProfileModified(profile) + val renamed = prefs[getProfileKey(PROFILE_NAME, profile)].orEmpty().isNotBlank() + val candidate = prefs.completeRemoteAttachmentDocument(profile, names) + RemoteAttachmentCandidate( + profileIndex = profile, + displayName = vpnProfileDisplayName(profile, names), + sourceLabel = candidate?.sourceLabel ?: when { + tunnelModified && deployModified -> "Туннель и Деплой" + tunnelModified -> "Туннель" + deployModified -> "Деплой" + renamed -> "Переименован" + else -> "Пустой профиль" + }, + document = candidate?.document.orEmpty(), + modified = renamed || tunnelModified || deployModified, + ) + } + }.first() + + /** Builds a complete value-free document only when the selected slot is ready to act. */ + suspend fun remoteActionProfileDocument(profileIndex: Int): String? = + preferencesFlow.map { prefs -> + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + val names = (0 until VPN_PROFILE_COUNT).map { index -> + prefs[getProfileKey(PROFILE_NAME, index)].orEmpty() + } + prefs.completeRemoteAttachmentDocument(profile, names)?.document + }.first() + + /** + * Builds a value-free connection document for an explicit generic attachment request. + * Existing remotely managed profiles are deliberately excluded because each local profile + * can own only one bound remote-management capability. + */ + private fun Preferences.hasRemoteAttachment(profile: Int): Boolean = + this[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true || + this[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty().isNotBlank() || + this[getProfileKey(REMOTE_ACTION_URL, profile)].orEmpty().isNotBlank() || + this[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].orEmpty().isNotBlank() + + private fun Preferences.canReplaceRemoteAttachment(profile: Int): Boolean { + val status = readStoredAccessLifecycle(this, profile).status + return canReplaceRemoteAttachment( + hasAttachment = hasRemoteAttachment(profile), + remoteManaged = this[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true, + continuationAvailable = status?.continuationAvailable, + dismissible = status?.dismissible, + ) + } + + private fun Preferences.protectsRemoteProfileFromReplacement(profile: Int): Boolean { + return protectsRemoteProfileFromReplacement( + remoteManagedProfile = + this[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true, + allowConnect = readStoredAccessLifecycle(this, profile).status?.allowConnect, + ) + } + + private fun Preferences.completeRemoteAttachmentDocument( + profile: Int, + names: List, + ): RemoteAttachmentDocument? { + val profileName = vpnProfileTransferName(profile, names) + val maxWorkers = this[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0 + val storedLink = this[getProfileKey(WDTT_LINK, profile)].orEmpty() + val storedParts = if (this[getProfileKey(WDTT_LINK_MODE, profile)] == true) { + WdttDeepLink.parse(storedLink, allowMissingHashes = true) + } else { + null + } + val tunnelParts = storedParts ?: WdttLinkParts( + host = this[getProfileKey(PEER, profile)].orEmpty().trim(), + dtlsPort = this[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000, + wgPort = this[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001, + localPort = this[getProfileKey(LISTEN_PORT, profile)] ?: 9000, + password = readSecret( + this, + CONNECTION_PASSWORD_ENCRYPTED, + CONNECTION_PASSWORD, + profile, + ), + hashes = "", + maxWorkers = maxWorkers, + ) + val deployParts = WdttLinkParts( + host = this[getProfileKey(DEPLOY_IP, profile)].orEmpty().trim(), + dtlsPort = this[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000, + wgPort = this[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001, + localPort = this[getProfileKey(LISTEN_PORT, profile)] ?: 9000, + password = readSecret( + this, + DEPLOY_MAIN_PASSWORD_ENCRYPTED, + DEPLOY_MAIN_PASSWORD, + profile, + ), + hashes = "", + maxWorkers = maxWorkers, + ) + return selectRemoteAttachmentDocument( + tunnelParts = tunnelParts, + deployParts = deployParts, + profileName = profileName, + maxWorkers = maxWorkers, + alreadyManaged = false, + ) + } + suspend fun exportAdminSettings(): String = appContext.dataStore.data.map { prefs -> val profiles = JSONArray() repeat(VPN_PROFILE_COUNT) { profile -> @@ -1640,6 +1994,13 @@ class SettingsStore(context: Context) { put("proxyHost", prefs[getProfileKey(PROXY_HOST, profile)] ?: "127.0.0.1") put("proxyPort", prefs[getProfileKey(PROXY_PORT, profile)] ?: 1080) put("vkCallsPreflight", prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true) + put("rtNetwork", prefs[getProfileKey(RT_NETWORK, profile)] ?: false) + put("rtMasque", prefs[getProfileKey(RT_MASQUE, profile)] ?: false) + put( + "rtMasqueServerBootstrap", + prefs[getProfileKey(RT_MASQUE_SERVER_BOOTSTRAP, profile)] ?: false, + ) + put("rtTurnSni", prefs[getProfileKey(RT_TURN_SNI, profile)] ?: DEFAULT_RT_TURN_SNI) put("captchaMode", prefs[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto") put("captchaSolveMethod", prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto") put("captchaWbvSolveMethod", prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] ?: "auto") @@ -1700,14 +2061,15 @@ class SettingsStore(context: Context) { val importedLinkMode = item.optBoolean("wdttLinkMode") val importedPeer = item.optString("peer") val importedConnectionPassword = item.optString("connectionPassword") - val importedMethod = item.optString("connectionInputMethod") + val requestedImportedMethod = item.optString("connectionInputMethod") .takeIf { it == "link" || it == "manual" } - ?: when { - importedLinkMode && - WdttDeepLink.parse(importedLink, allowMissingHashes = true) != null -> "link" - importedPeer.isNotBlank() && importedConnectionPassword.isNotBlank() -> "manual" - else -> "" - } + val importedMethod = when { + importedLinkMode && + WdttDeepLink.parse(importedLink, allowMissingHashes = true) != null -> "link" + requestedImportedMethod == "manual" -> "manual" + importedPeer.isNotBlank() && importedConnectionPassword.isNotBlank() -> "manual" + else -> "" + } prefs[getProfileKey(WDTT_LINK, profile)] = importedLink prefs[getProfileKey(WDTT_LINK_MODE, profile)] = importedLinkMode val connectionInputMethodKey = getProfileKey(CONNECTION_INPUT_METHOD, profile) @@ -1765,6 +2127,12 @@ class SettingsStore(context: Context) { prefs[getProfileKey(PROXY_HOST, profile)] = item.optString("proxyHost", "127.0.0.1") prefs[getProfileKey(PROXY_PORT, profile)] = item.safePort("proxyPort", 1080) prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] = item.optBoolean("vkCallsPreflight", true) + prefs[getProfileKey(RT_NETWORK, profile)] = item.optBoolean("rtNetwork", false) + prefs[getProfileKey(RT_MASQUE, profile)] = item.optBoolean("rtMasque", false) + prefs[getProfileKey(RT_MASQUE_SERVER_BOOTSTRAP, profile)] = + item.optBoolean("rtMasqueServerBootstrap", false) + prefs[getProfileKey(RT_TURN_SNI, profile)] = + item.optString("rtTurnSni", DEFAULT_RT_TURN_SNI) prefs[getProfileKey(CAPTCHA_MODE, profile)] = item.optString("captchaMode", "auto") prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] = item.optString("captchaSolveMethod", "auto") prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] = item.optString("captchaWbvSolveMethod", "auto") @@ -1812,6 +2180,11 @@ class SettingsStore(context: Context) { val parts = WdttDeepLink.parse(plan.link, allowMissingHashes = true) ?: return null val profile = plan.targetProfile.coerceIn(0, VPN_PROFILE_COUNT - 1) dataStore.edit { prefs -> + if (prefs.protectsRemoteProfileFromReplacement(profile)) { + throw IllegalStateException( + "Действующий готовый профиль нельзя заменить другим подключением." + ) + } prefs.applyWdttDeepLinkParts( plan = plan, parts = parts, @@ -1842,10 +2215,23 @@ class SettingsStore(context: Context) { isBoundUpdate: Boolean, existingProfileRedelivery: Boolean = false, ): WdttDeepLinkApplyResult? { - val parts = WdttDeepLink.parse(plan.link, allowMissingHashes = true) ?: return null + val parts = WdttDeepLink.parse( + plan.link, + allowMissingHashes = true, + allowOmittedConnection = isBoundUpdate && delivery.kind == RemoteDocumentKind.UPDATE, + ) ?: return null val profile = plan.targetProfile.coerceIn(0, VPN_PROFILE_COUNT - 1) var alreadyApplied = false dataStore.edit { prefs -> + if ( + !isBoundUpdate && + !existingProfileRedelivery && + prefs.protectsRemoteProfileFromReplacement(profile) + ) { + throw IllegalStateException( + "Действующий готовый профиль нельзя заменить другим подключением." + ) + } if ( isBoundUpdate && delivery.profileRevision > 0 && @@ -1855,6 +2241,26 @@ class SettingsStore(context: Context) { alreadyApplied = true return@edit } + val preserveExistingValues = delivery.shouldPreserveLocalVkHashes( + existingProfileRedelivery = existingProfileRedelivery, + ) + val existingProfileValues = if (preserveExistingValues) { + existingProfileValuesForRemoteAttachment( + linkMode = prefs[getProfileKey(WDTT_LINK_MODE, profile)] == true, + storedLink = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty(), + manualValues = prefs[getProfileKey(VK_HASHES, profile)].orEmpty(), + ) + } else { + "" + } + val preserveConnectionSettings = + shouldPreserveConnectionSettingsForRemoteUpdate( + isBoundUpdate = isBoundUpdate, + remoteManaged = + prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true, + incomingHost = parts.host, + incomingPassword = parts.password, + ) prefs.applyWdttDeepLinkParts( plan = plan, parts = parts, @@ -1862,10 +2268,21 @@ class SettingsStore(context: Context) { resetRemoteContinuation = !isBoundUpdate, profileMaxWorkers = delivery.profileMaxWorkers, remoteManaged = if (isBoundUpdate) null else true, - preserveVkHashes = delivery.shouldPreserveLocalVkHashes( - existingProfileRedelivery = existingProfileRedelivery, - ), + preserveVkHashes = preserveExistingValues, + preserveConnectionSettings = preserveConnectionSettings, + activateProfile = !shouldRestoreUiAfterBoundUpdate(isBoundUpdate), ) + if ( + preserveConnectionSettings && + prefs[getProfileKey(WDTT_LINK_MODE, profile)] != true && + prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] == "link" + ) { + prefs[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = "manual" + } + if (preserveExistingValues && existingProfileValues.isNotBlank()) { + prefs[getProfileKey(VK_HASHES, profile)] = existingProfileValues + prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = "" + } if (prefs[INTERFACE_ROLE].isNullOrBlank()) { prefs[INTERFACE_ROLE] = "user" if (!prefs.contains(PERMISSION_ONBOARDING_COMPLETE)) { @@ -1874,6 +2291,14 @@ class SettingsStore(context: Context) { } if (delivery.access.available) { prefs.putRemoteAccessCapability(delivery.access, profile) + if ( + existingProfileRedelivery && + existingProfileValues.isNotBlank() && + delivery.access.exchange.submitAvailable && + delivery.access.exchange.submitToken.isNotBlank() + ) { + prefs[getProfileKey(PROFILE_VALUES_SYNC_PENDING, profile)] = true + } delivery.access.initialStatus?.let { status -> prefs.putAccessLifecycleStatus(profile, status) } @@ -1906,6 +2331,59 @@ class SettingsStore(context: Context) { ) } + /** Stores a generic bound capability without taking ownership of the local connection. */ + suspend fun applyRemoteCapabilityAttachment( + profileIndex: Int, + delivery: RemoteDocumentDelivery, + ): Boolean { + if ( + delivery.kind != RemoteDocumentKind.ATTACHMENT || + delivery.binding.isBlank() || + !delivery.access.available || + !delivery.continuation.available + ) { + return false + } + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + dataStore.edit { prefs -> + if (prefs.hasRemoteAttachment(profile)) { + val existingBinding = + prefs[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)].orEmpty() + if (existingBinding != delivery.binding) { + if (!prefs.canReplaceRemoteAttachment(profile)) { + throw IllegalStateException( + "К этому профилю уже привязано другое удалённое разрешение." + ) + } + prefs.clearRemoteCapabilityAttachment(profile) + } + } + prefs[ACTIVE_PROFILE] = profile + val existingValues = existingProfileValuesForRemoteAttachment( + linkMode = prefs[getProfileKey(WDTT_LINK_MODE, profile)] == true, + storedLink = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty(), + manualValues = prefs[getProfileKey(VK_HASHES, profile)].orEmpty(), + ) + prefs.putRemoteAccessCapability(delivery.access, profile) + delivery.access.initialStatus?.let { status -> + prefs.putAccessLifecycleStatus(profile, status) + } + prefs.putRemoteContinuation( + continuation = delivery.continuation, + binding = delivery.binding, + profile = profile, + ) + if ( + existingValues.isNotBlank() && + delivery.access.exchange.submitAvailable && + delivery.access.exchange.submitToken.isNotBlank() + ) { + prefs[getProfileKey(PROFILE_VALUES_SYNC_PENDING, profile)] = true + } + } + return true + } + private fun MutablePreferences.applyWdttDeepLinkParts( plan: WdttDeepLinkApplyPlan, parts: WdttLinkParts, @@ -1914,8 +2392,12 @@ class SettingsStore(context: Context) { profileMaxWorkers: Int?, remoteManaged: Boolean?, preserveVkHashes: Boolean, + preserveConnectionSettings: Boolean = false, + activateProfile: Boolean = true, ) { - this[ACTIVE_PROFILE] = profile + if (activateProfile) { + this[ACTIVE_PROFILE] = profile + } if (resetRemoteContinuation) { putSecret( REMOTE_ACTION_KEY_ENCRYPTED, @@ -1932,38 +2414,41 @@ class SettingsStore(context: Context) { val key = getProfileKey(REMOTE_MANAGED_PROFILE, profile) if (managed) this[key] = true else remove(key) } - val requestedLimit = profileMaxWorkers - ?.takeIf { it >= TUNNEL_WORKERS_PER_GROUP } - ?: parts.maxWorkers - val normalizedLimit = (requestedLimit / TUNNEL_WORKERS_PER_GROUP) * - TUNNEL_WORKERS_PER_GROUP - if (normalizedLimit >= TUNNEL_WORKERS_PER_GROUP) { - this[getProfileKey(PROFILE_MAX_WORKERS, profile)] = - normalizedLimit.coerceAtMost(APP_MAX_WORKERS) - } else { - remove(getProfileKey(PROFILE_MAX_WORKERS, profile)) - } - val importedProfileName = vpnProfileRestorableName(parts.profileName) - if (importedProfileName.isNotBlank()) { - this[getProfileKey(PROFILE_NAME, profile)] = importedProfileName - } - this[getProfileKey(WDTT_LINK_MODE, profile)] = plan.storeAsLink - this[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = "link" - if (plan.storeAsLink) { - this[getProfileKey(WDTT_LINK, profile)] = plan.link - clearManualTunnelFields(profile) - } else { - remove(getProfileKey(WDTT_LINK, profile)) - this[getProfileKey(PEER, profile)] = parts.host - this[getProfileKey(SERVER_DTLS_PORT, profile)] = parts.dtlsPort - this[getProfileKey(SERVER_WG_PORT, profile)] = parts.wgPort - this[getProfileKey(LISTEN_PORT, profile)] = parts.localPort - putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, parts.password, profile) - if (!preserveVkHashes) { - this[getProfileKey(VK_HASHES, profile)] = parts.hashes - this[getProfileKey(SECONDARY_VK_HASH, profile)] = "" + if (!preserveConnectionSettings) { + val requestedLimit = profileMaxWorkers + ?.takeIf { it >= TUNNEL_WORKERS_PER_GROUP } + ?: parts.maxWorkers + val normalizedLimit = (requestedLimit / TUNNEL_WORKERS_PER_GROUP) * + TUNNEL_WORKERS_PER_GROUP + if (normalizedLimit >= TUNNEL_WORKERS_PER_GROUP) { + this[getProfileKey(PROFILE_MAX_WORKERS, profile)] = + normalizedLimit.coerceAtMost(APP_MAX_WORKERS) + } else { + remove(getProfileKey(PROFILE_MAX_WORKERS, profile)) } - this[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = parts.hasNonStandardPorts() + val importedProfileName = vpnProfileRestorableName(parts.profileName) + if (importedProfileName.isNotBlank()) { + this[getProfileKey(PROFILE_NAME, profile)] = importedProfileName + } + this[getProfileKey(WDTT_LINK_MODE, profile)] = plan.storeAsLink + this[getProfileKey(CONNECTION_INPUT_METHOD, profile)] = + if (plan.storeAsLink) "link" else "manual" + if (plan.storeAsLink) { + this[getProfileKey(WDTT_LINK, profile)] = plan.link + clearManualTunnelFields(profile) + } else { + remove(getProfileKey(WDTT_LINK, profile)) + this[getProfileKey(PEER, profile)] = parts.host + this[getProfileKey(SERVER_DTLS_PORT, profile)] = parts.dtlsPort + this[getProfileKey(SERVER_WG_PORT, profile)] = parts.wgPort + this[getProfileKey(LISTEN_PORT, profile)] = parts.localPort + putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, parts.password, profile) + this[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = parts.hasNonStandardPorts() + } + } + if (!preserveVkHashes) { + this[getProfileKey(VK_HASHES, profile)] = parts.hashes + this[getProfileKey(SECONDARY_VK_HASH, profile)] = "" } } @@ -2310,6 +2795,10 @@ class SettingsStore(context: Context) { } suspend fun getOrCreateConnectDeviceId(): String { + preferencesFlow.first()[CONNECT_DEVICE_ID] + ?.trim() + ?.takeIf(DeviceIdentity::valid) + ?.let { return it } val tunnelDeviceId = getOrCreateTunnelDeviceId() var resolved = "" dataStore.edit { prefs -> @@ -2324,6 +2813,10 @@ class SettingsStore(context: Context) { } suspend fun getOrCreateTunnelDeviceId(): String { + preferencesFlow.first()[TUNNEL_DEVICE_ID] + ?.trim() + ?.takeIf(DeviceIdentity::valid) + ?.let { return it } val platformId = android.provider.Settings.Secure.getString( appContext.contentResolver, android.provider.Settings.Secure.ANDROID_ID, @@ -2578,6 +3071,87 @@ class SettingsStore(context: Context) { } } + suspend fun saveRtNetwork(enabled: Boolean, turnSni: String? = null) { + dataStore.edit { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(RT_NETWORK, profile)] = enabled + if (turnSni != null) { + prefs[getProfileKey(RT_TURN_SNI, profile)] = turnSni + } + } + } + + suspend fun saveRtMasque(enabled: Boolean) { + dataStore.edit { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(RT_MASQUE, profile)] = enabled + } + } + + suspend fun saveRtMasqueServerBootstrap(enabled: Boolean) { + dataStore.edit { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(RT_MASQUE_SERVER_BOOTSTRAP, profile)] = + enabled && deploySshAccessStatus(prefs, profile).available + } + } + + internal suspend fun sshConnectionForProfile(profileIndex: Int): SshProfileConnection? { + val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) + return preferencesFlow.map { prefs -> + val host = prefs[getProfileKey(DEPLOY_IP, profile)].orEmpty().trim() + val user = prefs[getProfileKey(DEPLOY_LOGIN, profile)].orEmpty().trim() + val password = readSecret( + prefs, + DEPLOY_PASSWORD_ENCRYPTED, + DEPLOY_PASSWORD, + profile, + ) + val privateKey = readSecret( + prefs, + DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, + DEPLOY_SSH_PRIVATE_KEY, + profile, + ) + val privateKeyPassphrase = readSecret( + prefs, + DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, + DEPLOY_SSH_KEY_PASSPHRASE, + profile, + ) + val mode = prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] + ?.takeIf { it == "password" || it == "key" } + ?: if (privateKey.isNotBlank()) "key" else "password" + val credentials = sshCredentialsForMode( + mode = mode, + password = password, + privateKey = privateKey, + privateKeyPassphrase = privateKeyPassphrase, + ) + val accessStatus = sshProfileAccessStatus( + host = host, + authMode = mode, + password = password, + privateKey = privateKey, + ) + val port = prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] + ?.trim() + ?.toIntOrNull() + ?.takeIf { it in 1..65535 } + ?: 22 + if (!accessStatus.available || !credentials.hasAuthentication) { + null + } else { + SshProfileConnection( + host = host, + user = user, + credentials = credentials, + port = port, + ) + } + }.first() + } + suspend fun saveCaptchaMode(mode: String) { dataStore.edit { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 @@ -2704,7 +3278,9 @@ class SettingsStore(context: Context) { } val methodKey = getProfileKey(CONNECTION_INPUT_METHOD, profile) - if (prefs[methodKey] != "link" && prefs[methodKey] != "manual") { + if (!linkMode && hasManualConnection && prefs[methodKey] == "link") { + prefs[methodKey] = "manual" + } else if (prefs[methodKey] != "link" && prefs[methodKey] != "manual") { when { linkMode && hasStoredLink -> prefs[methodKey] = "link" hasManualConnection -> prefs[methodKey] = "manual" @@ -2737,9 +3313,6 @@ class SettingsStore(context: Context) { } else { this[getProfileKey(REMOTE_DOCUMENT_BINDING, profile)] = binding.trim() } - if (binding.isNotBlank() || continuation.available) { - this[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] = true - } } private fun MutablePreferences.putRemoteAccessCapability( @@ -2770,7 +3343,6 @@ class SettingsStore(context: Context) { this[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)] = capability.binding.trim() putCachedRemoteAction(capability.cachedAction, profile) putProfileExchange(capability.exchange, profile) - this[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] = true } private fun MutablePreferences.putCachedRemoteAction( @@ -2837,6 +3409,17 @@ class SettingsStore(context: Context) { this[getProfileKey(ACCESS_ALLOW_CONNECT, profile)] = status.allowConnect this[getProfileKey(ACCESS_CHECKED_AT, profile)] = status.checkedAtMillis.coerceAtLeast(0) this[getProfileKey(ACCESS_ACTION_AVAILABLE, profile)] = status.actionAvailable + val continuationKey = getProfileKey(ACCESS_CONTINUATION_AVAILABLE, profile) + status.continuationAvailable?.let { this[continuationKey] = it } + ?: remove(continuationKey) + val continuationExpiresKey = getProfileKey(ACCESS_CONTINUATION_EXPIRES_AT, profile) + status.continuationExpiresAtSeconds?.let { + this[continuationExpiresKey] = it.coerceAtLeast(0L) + } ?: remove(continuationExpiresKey) + val dismissibleKey = getProfileKey(ACCESS_DISMISSIBLE, profile) + status.dismissible?.let { this[dismissibleKey] = it } + ?: remove(dismissibleKey) + this[getProfileKey(ACCESS_DISMISSED_MESSAGE, profile)] = status.dismissedMessage this[getProfileKey(ACCESS_ACTION_LABEL, profile)] = status.actionLabel this[getProfileKey(ACCESS_ACTION_MESSAGE, profile)] = status.actionMessage this[getProfileKey(ACCESS_TITLE, profile)] = status.title @@ -2879,6 +3462,19 @@ class SettingsStore(context: Context) { prefs[getProfileKey(ACCESS_DETAIL_VALUE, profile)].orEmpty(), actionIcon = prefs[getProfileKey(ACCESS_ACTION_ICON, profile)].orEmpty(), + continuationAvailable = getProfileKey( + ACCESS_CONTINUATION_AVAILABLE, + profile, + ).let { key -> prefs[key].takeIf { prefs.contains(key) } }, + continuationExpiresAtSeconds = getProfileKey( + ACCESS_CONTINUATION_EXPIRES_AT, + profile, + ).let { key -> prefs[key].takeIf { prefs.contains(key) } }, + dismissible = getProfileKey(ACCESS_DISMISSIBLE, profile).let { key -> + prefs[key].takeIf { prefs.contains(key) } + }, + dismissedMessage = + prefs[getProfileKey(ACCESS_DISMISSED_MESSAGE, profile)].orEmpty(), severity = AccessLifecycleSeverity.parse( prefs[getProfileKey(ACCESS_SEVERITY, profile)].orEmpty(), allowConnect, @@ -2981,6 +3577,10 @@ class SettingsStore(context: Context) { private fun MutablePreferences.clearAccessLifecycleStatus(profile: Int) { remove(getProfileKey(ACCESS_ALLOW_CONNECT, profile)) remove(getProfileKey(ACCESS_ACTION_AVAILABLE, profile)) + remove(getProfileKey(ACCESS_CONTINUATION_AVAILABLE, profile)) + remove(getProfileKey(ACCESS_CONTINUATION_EXPIRES_AT, profile)) + remove(getProfileKey(ACCESS_DISMISSIBLE, profile)) + remove(getProfileKey(ACCESS_DISMISSED_MESSAGE, profile)) remove(getProfileKey(ACCESS_ACTION_LABEL, profile)) remove(getProfileKey(ACCESS_ACTION_MESSAGE, profile)) remove(getProfileKey(ACCESS_TITLE, profile)) @@ -3000,9 +3600,23 @@ class SettingsStore(context: Context) { remove(getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)) remove(getProfileKey(ACCESS_PROFILE_REVISION, profile)) putCachedRemoteAction(CachedRemoteAction.Unavailable, profile) + putProfileExchange(RemoteProfileExchange.Unavailable, profile) clearAccessLifecycleStatus(profile) } + private fun MutablePreferences.clearRemoteCapabilityAttachment(profile: Int) { + putSecret( + REMOTE_ACTION_KEY_ENCRYPTED, + REMOTE_ACTION_KEY, + "", + profile, + ) + remove(getProfileKey(REMOTE_ACTION_URL, profile)) + remove(getProfileKey(REMOTE_DOCUMENT_BINDING, profile)) + remove(getProfileKey(ACCESS_LIFECYCLE_DISMISSED_SIGNATURE, profile)) + clearAccessLifecycle(profile) + } + private fun readSecret( prefs: Preferences, encryptedKey: Preferences.Key, @@ -3044,6 +3658,42 @@ class SettingsStore(context: Context) { return !hasLink && !hasManualData } + private fun Preferences.isDeployProfileModified(profile: Int): Boolean { + val stringValues = listOf( + this[getProfileKey(DEPLOY_IP, profile)].orEmpty(), + this[getProfileKey(DEPLOY_LOGIN, profile)].orEmpty(), + ) + val secretValues = listOf( + readSecret(this, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile), + readSecret( + this, + DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, + DEPLOY_SSH_PRIVATE_KEY, + profile, + ), + readSecret( + this, + DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, + DEPLOY_SSH_KEY_PASSPHRASE, + profile, + ), + readSecret(this, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile), + readSecret(this, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile), + readSecret(this, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile), + ) + val sshPort = this[getProfileKey(DEPLOY_SSH_PORT, profile)].orEmpty().trim() + val dns1 = this[getProfileKey(DEPLOY_DNS1, profile)].orEmpty().trim() + val dns2 = this[getProfileKey(DEPLOY_DNS2, profile)].orEmpty().trim() + val nonDefaultPresentation = + (sshPort.isNotBlank() && sshPort != "22") || + (dns1.isNotBlank() && dns1 != "1.1.1.1") || + (dns2.isNotBlank() && dns2 != "1.0.0.1") || + this[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] == "key" + return stringValues.any(String::isNotBlank) || + secretValues.any(String::isNotBlank) || + nonDefaultPresentation + } + private fun MutablePreferences.clearManualTunnelFields(profile: Int) { remove(getProfileKey(PEER, profile)) remove(getProfileKey(VK_HASHES, profile)) diff --git a/app/src/main/java/com/wdtt/plus/SshAuthentication.kt b/app/src/main/java/com/wdtt/plus/SshAuthentication.kt index 71b9ab1..5c31b13 100644 --- a/app/src/main/java/com/wdtt/plus/SshAuthentication.kt +++ b/app/src/main/java/com/wdtt/plus/SshAuthentication.kt @@ -31,6 +31,54 @@ data class SshCredentials( get() = allowPasswordAuthentication && password.isNotBlank() } +data class SshProfileAccessStatus( + val available: Boolean, + val unavailableReason: String = "", +) + +internal fun sshProfileAccessStatus( + host: String, + authMode: String, + password: String, + privateKey: String, +): SshProfileAccessStatus { + if (host.isBlank()) { + return SshProfileAccessStatus( + available = false, + unavailableReason = "укажите адрес сервера в разделе «Деплой»", + ) + } + if (authMode == "key") { + if (privateKey.isBlank()) { + return SshProfileAccessStatus( + available = false, + unavailableReason = "добавьте приватный SSH-ключ в разделе «Деплой»", + ) + } + sshPrivateKeyIssue(privateKey)?.let { + return SshProfileAccessStatus( + available = false, + unavailableReason = "исправьте приватный SSH-ключ в разделе «Деплой»: ${it.removeSuffix(".")}", + ) + } + return SshProfileAccessStatus(available = true) + } + if (password.isBlank()) { + return SshProfileAccessStatus( + available = false, + unavailableReason = "укажите SSH-пароль в разделе «Деплой»", + ) + } + return SshProfileAccessStatus(available = true) +} + +internal data class SshProfileConnection( + val host: String, + val user: String, + val credentials: SshCredentials, + val port: Int, +) + fun sshCredentialsForMode( mode: String, password: String, diff --git a/app/src/main/java/com/wdtt/plus/TrustedWifi.kt b/app/src/main/java/com/wdtt/plus/TrustedWifi.kt index c9c590d..d329470 100644 --- a/app/src/main/java/com/wdtt/plus/TrustedWifi.kt +++ b/app/src/main/java/com/wdtt/plus/TrustedWifi.kt @@ -127,10 +127,11 @@ internal fun decideTrustedWifiTransition( internal fun shouldKeepTunnelServiceAlive( tunnelRunning: Boolean, + tunnelStarting: Boolean, tunnelPaused: Boolean, trustedWifiWaiting: Boolean, trustedWifiResumeInProgress: Boolean -): Boolean = tunnelRunning || tunnelPaused || trustedWifiWaiting || trustedWifiResumeInProgress +): Boolean = tunnelRunning || tunnelStarting || tunnelPaused || trustedWifiWaiting || trustedWifiResumeInProgress fun sanitizeTrustedWifiSsid(value: String): String { val clean = value diff --git a/app/src/main/java/com/wdtt/plus/TunnelManager.kt b/app/src/main/java/com/wdtt/plus/TunnelManager.kt index 6a02f48..94dc7c9 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelManager.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelManager.kt @@ -59,16 +59,32 @@ internal val ConnectionIssue.isStandaloneUiIssue: Boolean enum class NetworkRecoveryAction { SoftRestart, - RecreateVpn, StopVpn } -internal fun stableNetworkRecoveryAction(completedAttempts: Int): NetworkRecoveryAction = when { - completedAttempts <= 0 -> NetworkRecoveryAction.SoftRestart - completedAttempts == 1 -> NetworkRecoveryAction.RecreateVpn - else -> NetworkRecoveryAction.StopVpn +internal fun stableNetworkRecoveryAction(@Suppress("UNUSED_PARAMETER") completedAttempts: Int): NetworkRecoveryAction = + NetworkRecoveryAction.SoftRestart + +internal fun hasFreshTransportHeartbeat( + running: Boolean, + activeWorkers: Int, + lastActiveAtMs: Long, + lastStatsAtMs: Long, + sinceMs: Long, + nowMs: Long, + freshnessMs: Long = 90_000L, +): Boolean { + if (!running || activeWorkers <= 0) return false + val freshActive = lastActiveAtMs >= sinceMs && nowMs - lastActiveAtMs < freshnessMs + val freshStats = lastStatsAtMs >= sinceMs && nowMs - lastStatsAtMs < freshnessMs + return freshActive || freshStats } +internal fun shouldObserveTunnelHealth( + deviceInteractive: Boolean, + wakeRecoveryGraceActive: Boolean, +): Boolean = deviceInteractive && !wakeRecoveryGraceActive + enum class TunnelStopReason(val displayText: String) { User("отключено пользователем"), VpnSlotTransferred("VPN-слот передан другому приложению"), @@ -150,6 +166,287 @@ internal fun isExpiredAccessAuthFailure(line: String): Boolean = internal const val WRAP_HANDSHAKE_RETRY_MESSAGE = "[WRAP] Отдельные каналы не ответили, выполняется повтор" +internal const val RT_MASQUE_CONFIG_FILE_NAME = "rt-masque-v1.json" + +internal fun shouldUseRtMasque(rtNetwork: Boolean, rtMasque: Boolean): Boolean = + rtNetwork && rtMasque + +internal fun shouldUseRtMasqueServerBootstrap( + rtNetwork: Boolean, + rtMasque: Boolean, + serverBootstrap: Boolean, +): Boolean = rtNetwork && rtMasque && serverBootstrap + +internal data class MasqueLogPresentation( + val key: String, + val message: String, + val warning: Boolean = false, + val startsDtls: Boolean = false, +) + +internal fun classifyMasqueLog(line: String): MasqueLogPresentation? { + val hasTag = line.contains("[MASQUE]", ignoreCase = true) + val mentionsSelectedPath = line.contains("внутри MASQUE", ignoreCase = true) + val mentionsUdpFallback = line.contains("после MASQUE", ignoreCase = true) + if (!hasTag && !mentionsSelectedPath && !mentionsUdpFallback) return null + val text = if (hasTag) line.substringAfter("[MASQUE]", line).trim() else line.trim() + val h2 = text.contains("HTTP/2", ignoreCase = true) + val h3 = text.contains("HTTP/3", ignoreCase = true) + val registrationProblem = + text.contains("конфигурация WARP повреждена", ignoreCase = true) || + text.contains("публичный ключ WARP endpoint не совпал", ignoreCase = true) || + text.contains("access denied", ignoreCase = true) + val httpStatus = Regex("HTTP\\s+(\\d{3})", RegexOption.IGNORE_CASE) + .find(text) + ?.groupValues + ?.getOrNull(1) + ?.toIntOrNull() + val apiCode = Regex("code=(\\d+)", RegexOption.IGNORE_CASE) + .find(text) + ?.groupValues + ?.getOrNull(1) + val enrollmentStage = when { + text.contains("этап 1/4", ignoreCase = true) || + text.contains("регистрация WARP:", ignoreCase = true) -> + "создания устройства WARP (этап 1/4)" + text.contains("этап 2/4", ignoreCase = true) || + text.contains("enrollment WARP", ignoreCase = true) -> + "включения MASQUE в Cloudflare (этап 2/4)" + text.contains("этап 3/4", ignoreCase = true) || + text.contains("неполную конфигурацию", ignoreCase = true) -> + "проверки конфигурации MASQUE (этап 3/4)" + text.contains("этап 4/4", ignoreCase = true) || + text.contains("сохранение регистрации", ignoreCase = true) -> + "сохранения регистрации на устройстве (этап 4/4)" + else -> "подготовки WARP" + } + val pathFailureReason = when { + text.contains("timeout", ignoreCase = true) || + text.contains("deadline exceeded", ignoreCase = true) || + text.contains("тайм-аут", ignoreCase = true) -> "таймаут" + text.contains("refused", ignoreCase = true) -> "соединение отклонено" + text.contains("unreachable", ignoreCase = true) || + text.contains("no route", ignoreCase = true) -> "маршрут недоступен" + text.contains("lookup", ignoreCase = true) || + text.contains("DNS", ignoreCase = true) -> "ошибка DNS внутри WARP" + text.contains("handshake", ignoreCase = true) -> "ошибка рукопожатия" + else -> "CONNECT-IP или TURN не ответил" + } + val enrollmentFailureReason = when { + httpStatus == 429 -> "Cloudflare ограничил частоту регистраций (HTTP 429)" + httpStatus == 403 -> "Cloudflare отклонил запрос (HTTP 403)" + httpStatus != null && httpStatus >= 500 -> "временная ошибка Cloudflare (HTTP $httpStatus)" + text.contains("тайм-аут TLS-рукопожатия", ignoreCase = true) -> + "TLS-рукопожатие с API Cloudflare не завершилось после успешного TCP/443" + text.contains("не прислал заголовки ответа", ignoreCase = true) || + text.contains("не прислал ответ", ignoreCase = true) -> + "Cloudflare не ответил на уже отправленный HTTPS-запрос" + text.contains("тайм-аут подключения TCP/443", ignoreCase = true) -> + "не установилось TCP/443-соединение с API Cloudflare" + text.contains("тайм-аут системного DNS", ignoreCase = true) -> + "системный DNS Android не ответил для API Cloudflare" + text.contains("пустой ответ", ignoreCase = true) -> "Cloudflare вернул пустой ответ" + text.contains("не в формате JSON", ignoreCase = true) -> "Cloudflare вернул ответ не в формате JSON" + text.contains("структура JSON-ответа", ignoreCase = true) -> "формат ответа Cloudflare изменился" + text.contains("чтение ответа", ignoreCase = true) -> "ответ Cloudflare оборвался при чтении" + httpStatus != null -> "Cloudflare вернул HTTP $httpStatus" + text.contains("lookup", ignoreCase = true) || + text.contains("DNS", ignoreCase = true) -> "не разрешился адрес API Cloudflare" + text.contains("timeout", ignoreCase = true) || + text.contains("deadline exceeded", ignoreCase = true) || + text.contains("тайм-аут", ignoreCase = true) -> "таймаут обращения к API Cloudflare" + text.contains("certificate", ignoreCase = true) || + text.contains("x509", ignoreCase = true) -> "ошибка проверки TLS-сертификата API Cloudflare" + text.contains("connection refused", ignoreCase = true) -> "соединение с API Cloudflare отклонено" + text.contains("не вернула", ignoreCase = true) || + text.contains("не вернул", ignoreCase = true) -> "Cloudflare вернул неполную конфигурацию" + else -> "запрос к API Cloudflare завершился ошибкой" + } + val rawEnrollmentFailure = text + .substringAfter("фоновая подготовка WARP пока не выполнена:", "") + .trim() + .replaceFirst(Regex("^этап\\s+\\d/4,[^:]{0,160}:\\s*", RegexOption.IGNORE_CASE), "") + .replace(Regex("(?i)Bearer\\s+\\S+"), "Bearer [скрыт]") + .replace(Regex("https?://\\S+", RegexOption.IGNORE_CASE), "[URL скрыт]") + .replace(Regex("[\\r\\n\\t]+"), " ") + .trim() + .take(260) + val enrollmentTechnicalDetail = buildList { + if (apiCode != null) add("код API $apiCode") + when { + text.contains("ошибка DNS для", ignoreCase = true) -> + add(text.substringAfter("ошибка DNS для", "").trim().take(180).let { "DNS: $it" }) + text.contains("сетевая ошибка:", ignoreCase = true) -> + add(text.substringAfter("сетевая ошибка:", "").trim().take(180)) + text.contains("не вернул ID или токен", ignoreCase = true) -> + add("в ответе отсутствует ID или токен") + text.contains("не вернул адрес MASQUE", ignoreCase = true) -> + add("в ответе отсутствует адрес MASQUE") + text.contains("неполная конфигурация", ignoreCase = true) -> + add("в ответе отсутствует обязательное поле") + } + if (rawEnrollmentFailure.isNotBlank()) add(rawEnrollmentFailure) + }.filter { it.isNotBlank() }.distinct().joinToString(", ") + .let { if (it.isBlank()) "" else "; подробность: $it" } + + return when { + registrationProblem -> MasqueLogPresentation( + key = "masque_registration_invalid", + message = "[MASQUE] Регистрация WARP повреждена или отклонена. Остановите VPN и используйте «Сбросить регистрацию WARP» в справке MASQUE.", + warning = true, + ) + text.contains("фоновая подготовка WARP пока не выполнена", ignoreCase = true) -> + MasqueLogPresentation( + key = "masque_enrollment_pending", + message = "[MASQUE] Ошибка на этапе $enrollmentStage: $enrollmentFailureReason$enrollmentTechnicalDetail. " + + "Регистрация не сохранена; прямые пути продолжают работу. Для новой попытки остановите и снова запустите VPN.", + warning = true, + ) + text.contains("повторяем через TLS 1.2/HTTP 1.1", ignoreCase = true) && + text.contains("разделённым ClientHello", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_tls_fallback", + "[MASQUE] API Cloudflare: обычный TLS не ответил; пробуем TLS 1.2/HTTP 1.1 с разделённым ClientHello...", + warning = true, + ) + text.contains("данные устройства ещё не отправлялись", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_retry", + "[MASQUE] API Cloudflare не завершил соединение до отправки данных. Выполняем одну безопасную повторную попытку через системную сеть Android...", + warning = true, + ) + text.contains("прямые HTTPS-пути недоступны", ignoreCase = true) && + text.contains("выход через сервер профиля", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_server_retry", + "[MASQUE] Прямой API Cloudflare не ответил; пробуем регистрацию через сервер профиля...", + warning = true, + ) + text.contains("выход через сервер профиля доступен", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_server_connected", + "[MASQUE] Защищённый выход через сервер профиля установлен ✓", + ) + text.contains("выход через сервер профиля сработал", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_server_ok", + "[MASQUE] API Cloudflare доступен через сервер профиля ✓", + ) + text.contains("локальный выход для регистрации WARP отклонён", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_server_invalid", + "[MASQUE] Локальный выход регистрации отклонён как небезопасный; продолжаем прямые попытки", + warning = true, + ) + text.contains("системный DNS Android разрешил адрес", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_dns", + "[MASQUE] API Cloudflare: системный DNS Android разрешил адрес ✓", + ) + text.contains("TCP/443 через системную сеть Android установлен", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_tcp", + "[MASQUE] API Cloudflare: TCP/443 через системную сеть Android установлен ✓", + ) + text.contains("TLS-рукопожатие завершено", ignoreCase = true) && + text.contains("HTTP/1.1", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_tls_fallback_ok", + "[MASQUE] API Cloudflare: резерв TLS 1.2/HTTP 1.1 установлен ✓", + ) + text.contains("TLS-рукопожатие завершено", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_tls", + "[MASQUE] API Cloudflare: защищённое TLS-соединение установлено ✓", + ) + text.contains("HTTP-запрос отправлен", ignoreCase = true) && + text.contains("ожидаем ответ", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_request", + "[MASQUE] API Cloudflare: HTTPS-запрос отправлен, ожидаем ответ...", + ) + text.contains("получен первый байт HTTP-ответа", ignoreCase = true) -> + MasqueLogPresentation( + "masque_api_response", + "[MASQUE] API Cloudflare: получен HTTP-ответ ✓", + ) + text.contains("регистрация начата:", ignoreCase = true) || + text.contains("первый запуск: регистрируем", ignoreCase = true) -> + MasqueLogPresentation( + "masque_enrollment_start", + "[MASQUE] Этап 1/4: создаём отдельное устройство WARP в Cloudflare...", + ) + text.contains("этап 1/4 завершён", ignoreCase = true) || + text.contains("базовая регистрация WARP создана", ignoreCase = true) -> + MasqueLogPresentation( + "masque_account_created", + "[MASQUE] Этап 1/4 завершён: устройство WARP создано. Этап 2/4: включаем для него MASQUE...", + ) + text.contains("этап 2/4 завершён", ignoreCase = true) || + text.contains("Cloudflare принял ключ MASQUE", ignoreCase = true) -> + MasqueLogPresentation( + "masque_key_accepted", + "[MASQUE] Этап 2/4 завершён: Cloudflare принял ключ MASQUE. Этап 3/4: проверяем адреса и ключ сервера...", + ) + text.contains("этап 3/4 завершён", ignoreCase = true) -> + MasqueLogPresentation( + "masque_config_valid", + "[MASQUE] Этап 3/4 завершён: конфигурация MASQUE корректна ✓", + ) + text.contains("этап 4/4 — сохраняем", ignoreCase = true) -> + MasqueLogPresentation( + "masque_enrollment_saving", + "[MASQUE] Этап 4/4: сохраняем регистрацию только в приватном хранилище приложения...", + ) + text.contains("этап 4/4 завершён", ignoreCase = true) || + text.contains("enrollment WARP сохранён", ignoreCase = true) -> + MasqueLogPresentation( + "masque_enrollment_saved", + "[MASQUE] Этап 4/4 завершён: регистрация WARP сохранена в приватном хранилище ✓", + ) + text.contains("конфигурация WARP подготовлена", ignoreCase = true) -> + MasqueLogPresentation("masque_config_ready", "[MASQUE] Сохранённая регистрация WARP готова ✓") + text.contains("Включён резерв", ignoreCase = true) -> + MasqueLogPresentation("masque_enabled", "[MASQUE] Резерв включён: HTTP/2 (TCP/443), затем HTTP/3 (QUIC/443)") + text.contains("Прямые TCP/TLS-пути", ignoreCase = true) -> + MasqueLogPresentation("masque_fallback_start", "[MASQUE] Прямые TCP/TLS-пути РТ не ответили — запускаем CONNECT-IP до попытки UDP") + text.contains("Последний резерв после MASQUE", ignoreCase = true) -> + MasqueLogPresentation( + "masque_udp_fallback", + "[MASQUE] HTTP/2 и HTTP/3 не дали рабочий TURN — пробуем прямой UDP последним резервом", + warning = true, + ) + text.contains("Relay:", ignoreCase = true) && h2 -> + MasqueLogPresentation("masque_selected", "[MASQUE] Выбран HTTP/2 через TCP/443 ✓", startsDtls = true) + text.contains("Relay:", ignoreCase = true) && h3 -> + MasqueLogPresentation("masque_selected", "[MASQUE] Выбран HTTP/3 через QUIC/443 ✓", startsDtls = true) + text.contains("CONNECT-IP HTTP/2 установлен", ignoreCase = true) -> + MasqueLogPresentation("masque_h2_connected", "[MASQUE] CONNECT-IP HTTP/2 через TCP/443 установлен ✓") + text.contains("CONNECT-IP HTTP/3 установлен", ignoreCase = true) -> + MasqueLogPresentation("masque_h3_connected", "[MASQUE] CONNECT-IP HTTP/3 через QUIC/443 установлен ✓") + text.contains("устанавливаем CONNECT-IP", ignoreCase = true) && h2 -> + MasqueLogPresentation("masque_h2_connecting", "[MASQUE] Подключаем CONNECT-IP HTTP/2 через TCP/443...") + text.contains("устанавливаем CONNECT-IP", ignoreCase = true) && h3 -> + MasqueLogPresentation("masque_h3_connecting", "[MASQUE] Подключаем CONNECT-IP HTTP/3 через QUIC/443...") + text.contains("Пробуем TURN", ignoreCase = true) && h2 -> + MasqueLogPresentation("masque_h2_turn", "[MASQUE] Проверяем TURN внутри HTTP/2...") + text.contains("Пробуем TURN", ignoreCase = true) && h3 -> + MasqueLogPresentation("masque_h3_turn", "[MASQUE] Проверяем TURN внутри HTTP/3...") + (text.contains("не сработал", ignoreCase = true) || text.contains("потерян", ignoreCase = true)) && h2 -> + MasqueLogPresentation( + "masque_h2_failed", + "[MASQUE] Путь HTTP/2/TCP/443 не сработал ($pathFailureReason); проверяем другие TURN-адреса и HTTP/3", + warning = true, + ) + (text.contains("не сработал", ignoreCase = true) || text.contains("потерян", ignoreCase = true)) && h3 -> + MasqueLogPresentation( + "masque_h3_failed", + "[MASQUE] Путь HTTP/3/QUIC/443 не сработал ($pathFailureReason); проверяем другие TURN-адреса и прямой UDP", + warning = true, + ) + else -> MasqueLogPresentation("masque_status", "[MASQUE] $text") + } +} const val AMNEZIA_STYLE_RECOVERY = true private const val RECOVERABLE_NETWORK_GRACE_MS = 90_000L @@ -159,6 +456,7 @@ private const val STABLE_RECOVERY_GRACE_MS = 10 * 60_000L private const val STABLE_RECOVERY_RETRY_MS = 10 * 60_000L private const val STABLE_ZERO_WORKERS_GRACE_MS = 15 * 60_000L private const val STAGNANT_ACTIVE_TRAFFIC_MS = 20 * 60_000L +private const val WAKE_RECOVERY_GRACE_MS = 90_000L object TunnelManager { // 100% защита от утечек: единый управляемый глобальный Scope @@ -168,6 +466,7 @@ object TunnelManager { private var readerJob: Job? = null private var watchdogJob: Job? = null private var wgHelper: WireGuardHelper? = null + private var warpApiSshRelay: WarpApiSshRelay? = null private val startStopMutex = kotlinx.coroutines.sync.Mutex() @@ -198,8 +497,10 @@ object TunnelManager { private var lastSoftRestartAtMs = 0L private var lastUnderlyingNetworkChangeAtMs = 0L private var networkTransitionGraceUntilMs = 0L + private var wakeRecoveryGraceUntilMs = 0L private var lastNetworkSettleRestartAtMs = 0L private var lastStableNetworkIssueLogAtMs = 0L + private val sessionTraffic = TunnelSessionTrafficAccumulator() private val captchaSolveRequestId = AtomicLong(0) private val activeCaptchaSolveRequests = ConcurrentHashMap.newKeySet() @@ -381,6 +682,7 @@ object TunnelManager { fun pollNetworkRecoveryAction(now: Long = System.currentTimeMillis()): NetworkRecoveryAction? { if (!running.value) return null + if (isWakeRecoveryGraceActive(now)) return null if (AMNEZIA_STYLE_RECOVERY) { return pollStableNetworkRecoveryAction(now) } @@ -495,13 +797,9 @@ object TunnelManager { "Восстанавливаю транспорт", "Сеть долго не подаёт признаков жизни. Выполняется тихая попытка без пересоздания VPN." ) - NetworkRecoveryAction.RecreateVpn -> setConnectionIssue( - "Пересоздаю VPN", - "Тихое восстановление не помогло. Системный VPN-интерфейс будет пересоздан один раз." - ) NetworkRecoveryAction.StopVpn -> setConnectionIssue( "VPN остановлен, чтобы вернуть интернет", - "Пересоздание VPN не восстановило связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета." + "Повторные попытки не восстановили связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета." ) } return action @@ -660,6 +958,7 @@ object TunnelManager { if (!preserveLogs) clearLogs() config.value = null stats.value = "Ожидание данных..." + sessionTraffic.reset() floodCount = 0 mismatchCount = 0 refusedCount = 0 @@ -671,6 +970,7 @@ object TunnelManager { resetStatsLivenessState() lastUnderlyingNetworkChangeAtMs = 0L networkTransitionGraceUntilMs = 0L + wakeRecoveryGraceUntilMs = 0L lastNetworkSettleRestartAtMs = 0L activeHashIndex = 0 currentParams = params @@ -765,6 +1065,64 @@ object TunnelManager { // Go boolean flags must use -flag=value. A separate "false" value // stops flag.Parse and silently drops every argument after it. cmd.add("-vkcalls-preflight=${params.vkCallsPreflight}") + cmd.add("-turn-stream-first=${params.rtNetwork}") + if (params.rtNetwork) { + val turnSni = normalizeRtTurnSni(params.rtTurnSni) + if (turnSni != null) { + cmd.add("-turn-sni") + cmd.add(turnSni) + } else if (params.rtTurnSni.isNotBlank()) { + updateWarningLog( + "rt_sni_invalid", + "[TURN] SNI режима «Сеть РТ» имеет неверный формат; запускаем TCP/TLS без подмены SNI", + 20, + ) + } + } + val useRtMasque = shouldUseRtMasque(params.rtNetwork, params.rtMasque) + cmd.add("-rt-masque=$useRtMasque") + if (useRtMasque) { + val masqueConfig = File(appContext.filesDir, RT_MASQUE_CONFIG_FILE_NAME) + cmd.add("-rt-masque-config") + cmd.add(masqueConfig.absolutePath) + cmd.add("-rt-masque-accept-tos=true") + if ( + !masqueConfig.exists() && + shouldUseRtMasqueServerBootstrap( + rtNetwork = params.rtNetwork, + rtMasque = params.rtMasque, + serverBootstrap = params.rtMasqueServerBootstrap, + ) + ) { + closeWarpApiSshRelay() + when (val relayResult = WarpApiSshRelay.start(appContext, params.profileIndex)) { + is WarpApiSshRelayStartResult.Ready -> { + warpApiSshRelay = relayResult.relay + cmd.add("-warp-api-relay") + cmd.add(relayResult.relay.loopbackAddress) + updateLog( + "masque_server_bootstrap_ready", + "[MASQUE] Для первой регистрации подготовлен защищённый выход через сервер профиля ✓", + 4, + ) + } + WarpApiSshRelayStartResult.MissingProfileAccess -> { + updateWarningLog( + "masque_server_bootstrap_missing", + "[MASQUE] «Через сервер» недоступен: в «Деплой» нет адреса сервера или выбранного SSH-доступа (пароль/приватный ключ); пробуем прямую регистрацию", + 20, + ) + } + is WarpApiSshRelayStartResult.Failed -> { + updateWarningLog( + "masque_server_bootstrap_failed", + "[MASQUE] Выход через сервер не подготовлен: ${relayResult.message}; пробуем прямую регистрацию", + 20, + ) + } + } + } + } val androidId = SettingsStore(appContext).getOrCreateTunnelDeviceId() cmd.add("-device-id") @@ -811,12 +1169,26 @@ object TunnelManager { startWatchdog(appContext, params) } catch (e: Exception) { + closeWarpApiSshRelay() val message = e.readableMessage() updateLog("critical_start_error", "Критическая ошибка запуска: $message", 99, true) setConnectionIssue("Не удалось запустить подключение", "Проверьте настройки туннеля и попробуйте подключиться снова. Причина: $message") e.printStackTrace() - running.value = false - currentParams = null + if (isSwitching && currentParams != null) { + // При автоматическом восстановлении не превращаем неудачную + // попытку в окончательную остановку: служба оставляет параметры + // сессии и сможет повторить восстановление позже. + running.value = true + processStartedAtMs = System.currentTimeMillis() + updateWarningLog( + "vpn_recovery_retry_pending", + "[VPN] Автоматическое восстановление пока не завершилось; сохраняем сессию и повторим попытку позже.", + 50, + ) + } else { + running.value = false + currentParams = null + } clearTransition() } finally { if (!isSwitching) clearTransition() @@ -1089,7 +1461,8 @@ object TunnelManager { } if (lineTrim.contains("[СТАТИСТИКА]")) { - val msg = lineTrim.substringAfter("[СТАТИСТИКА]").trim() + val rawStats = lineTrim.substringAfter("[СТАТИСТИКА]").trim() + val msg = sessionTraffic.accumulate(rawStats) stats.value = msg lastStatsAtMs = now @@ -1155,7 +1528,22 @@ object TunnelManager { } val workerRetry = classifyRecoverableWorkerRetry(lineTrim, activeWorkers.value) + val masquePresentation = classifyMasqueLog(lineTrim) when { + masquePresentation != null -> { + val presentation = masquePresentation + if (presentation.warning) { + updateWarningLog(presentation.key, presentation.message, 20) + } else { + updateLog(presentation.key, presentation.message, 2, false) + } + if (presentation.startsDtls) { + updateLog("dtls_start", "[DTLS] Рукопожатие (Handshake)...", 1, false) + } + if (presentation.key == "masque_enrollment_saved") { + closeWarpApiSshRelay() + } + } workerRetry != null -> { if (activeWorkers.value <= 0) { when (workerRetry.first) { @@ -1352,10 +1740,23 @@ object TunnelManager { lineTrim.contains("[TURN]") -> { val text = lineTrim.substringAfter("[TURN]").trim() when { + text.contains("Креды уже заменены", true) -> + updateLog( + "turn_creds_current", + "[TURN] Используем уже обновлённые данные без повторного запроса к VK", + 5, + false + ) text.contains("Креды обновлены", true) -> updateLog("turn_creds_refreshed", "[TURN] Креды обновлены, продолжаем подключение", 2, false) text.contains("Креды уже обновлялись", true) -> updateLog("turn_creds_wait", "[TURN] Ждём перед повторным обновлением кредов", 2, false) + text.contains("временно ограничил новые allocation", true) -> + updateWarningLog( + "turn_capacity_retry", + "[TURN] Узел временно ограничил новые каналы; повторяем без обновления данных VK", + 20 + ) text.contains("неполный ответ", true) -> updateWarningLog("turn_allocate_retry", "[TURN] Неполный Allocate-ответ, обновляем данные и повторяем", 20) text.contains("Ошибка allocation/кредов", true) -> @@ -1560,8 +1961,23 @@ object TunnelManager { watchdogJob = scope.launch { var zeroWorkersSince = 0L var processDeadSince = 0L + val powerManager = context.getSystemService(Context.POWER_SERVICE) as? android.os.PowerManager delay(10_000) while (isActive && running.value) { + if ( + !shouldObserveTunnelHealth( + deviceInteractive = powerManager?.isInteractive != false, + wakeRecoveryGraceActive = isWakeRecoveryGraceActive(), + ) + ) { + // Сон и первые секунды после пробуждения не входят в длительность + // неисправности. Иначе старый таймер срабатывает сразу при включении + // экрана и без необходимости перезапускает транспорт. + zeroWorkersSince = 0L + processDeadSince = 0L + delay(10_000) + continue + } val proc = process if (proc == null || !proc.isAlive) { val now = System.currentTimeMillis() @@ -1599,7 +2015,12 @@ object TunnelManager { lastActiveAtMs == 0L && !isCaptchaInProgress() ) { - handleCriticalError("\uD83D\uDD12 Неверный пароль подключения или несовместимый WRAP. Воркеры остановлены.") + val wrapStopMessage = if (currentParams?.rtNetwork == true) { + "\uD83C\uDF10 Через сеть РТ не получен ответ WRAP. Обычно сеть не пропустила выбранный TURN/SNI; реже причина в пароле или совместимости WRAP. Воркеры остановлены." + } else { + "\uD83D\uDD12 Неверный пароль подключения или несовместимый WRAP. Воркеры остановлены." + } + handleCriticalError(wrapStopMessage) return@launch } else if ( System.currentTimeMillis() - zeroWorkersSince > (if (AMNEZIA_STYLE_RECOVERY) STABLE_ZERO_WORKERS_GRACE_MS else 3 * 60_000L) && @@ -1655,6 +2076,7 @@ object TunnelManager { updateLog("network_restart", reason, 50, false) activeWorkers.value = 0 resetStatsLivenessState() + sessionTraffic.noteTransportRestart() val restartDelayMs = transportRecoveryPolicy( params.managedConfigFirstStart ).processRestartDelayMs @@ -1715,6 +2137,7 @@ object TunnelManager { startStopMutex.lock() try { if (currentParams !== params || !running.value) return@launch + sessionTraffic.noteTransportRestart() killProcess() delay(250L) } finally { @@ -1761,6 +2184,30 @@ object TunnelManager { fun isNetworkTransitionGraceActive(now: Long = System.currentTimeMillis()): Boolean = now < networkTransitionGraceUntilMs + fun isWakeRecoveryGraceActive(now: Long = System.currentTimeMillis()): Boolean = + now < wakeRecoveryGraceUntilMs + + fun noteDeviceSleepStarted() { + if (!running.value) return + // Ошибки, возникшие до или во время сна, нельзя переносить в решение о + // восстановлении после пробуждения: сеть и вывод статистики в этот период + // могут штатно приостанавливаться Android. + wakeRecoveryGraceUntilMs = 0L + } + + fun noteDeviceWakeStarted(now: Long = System.currentTimeMillis()) { + if (!running.value) return + resetNetworkRecoveryState() + wakeRecoveryGraceUntilMs = now + WAKE_RECOVERY_GRACE_MS + networkTransitionGraceUntilMs = maxOf(networkTransitionGraceUntilMs, wakeRecoveryGraceUntilMs) + updateLog( + "wake_stabilization", + "[СОН] Устройство проснулось; даём текущему VPN восстановить активность без перезапуска.", + 20, + false, + ) + } + fun connectionIssueTitleForNotification(now: Long = System.currentTimeMillis()): String? { val issue = connectionIssue.value ?: return null if (!running.value) return null @@ -1788,10 +2235,14 @@ object TunnelManager { } fun hasFreshTunnelActivitySince(sinceMs: Long, now: Long = System.currentTimeMillis()): Boolean { - if (!running.value || activeWorkers.value <= 0) return false - val freshActive = lastActiveAtMs >= sinceMs && now - lastActiveAtMs < 90_000L - val freshStats = lastStatsAtMs >= sinceMs && now - lastStatsAtMs < 90_000L - return (freshActive || freshStats) && !isStatsTrafficStagnant(now) + return hasFreshTransportHeartbeat( + running = running.value, + activeWorkers = activeWorkers.value, + lastActiveAtMs = lastActiveAtMs, + lastStatsAtMs = lastStatsAtMs, + sinceMs = sinceMs, + nowMs = now, + ) } fun noteWakeRescueStarted() { @@ -1812,6 +2263,41 @@ object TunnelManager { ) } + fun noteWakeRescueDeferred() { + updateWarningLog( + "wake_rescue_deferred", + "[СОН] После пробуждения транспорт ещё не подал свежих признаков жизни. VPN-интерфейс оставлен активным; продолжаем наблюдение без аварийного отключения.", + 50, + ) + } + + fun noteSleepVpnPaused() { + updateLog( + "sleep_vpn_paused", + "[СОН] VPN временно отключён для экономии батареи; интернет телефона идёт напрямую.", + 20, + false, + ) + } + + fun noteSleepVpnPauseFailed() { + updateLog( + "sleep_vpn_pause_failed", + "[СОН] Режим экономии не применён: системный VPN-интерфейс не удалось безопасно остановить.", + 50, + false, + ) + } + + fun noteSleepVpnResumed() { + updateLog( + "sleep_vpn_resumed", + "[СОН] Экран включён; возобновляем VPN с сохранёнными настройками.", + 20, + false, + ) + } + fun noteWakeRescueReconnect() { updateWarningLog( "wake_rescue_reconnect", @@ -1837,15 +2323,16 @@ object TunnelManager { fun recreateVpnTunnel() { val params = currentParams ?: return val context = lastContext ?: return - updateWarningLog("network_full_restart", "[СЕТЬ] Мягкие попытки не помогли, пересоздаём VPN", 50) + updateWarningLog("network_full_restart", "[VPN] Android потерял системный VPN-интерфейс, создаём его заново", 50) scope.launch { withContext(Dispatchers.Main) { wgHelper?.stopTunnel() } + sessionTraffic.noteTransportRestart() killProcess() activeWorkers.value = 0 delay(2500) - if (currentParams != null) { + if (currentParams === params && running.value) { start(context, params, isSwitching = true) } } @@ -1867,6 +2354,7 @@ object TunnelManager { fun pause() { if (!running.value) return + sessionTraffic.noteTransportRestart() killProcess() activeWorkers.value = 0 resetStatsLivenessState() @@ -1904,9 +2392,18 @@ object TunnelManager { try { proc.waitFor(1000, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {} } } + closeWarpApiSshRelay() + } + + @Synchronized + private fun closeWarpApiSshRelay() { + val relay = warpApiSshRelay + warpApiSshRelay = null + relay?.close() } private fun stopOnlyProcess() { + sessionTraffic.noteTransportRestart() killProcess() running.value = false } @@ -1918,29 +2415,13 @@ object TunnelManager { updateLog("stats", "[СТАТИСТИКА] $stoppedStats", 3, false) } - fun onWireGuardStoppedExternally() { - noteStopRequested() - scope.launch { - startStopMutex.lock() - try { - if (!running.value) return@launch - updateLog( - "vpn_released", - "[VPN] Android отключил WDTT Plus VPN или передал VPN другому приложению. Транспорт остановлен.", - 50, - false - ) - killProcess() - running.value = false - markLogSessionStopped(TunnelStopReason.VpnStoppedExternally) - resetStatsLivenessState() - currentParams = null - ManlCaptchaWebViewManager.cancelCaptcha() - } finally { - clearTransition() - startStopMutex.unlock() - } - } + fun onWireGuardInterfaceDropped() { + if (!running.value) return + updateWarningLog( + "vpn_interface_dropped", + "[VPN] Android сообщил о потере системного VPN-интерфейса. Проверяем состояние перед восстановлением.", + 50, + ) } fun stop(reason: TunnelStopReason = TunnelStopReason.User) { @@ -1958,6 +2439,7 @@ object TunnelManager { resetStatsLivenessState() currentParams = null resetNetworkRecoveryState() + wakeRecoveryGraceUntilMs = 0L ManlCaptchaWebViewManager.cancelCaptcha() } finally { if (reason == TunnelStopReason.User) { @@ -1992,6 +2474,7 @@ object TunnelManager { resetStatsLivenessState() currentParams = null resetNetworkRecoveryState() + wakeRecoveryGraceUntilMs = 0L ManlCaptchaWebViewManager.cancelCaptcha() } } finally { @@ -2173,6 +2656,10 @@ data class TunnelParams( val connectionPassword: String = "", val protocol: String = "udp", val vkCallsPreflight: Boolean = true, + val rtNetwork: Boolean = false, + val rtMasque: Boolean = false, + val rtMasqueServerBootstrap: Boolean = false, + val rtTurnSni: String = DEFAULT_RT_TURN_SNI, val captchaMode: String = "auto", val captchaSolveMethod: String = "auto", val fingerprint: String = "firefox", diff --git a/app/src/main/java/com/wdtt/plus/TunnelService.kt b/app/src/main/java/com/wdtt/plus/TunnelService.kt index 61cd13f..c9859f2 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelService.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelService.kt @@ -34,6 +34,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import java.util.concurrent.ConcurrentHashMap private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4" @@ -44,14 +45,54 @@ private const val NETWORK_CHANGE_SETTLE_MS = 90_000L private const val NETWORK_RETURN_SETTLE_MS = 45_000L private const val NETWORK_LOSS_GRACE_MS = 2 * 60_000L private const val WAKE_RESCUE_GRACE_MS = 60_000L -private const val WAKE_RESCUE_FAIL_OPEN_MS = 2 * 60_000L private const val ACTIVE_PROFILE_REFRESH_INTERVAL_MS = 2 * 60_000L private const val INITIAL_VPN_START_GRACE_MS = 90_000L +private const val VPN_INTERFACE_MISSING_CONFIRM_MS = 90_000L +private const val VPN_INTERFACE_RECOVERY_RETRY_MS = 5 * 60_000L private const val TRUSTED_WIFI_ENTER_DELAY_MS = 2_000L private const val TRUSTED_WIFI_EXIT_DELAY_MS = 5_000L private const val TRUSTED_WIFI_RESUME_START_TIMEOUT_MS = 30_000L private const val TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS = 75_000L +internal fun shouldAttemptVpnInterfaceRecovery( + deviceInteractive: Boolean, + startupWindow: Boolean, + captchaActive: Boolean, + missingForMs: Long, + validatedNetworkAvailable: Boolean, + sinceLastAttemptMs: Long, +): Boolean = + deviceInteractive && + !startupWindow && + !captchaActive && + missingForMs >= VPN_INTERFACE_MISSING_CONFIRM_MS && + validatedNetworkAvailable && + sinceLastAttemptMs >= VPN_INTERFACE_RECOVERY_RETRY_MS + +internal fun shouldPauseVpnForSleep( + pauseEnabled: Boolean, + deviceInteractive: Boolean, + tunnelRunning: Boolean, + tunnelPaused: Boolean, + trustedWifiWaiting: Boolean, +): Boolean = + pauseEnabled && + !deviceInteractive && + tunnelRunning && + !tunnelPaused && + !trustedWifiWaiting + +internal fun shouldResumeVpnAfterSleep( + sleepPausedByPolicy: Boolean, + tunnelRunning: Boolean, + tunnelPaused: Boolean, + trustedWifiWaiting: Boolean, +): Boolean = + sleepPausedByPolicy && + tunnelRunning && + tunnelPaused && + !trustedWifiWaiting + class TunnelService : Service() { private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val startRequestGate = TunnelStartRequestGate() @@ -83,9 +124,16 @@ class TunnelService : Service() { private var lastValidatedNetwork: Network? = null private var lastStableNetworkReconnectAt = 0L private var stableNetworkWasLost = false + private var vpnInterfaceMissingSinceMs = 0L + private var lastVpnInterfaceRecoveryAttemptAtMs = 0L private var screenStateReceiver: BroadcastReceiver? = null private var trustedWifiStateReceiver: BroadcastReceiver? = null private var wakeRescueJob: Job? = null + private var sleepPauseJob: Job? = null + private val sleepTransitionMutex = Mutex() + private var lastKnownDeviceInteractive = true + @Volatile + private var sleepPausedByPolicy = false private var trustedWifiNetworkCallback: ConnectivityManager.NetworkCallback? = null private var trustedWifiSettingsJob: Job? = null private var trustedWifiEvaluationJob: Job? = null @@ -107,6 +155,10 @@ class TunnelService : Service() { override fun onCreate() { super.onCreate() createNotificationChannel() + lastKnownDeviceInteractive = isDeviceInteractive() + if (!lastKnownDeviceInteractive) { + TunnelManager.noteDeviceSleepStarted() + } // Сразу берем лок при создании acquireWakeLock() setupNetworkCallback() @@ -121,6 +173,7 @@ class TunnelService : Service() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent == null) { restoreTunnel() + scheduleSleepPauseIfNeeded() return START_STICKY } @@ -139,6 +192,11 @@ class TunnelService : Service() { connectionPassword = intent.getStringExtra("connection_password") ?: "", protocol = intent.getStringExtra("protocol") ?: "udp", vkCallsPreflight = intent.getBooleanExtra("vkcalls_preflight", true), + rtNetwork = intent.getBooleanExtra("rt_network", false), + rtMasque = intent.getBooleanExtra("rt_masque", false), + rtMasqueServerBootstrap = + intent.getBooleanExtra("rt_masque_server_bootstrap", false), + rtTurnSni = intent.getStringExtra("rt_turn_sni") ?: DEFAULT_RT_TURN_SNI, captchaMode = sanitizeCaptchaMode(intent.getStringExtra("captcha_mode")), captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto", fingerprint = intent.getStringExtra("fingerprint") ?: "firefox", @@ -152,6 +210,7 @@ class TunnelService : Service() { profileIndex = intent.getIntExtra(TUNNEL_PROFILE_INDEX_EXTRA, 0).coerceIn(0, 2), ) requestTunnelStart(params) + scheduleSleepPauseIfNeeded() } "STOP" -> stopTunnel(TunnelStopReason.User) "DEPLOY_START" -> { @@ -359,6 +418,8 @@ class TunnelService : Service() { cancelTrustedWifiResumeRetry(resetCount = !fromTrustedWifiResume) trustedWifiResumeInProgress = fromTrustedWifiResume trustedWifiResumeStartedAt = if (fromTrustedWifiResume) System.currentTimeMillis() else 0L + sleepPausedByPolicy = false + isTunnelPaused = false trustedWifiWaiting = false trustedWifiWaitingSsid = "" lastStartParams = params @@ -386,11 +447,16 @@ class TunnelService : Service() { startNotificationProfileWatcher() startStatsUpdater() startActiveProfileRefresh(params.profileIndex) + scheduleSleepPauseIfNeeded() } private fun stopTunnel(reason: TunnelStopReason = TunnelStopReason.User) { TunnelManager.noteStopRequested() if (stopSequenceJob?.isActive == true) return + sleepPausedByPolicy = false + sleepPauseJob?.cancel() + sleepPauseJob = null + isTunnelPaused = false invalidatePendingStart() val effectiveReason = requestedStopReason ?: reason requestedStopReason = effectiveReason @@ -512,12 +578,16 @@ class TunnelService : Service() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { Intent.ACTION_SCREEN_ON -> { + observeDeviceInteractiveState(interactive = true) + resumeSleepPausedTunnelIfNeeded() scheduleWakeRescueCheck() scheduleTrustedWifiEvaluation(delayMs = 0L) } Intent.ACTION_SCREEN_OFF -> { + observeDeviceInteractiveState(interactive = false) wakeRescueJob?.cancel() wakeRescueJob = null + scheduleSleepPauseIfNeeded() } } } @@ -534,6 +604,86 @@ class TunnelService : Service() { } } + private fun scheduleSleepPauseIfNeeded() { + sleepPauseJob?.cancel() + sleepPauseJob = serviceScope.launch { + val pauseEnabled = SettingsStore(applicationContext).pauseVpnDuringSleep.first() + if (isDeviceInteractive() || !pauseEnabled) return@launch + + val tunnelStarted = withTimeoutOrNull(15_000L) { + while (isActive && !TunnelManager.running.value) { + delay(250L) + } + TunnelManager.running.value + } ?: false + if (!tunnelStarted) return@launch + + sleepTransitionMutex.withLock { + if ( + !shouldPauseVpnForSleep( + pauseEnabled = pauseEnabled, + deviceInteractive = isDeviceInteractive(), + tunnelRunning = TunnelManager.running.value, + tunnelPaused = isTunnelPaused, + trustedWifiWaiting = trustedWifiWaiting, + ) + ) return@withLock + + sleepPausedByPolicy = true + isTunnelPaused = true + val interfaceStopped = withContext(Dispatchers.IO) { + // Освобождаем и нативный транспорт, и системный VPN-интерфейс: + // иначе при паузе трафик остался бы внутри пустого туннеля. + TunnelManager.pause() + val helper = WireGuardHelper(applicationContext) + helper.stopTunnel() + !helper.isTunnelUp() + } + if (!interfaceStopped) { + // Не оставляем телефон без рабочего маршрута, если Android + // не подтвердил остановку системного VPN-интерфейса. + sleepPausedByPolicy = false + isTunnelPaused = false + acquireWakeLock() + acquireWifiLock() + TunnelManager.resume() + TunnelManager.noteSleepVpnPauseFailed() + updateNotification("VPN остаётся активным") + return@withLock + } + TunnelManager.noteSleepVpnPaused() + releaseWakeLock() + releaseWifiLock() + updateNotification("VPN выключен во сне · интернет напрямую") + } + } + } + + private fun resumeSleepPausedTunnelIfNeeded() { + sleepPauseJob?.cancel() + sleepPauseJob = null + serviceScope.launch { + sleepTransitionMutex.withLock { + if ( + !shouldResumeVpnAfterSleep( + sleepPausedByPolicy = sleepPausedByPolicy, + tunnelRunning = TunnelManager.running.value, + tunnelPaused = isTunnelPaused, + trustedWifiWaiting = trustedWifiWaiting, + ) + ) return@withLock + + sleepPausedByPolicy = false + isTunnelPaused = false + acquireWakeLock() + acquireWifiLock() + updateNotification("Восстановление VPN...") + TunnelManager.noteSleepVpnResumed() + TunnelManager.resume() + } + } + } + private fun registerTrustedWifiStateReceiver() { if (trustedWifiStateReceiver != null) return trustedWifiStateReceiver = object : BroadcastReceiver() { @@ -586,52 +736,21 @@ class TunnelService : Service() { private fun scheduleWakeRescueCheck() { if (!AMNEZIA_STYLE_RECOVERY || !TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return - val wakeAt = System.currentTimeMillis() TunnelManager.noteWakeRescueStarted() - updateNotification("Проверка VPN после сна...") wakeRescueJob?.cancel() wakeRescueJob = TunnelManager.scope.launch(Dispatchers.Main) { delay(WAKE_RESCUE_GRACE_MS) if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch - if (TunnelManager.hasFreshTunnelActivitySince(wakeAt)) { + if (TunnelManager.hasFreshTunnelActivitySince(System.currentTimeMillis() - WAKE_RESCUE_GRACE_MS)) { TunnelManager.noteWakeRescueHealthy() - updateNotification(buildTunnelNotificationText()) - return@launch + } else { + // Выход из сна сам по себе не является доказательством поломки: + // Android и оператор могут на короткое время задержать вывод статистики. + // Не перезапускаем ни native-транспорт, ни системный VPN-интерфейс. + TunnelManager.noteWakeRescueDeferred() } - - if (TunnelManager.isNetworkTransitionGraceActive()) { - updateNotification(buildTunnelNotificationText()) - return@launch - } - val reconnectAt = System.currentTimeMillis() - val restarted = TunnelManager.restartTransport( - reason = "[СОН] После пробуждения VPN не подал признаков жизни. Мягко переподключаю транспорт.", - minIntervalMs = 60_000L - ) - if (!restarted) { - // Другая ветка восстановления уже перезапускает транспорт либо ещё действует - // её защитный интервал. Не запускаем параллельный таймер, который мог бы - // ошибочно остановить уже восстанавливающийся VPN. - updateNotification(buildTunnelNotificationText()) - return@launch - } - updateNotification("Восстановление VPN...") - - delay(WAKE_RESCUE_FAIL_OPEN_MS) - if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch - if (TunnelManager.hasFreshTunnelActivitySince(reconnectAt)) { - TunnelManager.noteWakeRescueHealthy() - updateNotification(buildTunnelNotificationText()) - return@launch - } - - TunnelManager.markStoppedAfterWakeRescue() - showTunnelAlertNotification( - "WDTT Plus остановил VPN", - "После пробуждения VPN не восстановился, поэтому приложение выключило VPN и вернуло прямой интернет." - ) - stopTunnel(TunnelStopReason.WakeRecoveryFailed) + updateNotification(buildTunnelNotificationText()) } } @@ -1147,6 +1266,7 @@ class TunnelService : Service() { private fun scheduleStableValidatedReconnect(reason: String) { val now = System.currentTimeMillis() + val interactiveAtSchedule = isDeviceInteractive() lastNetworkChangeTime = now if (!TunnelManager.running.value || isTunnelPaused) return @@ -1163,6 +1283,18 @@ class TunnelService : Service() { Log.d("TunnelService", "$reason, ждём короткую стабилизацию перед reconnect") delay(recoveryPolicy.networkSettleDelayMs) if (lastNetworkChangeTime != now) return@launch + // Смена underlying-сети во время сна часто является только + // восстановлением мобильного/Wi-Fi интерфейса Android. Не трогаем + // native-транспорт и VPN при таком событии ни во сне, ни если экран + // успел погаснуть до окончания стабилизации. + if (!interactiveAtSchedule || !isDeviceInteractive()) { + Log.d("TunnelService", "Пропускаем reconnect: событие сети пришло во время сна") + return@launch + } + if (TunnelManager.isWakeRecoveryGraceActive()) { + Log.d("TunnelService", "Пропускаем reconnect: после пробуждения ещё действует стабилизация") + return@launch + } if (!TunnelManager.running.value || !hasAnyRealNetwork() || TunnelManager.isCaptchaInProgress()) return@launch val sinceLastReconnect = System.currentTimeMillis() - lastStableNetworkReconnectAt @@ -1170,6 +1302,10 @@ class TunnelService : Service() { Log.d("TunnelService", "Пропускаем reconnect: недавний reconnect уже был") return@launch } + if (TunnelManager.hasFreshTunnelActivitySince(now)) { + Log.d("TunnelService", "Пропускаем reconnect: транспорт уже активен на подтверждённой сети") + return@launch + } lastStableNetworkReconnectAt = System.currentTimeMillis() TunnelManager.restartTransport( reason = "[СЕТЬ] Android подтвердил новую сеть. Мягко переподключаю транспорт.", @@ -1190,6 +1326,30 @@ class TunnelService : Service() { } } + @Suppress("DEPRECATION") + private fun hasValidatedRealNetwork(): Boolean { + val cm = connectivityManager ?: return false + return cm.allNetworks.any { network -> + val caps = cm.getNetworkCapabilities(network) ?: return@any false + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) && + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) + } + } + + private fun isDeviceInteractive(): Boolean = + (getSystemService(POWER_SERVICE) as PowerManager).isInteractive + + private fun observeDeviceInteractiveState(interactive: Boolean) { + if (lastKnownDeviceInteractive == interactive) return + lastKnownDeviceInteractive = interactive + if (interactive) { + TunnelManager.noteDeviceWakeStarted() + } else { + TunnelManager.noteDeviceSleepStarted() + } + } + @Suppress("DEPRECATION") private fun hasUsableRealNetworkForTrustedWifiResume(): Boolean { return trustedWifiValidatedNetworks.hasUsableNetwork() @@ -1385,6 +1545,15 @@ class TunnelService : Service() { if ( !shouldKeepTunnelServiceAlive( tunnelRunning = TunnelManager.running.value, + tunnelStarting = + TunnelManager.transition.value == TunnelTransition.STARTING && + lastStartParams?.let { params -> + shouldUseRtMasqueServerBootstrap( + rtNetwork = params.rtNetwork, + rtMasque = params.rtMasque, + serverBootstrap = params.rtMasqueServerBootstrap, + ) + } == true, tunnelPaused = isTunnelPaused, trustedWifiWaiting = trustedWifiWaiting, trustedWifiResumeInProgress = trustedWifiResumeInProgress @@ -1403,12 +1572,51 @@ class TunnelService : Service() { stopTunnel(TunnelStopReason.VpnSlotTransferred) break } - if (!startupWindow && !captchaActive && !helper.isTunnelUp()) { - Log.w("TunnelService", "Обнаружена пропажа или замена VPN-интерфейса! Экстренное выключение туннеля.") - stopTunnel(TunnelStopReason.VpnInterfaceLost) - break + val deviceInteractive = isDeviceInteractive() + // Не полагаемся только на broadcast: после глубокого сна первая + // итерация службы иногда выполняется раньше ACTION_SCREEN_ON. + observeDeviceInteractiveState(deviceInteractive) + val shouldInspectVpnInterface = + deviceInteractive && !startupWindow && !captchaActive + val vpnInterfaceUp = !shouldInspectVpnInterface || helper.isTunnelUp() + if (vpnInterfaceUp) { + vpnInterfaceMissingSinceMs = 0L + lastVpnInterfaceRecoveryAttemptAtMs = 0L + } else { + val now = System.currentTimeMillis() + if (vpnInterfaceMissingSinceMs == 0L) { + vpnInterfaceMissingSinceMs = now + Log.w( + "TunnelService", + "Системный VPN-интерфейс не найден. Подтверждаем состояние перед восстановлением." + ) + } + val missingForMs = now - vpnInterfaceMissingSinceMs + val sinceLastAttemptMs = if (lastVpnInterfaceRecoveryAttemptAtMs == 0L) { + Long.MAX_VALUE + } else { + now - lastVpnInterfaceRecoveryAttemptAtMs + } + if ( + shouldAttemptVpnInterfaceRecovery( + deviceInteractive = deviceInteractive, + startupWindow = startupWindow, + captchaActive = captchaActive, + missingForMs = missingForMs, + validatedNetworkAvailable = hasValidatedRealNetwork(), + sinceLastAttemptMs = sinceLastAttemptMs, + ) + ) { + lastVpnInterfaceRecoveryAttemptAtMs = now + Log.w( + "TunnelService", + "Потеря VPN-интерфейса подтверждена на рабочей сети. Создаём его заново." + ) + updateNotification("Восстановление VPN...") + TunnelManager.recreateVpnTunnel() + } } - if (!startupWindow && !captchaActive) { + if (!startupWindow && !captchaActive && vpnInterfaceUp && deviceInteractive) { when (TunnelManager.pollNetworkRecoveryAction()) { NetworkRecoveryAction.SoftRestart -> { Log.w("TunnelService", "Сетевая ошибка туннеля. Мягко перезапускаем транспорт.") @@ -1417,11 +1625,6 @@ class TunnelService : Service() { minIntervalMs = 20_000L ) } - NetworkRecoveryAction.RecreateVpn -> { - Log.w("TunnelService", "Мягкие попытки не помогли. Пересоздаём VPN-туннель.") - updateNotification("Пересоздание VPN...") - TunnelManager.recreateVpnTunnel() - } NetworkRecoveryAction.StopVpn -> { Log.w("TunnelService", "Автовосстановление не помогло. Останавливаем VPN, чтобы вернуть интернет.") TunnelManager.markStoppedAfterFailedRecovery() diff --git a/app/src/main/java/com/wdtt/plus/TunnelSessionTraffic.kt b/app/src/main/java/com/wdtt/plus/TunnelSessionTraffic.kt new file mode 100644 index 0000000..8697ef2 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/TunnelSessionTraffic.kt @@ -0,0 +1,63 @@ +package com.wdtt.plus + +import java.util.Locale + +private val tunnelTrafficPairRegex = Regex( + "↓\\s*([0-9]+(?:[.,][0-9]+)?)\\s*МБ\\s*/\\s*↑\\s*([0-9]+(?:[.,][0-9]+)?)\\s*МБ" +) + +internal class TunnelSessionTrafficAccumulator { + private var downloadOffsetMb = 0.0 + private var uploadOffsetMb = 0.0 + private var lastRawDownloadMb: Double? = null + private var lastRawUploadMb: Double? = null + + @Synchronized + fun reset() { + downloadOffsetMb = 0.0 + uploadOffsetMb = 0.0 + lastRawDownloadMb = null + lastRawUploadMb = null + } + + @Synchronized + fun noteTransportRestart() { + downloadOffsetMb += lastRawDownloadMb ?: 0.0 + uploadOffsetMb += lastRawUploadMb ?: 0.0 + lastRawDownloadMb = null + lastRawUploadMb = null + } + + @Synchronized + fun accumulate(message: String): String { + val match = tunnelTrafficPairRegex.find(message) ?: return message + val rawDownload = match.groupValues[1].toTrafficDouble() ?: return message + val rawUpload = match.groupValues[2].toTrafficDouble() ?: return message + + val previousDownload = lastRawDownloadMb + val previousUpload = lastRawUploadMb + if (previousDownload != null && rawDownload + TRAFFIC_RESET_TOLERANCE_MB < previousDownload) { + downloadOffsetMb += previousDownload + } + if (previousUpload != null && rawUpload + TRAFFIC_RESET_TOLERANCE_MB < previousUpload) { + uploadOffsetMb += previousUpload + } + + lastRawDownloadMb = rawDownload + lastRawUploadMb = rawUpload + + val replacement = "↓${formatTrafficMb(downloadOffsetMb + rawDownload)} МБ / " + + "↑${formatTrafficMb(uploadOffsetMb + rawUpload)} МБ" + return message.replaceRange(match.range, replacement) + } + + private fun String.toTrafficDouble(): Double? = + replace(',', '.').toDoubleOrNull() + + private fun formatTrafficMb(value: Double): String = + String.format(Locale.US, "%.2f", value) + + private companion object { + const val TRAFFIC_RESET_TOLERANCE_MB = 0.005 + } +} diff --git a/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt b/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt index cb2fe7d..10f9928 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelStartConfig.kt @@ -5,6 +5,33 @@ import android.content.Intent internal const val TUNNEL_PROFILE_INDEX_EXTRA = "profile_index" internal const val MANAGED_CONFIG_FIRST_START_EXTRA = "managed_config_first_start" +internal const val DEFAULT_RT_TURN_SNI = "ya.ru" + +internal fun normalizeRtTurnSni(value: String): String? { + val host = value.trim().lowercase() + if ( + host.isBlank() || + host.length > 253 || + host.startsWith(".") || + host.endsWith(".") || + host.contains("..") + ) { + return null + } + val labels = host.split('.') + if (labels.size < 2 || labels.all { it.toIntOrNull() != null }) return null + return host.takeIf { + labels.all { label -> + label.isNotBlank() && + label.length <= 63 && + !label.startsWith("-") && + !label.endsWith("-") && + label.all { char -> + char in 'a'..'z' || char in '0'..'9' || char == '-' + } + } + } +} internal data class TransportRecoveryPolicy( val networkSettleDelayMs: Long, @@ -15,18 +42,12 @@ internal data class TransportRecoveryPolicy( internal fun transportRecoveryPolicy( managedConfigFirstStart: Boolean, -): TransportRecoveryPolicy = if (managedConfigFirstStart) { - TransportRecoveryPolicy( - networkSettleDelayMs = 3_000L, - reconnectMinIntervalMs = 8_000L, - processRestartDelayMs = 250L, - forceRestart = true, - ) -} else { - TransportRecoveryPolicy( +): TransportRecoveryPolicy { + val processRestartDelayMs = if (managedConfigFirstStart) 250L else 2_500L + return TransportRecoveryPolicy( networkSettleDelayMs = 15_000L, reconnectMinIntervalMs = 2 * 60_000L, - processRestartDelayMs = 2_500L, + processRestartDelayMs = processRestartDelayMs, forceRestart = false, ) } @@ -96,6 +117,11 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? { connectionPassword = linkParts.password, protocol = saved.protocol, vkCallsPreflight = saved.vkCallsPreflight, + rtNetwork = saved.rtNetwork, + rtMasque = saved.rtMasque, + rtMasqueServerBootstrap = + saved.rtMasqueServerBootstrap && saved.rtMasqueServerAccessReady, + rtTurnSni = saved.rtTurnSni, captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode), captchaSolveMethod = saved.captchaSolveMethod, fingerprint = saved.fingerprint, @@ -127,6 +153,11 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? { connectionPassword = password, protocol = saved.protocol, vkCallsPreflight = saved.vkCallsPreflight, + rtNetwork = saved.rtNetwork, + rtMasque = saved.rtMasque, + rtMasqueServerBootstrap = + saved.rtMasqueServerBootstrap && saved.rtMasqueServerAccessReady, + rtTurnSni = saved.rtTurnSni, captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode), captchaSolveMethod = saved.captchaSolveMethod, fingerprint = saved.fingerprint, @@ -154,6 +185,10 @@ suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? { putExtra("connection_password", params.connectionPassword) putExtra("protocol", params.protocol) putExtra("vkcalls_preflight", params.vkCallsPreflight) + putExtra("rt_network", params.rtNetwork) + putExtra("rt_masque", params.rtMasque) + putExtra("rt_masque_server_bootstrap", params.rtMasqueServerBootstrap) + putExtra("rt_turn_sni", params.rtTurnSni) putExtra("captcha_mode", params.captchaMode) putExtra("captcha_solve_method", params.captchaSolveMethod) putExtra("fingerprint", params.fingerprint) diff --git a/app/src/main/java/com/wdtt/plus/WarpApiSshRelay.kt b/app/src/main/java/com/wdtt/plus/WarpApiSshRelay.kt new file mode 100644 index 0000000..77c6db9 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/WarpApiSshRelay.kt @@ -0,0 +1,94 @@ +package com.wdtt.plus + +import android.content.Context +import com.jcraft.jsch.Session +import java.io.Closeable + +private const val WARP_API_RELAY_TARGET = "api.cloudflareclient.com" +private const val WARP_API_RELAY_TARGET_PORT = 443 + +internal sealed interface WarpApiSshRelayStartResult { + data class Ready(val relay: WarpApiSshRelay) : WarpApiSshRelayStartResult + data object MissingProfileAccess : WarpApiSshRelayStartResult + data class Failed(val message: String) : WarpApiSshRelayStartResult +} + +/** + * A short-lived loopback-only TCP relay backed by the SSH access already stored for the active + * Deploy profile. The forwarding target is fixed to Cloudflare's WARP enrollment API. No server + * endpoint, SSH username or credential is passed to the native process or written to logs. + */ +internal class WarpApiSshRelay private constructor( + private val session: Session, + val port: Int, +) : Closeable { + val loopbackAddress: String + get() = "127.0.0.1:$port" + + @Volatile + private var closed = false + + override fun close() { + if (closed) return + synchronized(this) { + if (closed) return + closed = true + runCatching { session.delPortForwardingL("127.0.0.1", port) } + runCatching { session.disconnect() } + } + } + + companion object { + suspend fun start( + context: Context, + profileIndex: Int, + ): WarpApiSshRelayStartResult { + val profile = SettingsStore(context.applicationContext) + .sshConnectionForProfile(profileIndex) + ?: return WarpApiSshRelayStartResult.MissingProfileAccess + + var session: Session? = null + return try { + session = createSshSession( + host = profile.host, + user = profile.user, + credentials = profile.credentials, + port = profile.port, + ) + val localPort = session.setPortForwardingL( + "127.0.0.1", + 0, + WARP_API_RELAY_TARGET, + WARP_API_RELAY_TARGET_PORT, + ) + if (localPort !in 1..65535) { + throw IllegalStateException("SSH не выделил локальный порт") + } + WarpApiSshRelayStartResult.Ready( + WarpApiSshRelay(session = session, port = localPort), + ) + } catch (error: Exception) { + runCatching { session?.disconnect() } + WarpApiSshRelayStartResult.Failed(safeRelayError(error)) + } + } + + private fun safeRelayError(error: Throwable): String { + val detail = generateSequence(error) { it.cause } + .mapNotNull { it.message } + .joinToString(" ") + .lowercase() + return when { + "auth fail" in detail || "отклонил пароль" in detail || "отклонил приватный ключ" in detail -> + "SSH-сервер отклонил данные входа" + "timeout" in detail || "20 секунд" in detail -> + "SSH-сервер не ответил вовремя" + "refused" in detail || "порт отклонил" in detail -> + "SSH-порт отклонил подключение" + "administratively prohibited" in detail || "port forwarding" in detail -> + "SSH-сервер запретил TCP-переадресацию" + else -> "не удалось подготовить SSH-переадресацию" + } + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/WdttApplication.kt b/app/src/main/java/com/wdtt/plus/WdttApplication.kt index 3401a73..74c1df2 100644 --- a/app/src/main/java/com/wdtt/plus/WdttApplication.kt +++ b/app/src/main/java/com/wdtt/plus/WdttApplication.kt @@ -9,8 +9,12 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +internal fun shouldClearPhantomVpn(activeTunnelProfile: Int?): Boolean = + activeTunnelProfile == null + class WdttApplication : Application() { @Volatile private var backendInstance: GoBackend? = null @@ -21,12 +25,19 @@ class WdttApplication : Application() { override fun onCreate() { super.onCreate() DeployManager.init(this) - - // Очищаем фантомный VPN при холодном старте приложения (например, после перезагрузки телефона). - // Если телефон перезагрузился, система Android пытается сама восстановить VpnService, - // что приводит к фантомному ключу без интернета. Этот код мгновенно сбрасывает статус в DOWN. + + val settingsStore = SettingsStore(this) + + // Очищаем только действительно бесхозный фантомный VPN. Если сохранён активный + // профиль, Android одновременно восстанавливает TunnelService: безусловный DOWN + // здесь мог опередить или оборвать штатное восстановление и затем вызвать новый UP. CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { runCatching { + val activeTunnelProfile = settingsStore.activeTunnelProfile.first() + if (!shouldClearPhantomVpn(activeTunnelProfile)) { + Log.d("WdttApp", "Ожидается восстановление активного VPN; очистка фантома пропущена") + return@runCatching + } val backend = getBackend(this@WdttApplication) val tunnel = WireGuardHelper.WgTunnel() backend.setState(tunnel, Tunnel.State.DOWN, null) @@ -35,8 +46,6 @@ class WdttApplication : Application() { Log.w("WdttApp", "Не удалось очистить фантомный VPN: ${it.message}") } } - - val settingsStore = SettingsStore(this) CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { RemoteActionCatalogGateway.fetch(force = true) } diff --git a/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt b/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt index fd7dcb7..e4ef51b 100644 --- a/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt +++ b/app/src/main/java/com/wdtt/plus/WireGuardHelper.kt @@ -153,7 +153,7 @@ class WireGuardHelper(context: Context) { } val nextTunnel = WgTunnel { - TunnelManager.onWireGuardStoppedExternally() + TunnelManager.onWireGuardInterfaceDropped() } setTunnelUpWithRetry(nextTunnel, finalConfig) sharedTunnel = nextTunnel 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 23378b2..e7914f0 100644 --- a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt +++ b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt @@ -70,6 +70,7 @@ private const val PROFILE_RESET_TIMEOUT_MS = 10_000L @OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class) @Composable fun FloatingToolbar( + settingsStore: SettingsStore, activeProfile: Int, profileNames: List, onActiveProfileChange: (Int) -> Unit, @@ -92,10 +93,10 @@ fun FloatingToolbar( ) { val context = LocalContext.current val scope = rememberCoroutineScope() - val settingsStore = remember { SettingsStore(context) } val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false) val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList()) val trustedWifiRuntime by com.wdtt.plus.TrustedWifiManager.state.collectAsStateWithLifecycle() + val pauseVpnDuringSleep by settingsStore.pauseVpnDuringSleep.collectAsStateWithLifecycle(initialValue = false) val customVkCredentialsEnabled by settingsStore.customVkCredentialsEnabled.collectAsStateWithLifecycle(initialValue = false) val customVkCredentialsComplete by settingsStore.customVkCredentialsComplete.collectAsStateWithLifecycle(initialValue = false) val savedToolbarYFraction by settingsStore.floatingToolbarYFraction.collectAsStateWithLifecycle( @@ -388,6 +389,38 @@ fun FloatingToolbar( ) } + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) { + Text( + "Экономия батареи во сне", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + if (pauseVpnDuringSleep) { + "VPN выключается · интернет напрямую" + } else { + "VPN остаётся активным" + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 15.sp + ) + } + Switch( + checked = pauseVpnDuringSleep, + onCheckedChange = { enabled -> + scope.launch { settingsStore.savePauseVpnDuringSleep(enabled) } + }, + modifier = Modifier.scale(0.85f) + ) + } + HorizontalDivider( modifier = Modifier.padding(vertical = 4.dp), color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) diff --git a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt index ac6736a..1826f66 100644 --- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt @@ -8,8 +8,6 @@ import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager -import android.net.ConnectivityManager -import android.net.NetworkCapabilities import android.net.Uri import android.net.VpnService import android.os.Build @@ -23,7 +21,10 @@ import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut @@ -117,10 +118,13 @@ import com.wdtt.plus.RemoteActionForm import com.wdtt.plus.RemoteContinuationLauncher import com.wdtt.plus.RemoteUiAction import com.wdtt.plus.RemoteUiActionLauncher +import com.wdtt.plus.RT_MASQUE_CONFIG_FILE_NAME +import com.wdtt.plus.RtMasqueEnrollmentState import com.wdtt.plus.SettingsStore import com.wdtt.plus.TunnelManager import com.wdtt.plus.TrustedWifiManager import com.wdtt.plus.trustedWifiAccessProblem +import com.wdtt.plus.inspectRtMasqueEnrollment import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE import com.wdtt.plus.WDTTColors @@ -139,6 +143,7 @@ import com.wdtt.plus.selectUpdateApkAsset import com.wdtt.plus.deviceCheckActionIntent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -260,6 +265,7 @@ fun InfoTab( var showHelpDialog by remember { mutableStateOf(false) } var showQuestionDialog by remember { mutableStateOf(false) } var showSupportDialog by remember { mutableStateOf(false) } + var highlightNoServerBlock by remember { mutableStateOf(false) } var pendingActionForm by remember { mutableStateOf(null) } var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) } var questionAction by remember { mutableStateOf(null) } @@ -270,6 +276,7 @@ fun InfoTab( var projectExpanded by projectExpandedState LaunchedEffect(projectSupportDialogRequest) { if (projectSupportDialogRequest > 0) { + highlightNoServerBlock = true showSupportDialog = true onProjectSupportDialogRequestConsumed() } @@ -353,6 +360,7 @@ fun InfoTab( latestRelease = latestRelease ) val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull() + val tunnelProfile = runCatching { settingsStore.tunnelProfileSnapshot() }.getOrNull() val diagnosticsSummary = withContext(Dispatchers.Default) { buildSupportReportSummary(context.applicationContext, settingsStore) } @@ -385,7 +393,12 @@ fun InfoTab( return report.copy( summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines, items = listOf(versionItem) + - report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE } + + report.items.filterNot { + it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE || + it.title == "Сеть Android" + } + listOfNotNull( + tunnelProfile?.let { DeviceCompatibility.rtNetworkModeItem(context, it) } + ) + clientNetworkDiagnostics.items ) } @@ -415,6 +428,7 @@ fun InfoTab( currentVersion = currentVersion, releaseDate = releaseDate, onSupportClick = { + highlightNoServerBlock = false showSupportDialog = true } ) @@ -469,7 +483,7 @@ fun InfoTab( WideActionTile( title = "Проверить устройство", subtitle = if (isCheckingDevice) { - "Проверяем версию, Android, ABI, сеть и системные условия..." + "Проверяем Android, ABI, 16 КиБ, WireGuard, режим РТ и сеть..." } else { "Проверка совместимости и полный отчёт для диагностики" }, @@ -790,10 +804,16 @@ fun InfoTab( } if (showSupportDialog) { AdditionalActionsDialog( - onDismiss = { showSupportDialog = false }, + onDismiss = { + highlightNoServerBlock = false + showSupportDialog = false + }, primaryAction = actionCatalog.at("about"), secondaryAction = actionCatalog.at("tunnel"), + highlightSecondaryAction = highlightNoServerBlock, + onSecondaryHighlightConsumed = { highlightNoServerBlock = false }, onActionClick = { action -> + highlightNoServerBlock = false if (action.form != null) { showSupportDialog = false pendingActionForm = action @@ -811,10 +831,12 @@ fun InfoTab( } }, onProjectFallbackClick = { + highlightNoServerBlock = false showSupportDialog = false openUrlInBrowser(context, ProjectDonateFallbackUrl) }, onDonateOriginalClick = { + highlightNoServerBlock = false showSupportDialog = false openUrlInBrowser(context, OriginalDonateUrl) } @@ -970,6 +992,8 @@ private fun AdditionalActionsDialog( onDismiss: () -> Unit, primaryAction: RemoteUiAction?, secondaryAction: RemoteUiAction?, + highlightSecondaryAction: Boolean, + onSecondaryHighlightConsumed: () -> Unit, onActionClick: (RemoteUiAction) -> Unit, onProjectFallbackClick: () -> Unit, onDonateOriginalClick: () -> Unit @@ -1034,7 +1058,7 @@ private fun AdditionalActionsDialog( ExternalSupportBlock( title = primaryAction.title, body = primaryAction.message, - buttonText = primaryAction.label, + buttonText = "Поддержать проект", onClick = { onActionClick(primaryAction) }, emphasized = true, ) @@ -1054,6 +1078,8 @@ private fun AdditionalActionsDialog( secondaryAction?.let { action -> RemoteInfoActionBlock( action = action, + highlightRequested = highlightSecondaryAction, + onHighlightConsumed = onSecondaryHighlightConsumed, onClick = { onActionClick(action) }, ) } @@ -1088,6 +1114,19 @@ private fun RemoteActionFormDialog( var fallbackAvailable by remember(form.token) { mutableStateOf(false) } val numericValue = valueText.toLongOrNull() val valueValid = numericValue != null && numericValue in form.minimum..form.maximum + val supportAmount = valueText.trim() + val supportButtonLabel = if (supportAmount.isNotEmpty()) { + buildString { + append("Поддержать на ") + append(supportAmount) + if (form.inputSuffix.isNotBlank()) { + append(' ') + append(form.inputSuffix.trim()) + } + } + } else { + "Поддержать" + } fun selectValue(value: String) { valueText = value @@ -1268,7 +1307,7 @@ private fun RemoteActionFormDialog( Text(form.busyLabel, fontWeight = FontWeight.Bold) } else { Text( - form.submitLabel.replace("{value}", valueText), + supportButtonLabel, fontWeight = FontWeight.Bold, ) } @@ -1298,16 +1337,44 @@ private fun RemoteActionFormDialog( @Composable private fun RemoteInfoActionBlock( action: RemoteUiAction, + highlightRequested: Boolean = false, + onHighlightConsumed: () -> Unit = {}, onClick: () -> Unit, ) { + var borderPulseActive by remember(highlightRequested) { + mutableStateOf(false) + } + LaunchedEffect(highlightRequested) { + if (highlightRequested) { + repeat(2) { + borderPulseActive = true + delay(380) + borderPulseActive = false + delay(280) + } + onHighlightConsumed() + } + } + val borderColor by animateColorAsState( + targetValue = if (borderPulseActive) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) + }, + animationSpec = tween(durationMillis = 240), + label = "no_server_highlight_border", + ) + val borderWidth by animateDpAsState( + targetValue = if (borderPulseActive) 2.5.dp else 1.dp, + animationSpec = tween(durationMillis = 240), + label = "no_server_highlight_border_width", + ) + Surface( shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f), contentColor = MaterialTheme.colorScheme.onSecondaryContainer, - border = BorderStroke( - 1.dp, - MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) - ) + border = BorderStroke(borderWidth, borderColor), ) { Column( modifier = Modifier.fillMaxWidth().padding(14.dp), @@ -1930,41 +1997,14 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S "без ограничений батареи=${powerManager?.isIgnoringBatteryOptimizations(context.packageName)}" } - val connectivityManager = runCatching { - context.getSystemService(ConnectivityManager::class.java) - }.getOrNull() - val activeNetwork = runCatching { connectivityManager?.activeNetwork }.getOrNull() - val networkCapabilities = runCatching { - activeNetwork?.let { connectivityManager?.getNetworkCapabilities(it) } - }.getOrNull() - val networkTransports = buildList { - if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true) add("Wi-Fi") - if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true) add("мобильная") - if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) == true) add("Ethernet") - if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true) add("VPN") - }.joinToString().ifBlank { "не определён" } - val networkSummary = if (networkCapabilities != null) { - "$networkTransports, internet=${networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)}, " + - "validated=${networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)}, " + - "metered=${connectivityManager?.isActiveNetworkMetered}" - } else { - "недоступно" - } - val privateDns = diagnosticText { - val properties = activeNetwork?.let { connectivityManager?.getLinkProperties(it) } - properties?.isPrivateDnsActive - } - val webViewInfo = diagnosticText { WebView.getCurrentWebViewPackage()?.let { "${it.packageName} ${it.versionName}" } } - val nativeClientInfo = runCatching { + val nativeComponentsInfo = runCatching { val nativeClient = File(appInfo?.nativeLibraryDir.orEmpty(), "libclient.so") - if (nativeClient.isFile) { - "найден, ${formatMiB(nativeClient.length())}, executable=${nativeClient.canExecute()}" - } else { - "не найден" - } + val wireGuardBackend = File(appInfo?.nativeLibraryDir.orEmpty(), "libwg-go.so") + "libclient.so=${if (nativeClient.isFile) formatMiB(nativeClient.length()) else "не найден"}, " + + "libwg-go.so=${if (wireGuardBackend.isFile) formatMiB(wireGuardBackend.length()) else "не найден"}" }.getOrDefault("недоступно") val notificationPermission = diagnosticText { @@ -1994,6 +2034,18 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S .coerceAtMost(4) val hasSecondaryHash = runCatching { settingsStore.secondaryVkHash.first().isNotBlank() }.getOrNull() val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull() + val rtNetworkEnabled = runCatching { settingsStore.rtNetwork.first() }.getOrNull() + val rtMasqueEnabled = runCatching { settingsStore.rtMasque.first() }.getOrNull() + val rtMasqueServerBootstrap = + runCatching { settingsStore.rtMasqueServerBootstrap.first() }.getOrNull() + val rtMasqueEnrollment = runCatching { + val config = File(context.filesDir, RT_MASQUE_CONFIG_FILE_NAME) + when (inspectRtMasqueEnrollment(config)) { + RtMasqueEnrollmentState.Missing -> "не создана" + RtMasqueEnrollmentState.Ready -> "сохранена и структурно корректна" + RtMasqueEnrollmentState.Invalid -> "повреждена" + } + }.getOrDefault("недоступно") val customVkCredentialsEnabled = runCatching { settingsStore.customVkCredentialsEnabled.first() }.getOrNull() val customVkCredentialsComplete = runCatching { settingsStore.customVkCredentialsComplete.first() }.getOrNull() val builtInVkClientCount = runCatching { @@ -2052,10 +2104,8 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S appendLine("Low-RAM устройство: $lowRamDevice") appendLine("Хранилище приложения: $storageSummary") appendLine("Питание: $powerSummary") - appendLine("Сеть: $networkSummary") - appendLine("Private DNS: $privateDns") appendLine("WebView: $webViewInfo") - appendLine("Нативный клиент: $nativeClientInfo") + appendLine("Нативные компоненты: $nativeComponentsInfo") appendLine("Экран: $screenSummary") appendLine("Разрешение уведомлений: $notificationPermission") appendLine("Установка обновлений APK: $updateInstallPermission") @@ -2072,6 +2122,12 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S appendLine("Потоки: ${workers ?: "недоступно"}") appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}") appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}") + appendLine("Сеть РТ (TURN stream-first): ${rtNetworkEnabled ?: "недоступно"}") + appendLine( + "MASQUE в Сети РТ (HTTP/2 → HTTP/3): ${rtMasqueEnabled ?: "недоступно"}, " + + "регистрация WARP=$rtMasqueEnrollment, " + + "первая регистрация через сервер=${rtMasqueServerBootstrap ?: "недоступно"}" + ) appendLine( "Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " + "заполнены=${customVkCredentialsComplete ?: "недоступно"}, встроенных=${builtInVkClientCount ?: "недоступно"}" diff --git a/app/src/main/java/com/wdtt/plus/ui/RtNetworkSettingsDialog.kt b/app/src/main/java/com/wdtt/plus/ui/RtNetworkSettingsDialog.kt new file mode 100644 index 0000000..7d0ffa5 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/RtNetworkSettingsDialog.kt @@ -0,0 +1,298 @@ +package com.wdtt.plus.ui + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.HelpOutline +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Cloud +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import com.wdtt.plus.DEFAULT_RT_TURN_SNI +import com.wdtt.plus.SshProfileAccessStatus + +@Composable +internal fun RtNetworkSettingsDialog( + rtNetwork: Boolean, + turnSni: String, + turnSniValid: Boolean, + rtMasque: Boolean, + rtMasqueServerBootstrap: Boolean, + serverAccess: SshProfileAccessStatus, + tunnelRunning: Boolean, + onTurnSniChange: (String) -> Unit, + onRtMasqueChange: (Boolean) -> Unit, + onServerBootstrapChange: (Boolean) -> Unit, + onShowRtHelp: () -> Unit, + onShowMasqueHelp: () -> Unit, + onShowServerHelp: () -> Unit, + onDismiss: () -> Unit, +) { + val configuration = LocalConfiguration.current + val dialogMaxHeight = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp) + val dialogMinHeight = 520.dp.coerceAtMost(dialogMaxHeight) + val controlsEnabled = rtNetwork && !tunnelRunning + val serverSupportingText = when { + !rtNetwork -> "Сначала включите «Сеть РТ»" + !rtMasque -> "Сначала включите MASQUE" + !serverAccess.available -> "Недоступно: ${serverAccess.unavailableReason}" + tunnelRunning -> "Остановите VPN, чтобы изменить настройку" + else -> "Только первая регистрация WARP · SSH из «Деплой»" + } + val serverTextIsError = rtNetwork && rtMasque && !serverAccess.available + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false), + ) { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center, + ) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .heightIn(min = dialogMinHeight, max = dialogMaxHeight), + shape = RoundedCornerShape(30.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 8.dp, + shadowElevation = 8.dp, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(18.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.primaryContainer, + ) { + Box( + modifier = Modifier.size(48.dp), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Default.Cloud, + contentDescription = null, + modifier = Modifier.size(25.dp), + ) + } + } + Text( + "Сеть РТ", + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + ) + IconButton(onClick = onShowRtHelp) { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Инструкция по режиму Сеть РТ", + ) + } + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + + if (!rtNetwork || tunnelRunning) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f), + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.outline.copy(alpha = 0.2f), + ), + ) { + Text( + if (!rtNetwork) { + "Включите «Сеть РТ» в основном окне, чтобы изменить эти параметры." + } else { + "Остановите VPN, чтобы изменить параметры режима." + }, + modifier = Modifier.padding(14.dp), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + OutlinedTextField( + value = turnSni, + onValueChange = onTurnSniChange, + label = { Text("SNI белого списка") }, + placeholder = { Text(DEFAULT_RT_TURN_SNI) }, + isError = !turnSniValid, + enabled = controlsEnabled, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + ) + Text( + text = if (turnSniValid) { + "Только для TURN/TLS и MASQUE; в TURN/TCP и UDP SNI нет" + } else { + "Укажите домен латиницей, например $DEFAULT_RT_TURN_SNI" + }, + modifier = Modifier.fillMaxWidth(), + style = MaterialTheme.typography.bodySmall, + color = if (turnSniValid) { + MaterialTheme.colorScheme.onSurfaceVariant + } else { + MaterialTheme.colorScheme.error + }, + ) + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)) + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("MASQUE", fontWeight = FontWeight.SemiBold) + IconButton( + onClick = onShowMasqueHelp, + modifier = Modifier.size(32.dp), + ) { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Инструкция по MASQUE", + modifier = Modifier.size(19.dp), + ) + } + } + Text( + "Резерв после TURN/TLS и TCP: HTTP/2, затем HTTP/3", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Switch( + checked = rtMasque, + enabled = controlsEnabled, + onCheckedChange = onRtMasqueChange, + ) + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)) + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Через сервер", fontWeight = FontWeight.SemiBold) + IconButton( + onClick = onShowServerHelp, + modifier = Modifier.size(32.dp), + ) { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Инструкция по регистрации через сервер", + modifier = Modifier.size(19.dp), + ) + } + } + Text( + serverSupportingText, + style = MaterialTheme.typography.bodySmall, + color = if (serverTextIsError) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + Switch( + checked = rtMasqueServerBootstrap, + enabled = controlsEnabled && rtMasque && serverAccess.available, + onCheckedChange = onServerBootstrapChange, + ) + } + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f), + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.outline.copy(alpha = 0.2f), + ), + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + "Когда включать", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + ) + Text( + "Сеть РТ — если в мобильной сети Ростелекома открываются разрешённые сайты, но WDTT Plus не подключается.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + "MASQUE — если одной «Сети РТ» недостаточно: это дополнительный резерв после TURN/TLS и TCP.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + "Через сервер — только если первая регистрация WARP для MASQUE не проходит напрямую; нужен настроенный иностранный SSH-сервер в «Деплой».", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + } + } +} 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 5af1095..8a516e8 100644 --- a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt @@ -11,6 +11,7 @@ import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Canvas +import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.* @@ -27,6 +28,7 @@ import androidx.compose.material.icons.filled.Cloud import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.Link import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.PowerSettingsNew import androidx.compose.material.icons.filled.Refresh @@ -54,6 +56,7 @@ import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.withLink import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType @@ -80,6 +83,7 @@ import com.wdtt.plus.AccessStartDecision import com.wdtt.plus.CaptchaWebViewManager import com.wdtt.plus.ConnectionIssueKind import com.wdtt.plus.DEFAULT_VK_CLIENT_IDS +import com.wdtt.plus.DEFAULT_RT_TURN_SNI import com.wdtt.plus.ManlCaptchaWebViewManager import com.wdtt.plus.MainActivity import com.wdtt.plus.MANAGED_CONFIG_FIRST_START_EXTRA @@ -90,6 +94,7 @@ import com.wdtt.plus.RemoteDocumentGateway import com.wdtt.plus.RemoteLaunchTarget import com.wdtt.plus.RemoteUiAction import com.wdtt.plus.RemoteUiActionLauncher +import com.wdtt.plus.RT_MASQUE_CONFIG_FILE_NAME import com.wdtt.plus.SettingsStore import com.wdtt.plus.TunnelManager import com.wdtt.plus.TunnelService @@ -98,6 +103,7 @@ import com.wdtt.plus.TunnelStopResult import com.wdtt.plus.TunnelTransition import com.wdtt.plus.TUNNEL_PROFILE_INDEX_EXTRA import com.wdtt.plus.normalizeTunnelWorkerCount +import com.wdtt.plus.normalizeRtTurnSni import com.wdtt.plus.shouldUseManagedConfigFirstStart import com.wdtt.plus.TrustedWifiManager import com.wdtt.plus.VkJoinLink @@ -107,6 +113,8 @@ import com.wdtt.plus.WdttDeepLinkApplyPlan import com.wdtt.plus.isValidVkClientId import com.wdtt.plus.isStandaloneUiIssue import com.wdtt.plus.accessLifecycleDismissalSignature +import com.wdtt.plus.accessLifecycleCanDismiss +import com.wdtt.plus.boundContinuationAvailable import com.wdtt.plus.fallbackTitle import com.wdtt.plus.vpnProfileDisplayName import kotlinx.coroutines.Dispatchers @@ -126,6 +134,7 @@ import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import kotlin.math.roundToInt +import java.io.File private const val WORKERS_PER_GROUP = 9 private const val REMOTE_ACTION_REFRESH_MS = 10 * 60 * 1000L @@ -150,7 +159,13 @@ internal fun resolveConnectionInputMethod( hasManualConnection: Boolean, userInterface: Boolean, ): String = when (savedMethod) { - "link", "manual" -> savedMethod + "link" -> when { + hasStoredLink -> "link" + hasManualConnection -> "manual" + userInterface -> "link" + else -> "manual" + } + "manual" -> "manual" else -> when { hasStoredLink -> "link" hasManualConnection -> "manual" @@ -199,6 +214,20 @@ internal fun shouldShowTunnelRemoteActionCard( ) } +internal fun shouldShowManagedHashStatusCard( + continuationAvailable: Boolean, + lifecycle: AccessLifecycleUiState, +): Boolean = + !continuationAvailable && + lifecycle.managed && + lifecycle.allowConnect && + lifecycle.severity == AccessLifecycleSeverity.NORMAL && + ( + lifecycle.title.isNotBlank() || + lifecycle.message.isNotBlank() || + lifecycle.detailValue.isNotBlank() + ) + internal fun isSelectedCompactConnectionReady( selectedMethod: String, savedMethod: String, @@ -207,14 +236,8 @@ internal fun isSelectedCompactConnectionReady( linkValid: Boolean, manualValid: Boolean, ): Boolean = when (selectedMethod) { - "link" -> when { - storedLinkMode && linkPresent -> linkValid - savedMethod == "link" -> manualValid - else -> false - } - "manual" -> !storedLinkMode && - (savedMethod == "manual" || savedMethod.isBlank()) && - manualValid + "link" -> storedLinkMode && linkPresent && linkValid + "manual" -> !storedLinkMode && manualValid else -> false } @@ -272,7 +295,7 @@ fun SettingsTabContent( onOpenProjectSupport: () -> Unit, ) { val profileSnapshotState by - settingsStore.activeTunnelProfileUiSnapshot.collectAsStateWithLifecycle() + settingsStore.activeTunnelProfileContentUiSnapshot.collectAsStateWithLifecycle() val profileSnapshot = profileSnapshotState ?: return val savedConnectionPassword = profileSnapshot.connectionPassword val savedPeer = profileSnapshot.peer @@ -296,83 +319,35 @@ fun SettingsTabContent( val customVkClientId = profileSnapshot.customVkClientId val customVkClientSecret = profileSnapshot.customVkClientSecret val vkCallsPreflight = profileSnapshot.vkCallsPreflight + val rtNetwork = profileSnapshot.rtNetwork + val rtMasque = profileSnapshot.rtMasque + val rtMasqueServerBootstrap = profileSnapshot.rtMasqueServerBootstrap + val rtMasqueServerAccess = profileSnapshot.rtMasqueServerAccessStatus + val effectiveRtMasqueServerBootstrap = + rtMasqueServerBootstrap && rtMasqueServerAccess.available + val savedRtTurnSni = profileSnapshot.rtTurnSni val remoteActionKey = profileSnapshot.remoteActionKey val remoteActionUrl = profileSnapshot.remoteActionUrl val remoteManagedProfile = profileSnapshot.remoteManaged val interfaceRole = if (remoteManagedProfile) "user" else profileSnapshot.interfaceRole val cachedRemoteAction = profileSnapshot.cachedRemoteAction val remoteCardDismissed = profileSnapshot.remoteCardDismissed - val accessLifecycle = profileSnapshot.accessLifecycle - val accessLifecycleDismissedSignature = - profileSnapshot.accessLifecycleDismissedSignature val profileMaxWorkers = profileSnapshot.profileMaxWorkers - val refreshingProfiles by - AccessLifecycleCoordinator.refreshingProfiles.collectAsStateWithLifecycle() - val accessRefreshing = activeProfile in refreshingProfiles - var accessActionBusy by remember(activeProfile) { mutableStateOf(false) } - var accessManualRefreshBusy by remember(activeProfile) { mutableStateOf(false) } - var accessLifecycleDismissCountdown by remember(activeProfile) { mutableIntStateOf(0) } - val initialActionCatalog = remember { RemoteActionCatalogGateway.cached() } - var actionCatalog by remember { mutableStateOf(initialActionCatalog) } - var actionCatalogResolved by remember { - mutableStateOf(RemoteActionCatalogGateway.hasFreshCache()) + + LaunchedEffect( + activeProfile, + rtMasqueServerBootstrap, + rtMasqueServerAccess.available, + ) { + if (rtMasqueServerBootstrap && !rtMasqueServerAccess.available) { + settingsStore.saveRtMasqueServerBootstrap(false) + } } - var remoteCardDismissCountdown by remember(activeProfile) { mutableIntStateOf(0) } - val lifecycleOwner = LocalLifecycleOwner.current val compactTunnelInterface = usesCompactTunnelInterface(interfaceRole) - val remoteActionAudience = - compactTunnelInterface || - interfaceRole == "admin" || - BuildConfig.REMOTE_ACTION_PREVIEW - val remoteActionFetchAllowed = remoteActionAudience - - LaunchedEffect(remoteActionFetchAllowed, lifecycleOwner) { - if (!remoteActionFetchAllowed) { - actionCatalog = com.wdtt.plus.RemoteActionCatalog.Empty - actionCatalogResolved = true - return@LaunchedEffect - } - if (RemoteActionCatalogGateway.hasFreshCache()) { - actionCatalog = RemoteActionCatalogGateway.cached() - actionCatalogResolved = true - } else { - actionCatalogResolved = false - } - lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { - while (isActive) { - actionCatalog = RemoteActionCatalogGateway.fetch(force = true) - actionCatalogResolved = true - delay(REMOTE_ACTION_REFRESH_MS) - } - } - } - - LaunchedEffect(activeProfile, remoteCardDismissCountdown > 0) { - if (remoteCardDismissCountdown <= 0) return@LaunchedEffect - while (remoteCardDismissCountdown > 0) { - delay(1_000) - remoteCardDismissCountdown-- - } - } - - LaunchedEffect(activeProfile, accessLifecycleDismissCountdown > 0) { - if (accessLifecycleDismissCountdown <= 0) return@LaunchedEffect - while (accessLifecycleDismissCountdown > 0) { - delay(1_000) - accessLifecycleDismissCountdown-- - } - } - - LaunchedEffect(activeProfile, accessLifecycle.managed) { - if (accessLifecycle.managed) { - AccessLifecycleCoordinator.refreshProfile(context, activeProfile, force = false) - } else { - TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS) - } - } val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle() + val warpResetBlockedMessage = "Для сброса отключите VPN" val tunnelTransition by TunnelManager.transition.collectAsStateWithLifecycle() val trustedWifiState by TrustedWifiManager.state.collectAsStateWithLifecycle() val trustedWifiWaiting = trustedWifiState.waiting @@ -382,42 +357,81 @@ fun SettingsTabContent( val cooldownActive by TunnelManager.cooldownActive.collectAsStateWithLifecycle() - val loadedHashSlots = remember(profileSnapshot) { parseVkHashSlots(savedVkHashesState) } - var peerInput by remember(profileSnapshot) { mutableStateOf(savedPeer) } - var vkHash1 by remember(profileSnapshot) { mutableStateOf(loadedHashSlots.getOrElse(0) { "" }) } - var vkHash2 by remember(profileSnapshot) { mutableStateOf(loadedHashSlots.getOrElse(1) { "" }) } - var vkHash3 by remember(profileSnapshot) { mutableStateOf(loadedHashSlots.getOrElse(2) { "" }) } - var vkHash4 by remember(profileSnapshot) { mutableStateOf(loadedHashSlots.getOrElse(3) { "" }) } - val loadedWorkers = remember(profileSnapshot) { + val loadedHashSlots = remember(activeProfile, savedVkHashesState) { + parseVkHashSlots(savedVkHashesState) + } + var peerInput by remember(activeProfile, savedPeer) { mutableStateOf(savedPeer) } + var vkHash1 by remember(activeProfile, savedVkHashesState) { + mutableStateOf(loadedHashSlots.getOrElse(0) { "" }) + } + var vkHash2 by remember(activeProfile, savedVkHashesState) { + mutableStateOf(loadedHashSlots.getOrElse(1) { "" }) + } + var vkHash3 by remember(activeProfile, savedVkHashesState) { + mutableStateOf(loadedHashSlots.getOrElse(2) { "" }) + } + var vkHash4 by remember(activeProfile, savedVkHashesState) { + mutableStateOf(loadedHashSlots.getOrElse(3) { "" }) + } + val loadedWorkers = remember( + activeProfile, + savedWorkers, + savedVkHashesState, + profileMaxWorkers, + ) { val normalized = normalizeTunnelWorkerCount(savedWorkers, profileMaxWorkers) roundToGroup( normalized.toFloat(), maxWorkersForHashSlots(loadedHashSlots, profileMaxWorkers) ) } - var workersInput by remember(profileSnapshot) { mutableFloatStateOf(loadedWorkers) } + var workersInput by remember(activeProfile, loadedWorkers) { + mutableFloatStateOf(loadedWorkers) + } var showHashesDialog by rememberSaveable { mutableStateOf(false) } - var autoCaptchaEnabled by remember(profileSnapshot) { + var profileRemoteAction by remember(activeProfile) { + mutableStateOf(RemoteActionCatalogGateway.cached().at("profile")) + } + LaunchedEffect(showHashesDialog, activeProfile) { + if (showHashesDialog) { + profileRemoteAction = RemoteActionCatalogGateway.fetch().at("profile") + } + } + var autoCaptchaEnabled by remember(activeProfile, savedCaptchaMode, savedCaptchaMethod) { mutableStateOf(savedCaptchaMode != "wv" || savedCaptchaMethod != "manual") } - var manualPortsEnabled by remember(profileSnapshot) { mutableStateOf(savedManualPortsEnabled) } + var manualPortsEnabled by remember(activeProfile, savedManualPortsEnabled) { + mutableStateOf(savedManualPortsEnabled) + } var showPowerHelp by rememberSaveable { mutableStateOf(false) } var showVkCallsHelp by rememberSaveable { mutableStateOf(false) } var showAutoCaptchaHelp by rememberSaveable { mutableStateOf(false) } - var serverDtlsPortInput by remember(profileSnapshot) { mutableStateOf(savedServerDtlsPort.toString()) } - var serverWgPortInput by remember(profileSnapshot) { mutableStateOf(savedServerWgPort.toString()) } + var showRtNetworkSettings by rememberSaveable { mutableStateOf(false) } + var showRtNetworkHelp by rememberSaveable { mutableStateOf(false) } + var showRtMasqueHelp by rememberSaveable { mutableStateOf(false) } + var showRtMasqueServerBootstrapHelp by rememberSaveable { mutableStateOf(false) } + var showRtMasqueConsent by rememberSaveable { mutableStateOf(false) } + var showRtMasqueResetConfirm by rememberSaveable { mutableStateOf(false) } + var serverDtlsPortInput by remember(activeProfile, savedServerDtlsPort) { + mutableStateOf(savedServerDtlsPort.toString()) + } + var serverWgPortInput by remember(activeProfile, savedServerWgPort) { + mutableStateOf(savedServerWgPort.toString()) + } var userConnectionEditor by remember(activeProfile) { mutableStateOf("") } var userLinkInput by remember(activeProfile) { mutableStateOf("") } - val storedLinkSelected = remember(profileSnapshot) { + val storedLinkSelected = remember(activeProfile, savedConnectionInputMethod, wdttLinkMode) { wdttLinkMode && WdttDeepLink.parse(wdttLink, allowMissingHashes = true) != null } - val importedLinkStoredAsManualFields = remember(profileSnapshot) { - savedConnectionInputMethod == "link" && - !wdttLinkMode && - savedPeer.isNotBlank() && - savedConnectionPassword.isNotBlank() - } - var userConnectionMethod by remember(profileSnapshot) { + var userConnectionMethod by remember( + activeProfile, + savedConnectionInputMethod, + wdttLinkMode, + wdttLink, + savedPeer, + savedConnectionPassword, + interfaceRole, + ) { mutableStateOf( resolveConnectionInputMethod( savedMethod = savedConnectionInputMethod, @@ -446,8 +460,13 @@ fun SettingsTabContent( val dynamicMaxWorkers = remember(filledHashCount, profileMaxWorkers) { maxWorkersForHashCount(filledHashCount, profileMaxWorkers) } - var portInput by remember(profileSnapshot) { mutableStateOf(savedListenPort.toString()) } - var sniInput by remember(profileSnapshot) { mutableStateOf(savedSni) } + var portInput by remember(activeProfile, savedListenPort) { + mutableStateOf(savedListenPort.toString()) + } + var sniInput by remember(activeProfile, savedSni) { mutableStateOf(savedSni) } + var rtTurnSniInput by remember(activeProfile, savedRtTurnSni) { + mutableStateOf(savedRtTurnSni) + } val currentWorkers = workersInput.coerceIn(WORKERS_PER_GROUP.toFloat(), dynamicMaxWorkers) @@ -534,7 +553,8 @@ fun SettingsTabContent( linkValid = isLinkValid, manualValid = isManualValid, ) - val isValid = selectedCompactMethodValid + val rtSniValid = !rtNetwork || normalizeRtTurnSni(rtTurnSniInput) != null + val isValid = selectedCompactMethodValid && rtSniValid val hasConnectionSource = hasTunnelConnectionSource( linkMode = wdttLinkMode, linkValid = linkConnectionPresent, @@ -584,6 +604,10 @@ fun SettingsTabContent( 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) @@ -657,7 +681,7 @@ fun SettingsTabContent( } catch (error: Exception) { TunnelManager.clearTransition() TunnelManager.reportConnectionIssue( - if (accessLifecycle.managed) { + if (remoteManagedProfile) { "Не удалось проверить доступ" } else { "Не удалось начать подключение" @@ -760,6 +784,9 @@ fun SettingsTabContent( } if (WdttDeepLink.parse(cleanLink, allowMissingHashes = true) == null) return scope.launch { + val managedAccess = withContext(Dispatchers.IO) { + settingsStore.accessLifecycleForProfile(activeProfile).managed + } val result = settingsStore.applyWdttDeepLink( plan = WdttDeepLinkApplyPlan( link = cleanLink, @@ -767,7 +794,7 @@ fun SettingsTabContent( requiresConfirmation = hasConnectionSource, storeAsLink = false ), - resetRemoteContinuation = true, + resetRemoteContinuation = !managedAccess, remoteManaged = false ) if (result == null) { @@ -803,7 +830,6 @@ fun SettingsTabContent( }, onSave = ::saveUserWdttLink, allowMissingHashes = true, - importedLinkStoredAsManualFields = importedLinkStoredAsManualFields, remoteUpdateOnly = userConnectionEditor == "remote-update" || remoteManagedProfile, cachedAction = cachedRemoteAction, onCachedAction = { @@ -918,9 +944,16 @@ fun SettingsTabContent( } if (showHashesDialog) { + val activeAccessSnapshot by + settingsStore.activeTunnelAccessUiSnapshot.collectAsStateWithLifecycle() + val accessLifecycle = activeAccessSnapshot + ?.takeIf { it.profileIndex == activeProfile } + ?.lifecycle + ?: AccessLifecycleUiState.Unmanaged val hashCheckCaptchaMode = if (autoCaptchaEnabled) "auto" else "wv" HashesDialog( settingsStore = settingsStore, + profileIndex = activeProfile, hash1 = vkHash1, hash2 = vkHash2, hash3 = vkHash3, @@ -931,11 +964,17 @@ fun SettingsTabContent( customVkClientId = customVkClientId, customVkClientSecret = customVkClientSecret, remoteContinuation = RemoteContinuation( - available = remoteActionKey.isNotBlank() && remoteActionUrl.isNotBlank(), + available = boundContinuationAvailable( + hasCredential = remoteActionKey.isNotBlank(), + hasEndpoint = remoteActionUrl.isNotBlank(), + remoteAvailability = accessLifecycle.continuationAvailable, + expiresAtSeconds = accessLifecycle.continuationExpiresAtSeconds, + ), key = remoteActionKey, url = remoteActionUrl ), - remoteAction = actionCatalog.at("profile"), + remoteAccessLifecycle = accessLifecycle, + remoteAction = profileRemoteAction, vkCallsPreflight = vkCallsPreflight, captchaMode = hashCheckCaptchaMode, selectedWebViewManual = !autoCaptchaEnabled, @@ -977,52 +1016,14 @@ fun SettingsTabContent( verticalArrangement = Arrangement.spacedBy(12.dp) ) { Column { - val tunnelAction = actionCatalog.at("tunnel") - if (shouldShowTunnelRemoteActionCard( - interfaceRole = interfaceRole, - preview = BuildConfig.REMOTE_ACTION_PREVIEW, - hasConnectionSource = hasConnectionSource, - dismissed = remoteCardDismissed, - dismissCountdown = remoteCardDismissCountdown, - actionResolved = actionCatalogResolved, - actionAvailable = tunnelAction != null, - ) - ) { - Column { - if (remoteCardDismissCountdown > 0) { - DismissedNoticeCard( - title = "Предложение скрыто", - message = "Ссылку всегда можно найти в «Инфо» → «Поддержать проект».", - countdown = remoteCardDismissCountdown, - onProjectSupportClick = onOpenProjectSupport, - ) - } else if (tunnelAction != null) { - RemoteActionCard( - action = tunnelAction, - onLinkClick = onOpenProjectSupport, - onClick = { - scope.launch { - val opened = RemoteUiActionLauncher.open(context, tunnelAction) - if (!opened) { - Toast.makeText( - context, - "Не удалось открыть страницу. Проверьте браузер.", - Toast.LENGTH_LONG - ).show() - } - } - }, - onDismiss = { - remoteCardDismissCountdown = 5 - scope.launch { - settingsStore.saveRemoteCardDismissed(activeProfile, true) - } - } - ) - } - Spacer(Modifier.height(12.dp)) - } - } + TunnelRemoteActionSection( + settingsStore = settingsStore, + activeProfile = activeProfile, + interfaceRole = interfaceRole, + hasConnectionSource = hasConnectionSource, + dismissed = remoteCardDismissed, + onOpenProjectSupport = onOpenProjectSupport, + ) Text( "Настройки туннеля (${vpnProfileDisplayName(activeProfile, profileNames)})", @@ -1031,139 +1032,12 @@ fun SettingsTabContent( modifier = Modifier.padding(bottom = 12.dp) ) - val accessDismissible = - accessLifecycle.allowConnect && - accessLifecycle.severity == AccessLifecycleSeverity.WARNING - val accessDismissSignature = accessLifecycleDismissalSignature(accessLifecycle) - val accessDismissed = - accessDismissible && - accessDismissSignature.isNotBlank() && - accessDismissSignature == accessLifecycleDismissedSignature - val routeUpdateAvailable = remoteManagedProfile - val accessCardDismissed = - accessDismissible && - accessDismissed && - accessLifecycleDismissCountdown <= 0 && - !routeUpdateAvailable - if ( - accessLifecycle.managed && - !accessCardDismissed - ) { - if (accessLifecycleDismissCountdown > 0 && !routeUpdateAvailable) { - DismissedNoticeCard( - title = "Напоминание скрыто", - message = "Действие для профиля остаётся доступно после следующей проверки.", - countdown = accessLifecycleDismissCountdown, - ) - } else { - AccessLifecycleCard( - lifecycle = accessLifecycle, - refreshing = accessRefreshing || accessManualRefreshBusy, - actionBusy = accessActionBusy, - onRouteUpdate = if (routeUpdateAvailable) { - ::openRemoteUpdateEditor - } else { - null - }, - onDismiss = if (accessDismissible) { - { - accessLifecycleDismissCountdown = 5 - scope.launch { - settingsStore.saveAccessLifecycleDismissedSignature( - activeProfile, - accessDismissSignature, - ) - } - } - } else { - null - }, - onRefresh = { - if (accessManualRefreshBusy) return@AccessLifecycleCard - accessManualRefreshBusy = true - scope.launch { - val startedAt = System.currentTimeMillis() - try { - when ( - val result = AccessLifecycleCoordinator.refreshProfile( - context, - activeProfile, - force = true, - ) - ) { - is AccessLifecycleRefreshResult.Success -> Toast.makeText( - context, - "Данные обновлены", - Toast.LENGTH_SHORT, - ).show() - is AccessLifecycleRefreshResult.Cached -> Toast.makeText( - context, - "Данные уже актуальны", - Toast.LENGTH_SHORT, - ).show() - is AccessLifecycleRefreshResult.Throttled -> Toast.makeText( - context, - "Проверено недавно. Повторите через несколько секунд", - Toast.LENGTH_SHORT, - ).show() - is AccessLifecycleRefreshResult.Failed -> Toast.makeText( - context, - result.message, - Toast.LENGTH_LONG, - ).show() - AccessLifecycleRefreshResult.Unmanaged -> Toast.makeText( - context, - "Проверка недоступна", - Toast.LENGTH_SHORT, - ).show() - } - } finally { - val visibleFor = System.currentTimeMillis() - startedAt - if (visibleFor < 450) delay(450 - visibleFor) - accessManualRefreshBusy = false - } - } - }, - onAction = { - if (accessActionBusy) return@AccessLifecycleCard - accessActionBusy = true - scope.launch { - runCatching { - AccessLifecycleCoordinator.beginAction( - context, - activeProfile, - ) - }.onSuccess { target -> - runCatching { - launchRemoteTarget(context, target) - }.onFailure { error -> - if (error is CancellationException) throw error - Toast.makeText( - context, - error.message ?: "Не удалось открыть страницу.", - Toast.LENGTH_LONG, - ).show() - } - }.onFailure { error -> - if (error is CancellationException) throw error - TunnelManager.noteAccessLifecycleEvent( - key = "action_unavailable_$activeProfile", - message = error.message ?: "Действие сейчас недоступно", - warning = true, - ) - Toast.makeText( - context, - error.message ?: "Действие сейчас недоступно.", - Toast.LENGTH_LONG, - ).show() - } - accessActionBusy = false - } - } - ) - } - Spacer(Modifier.height(12.dp)) - } + ManagedAccessLifecycleSection( + settingsStore = settingsStore, + activeProfile = activeProfile, + routeUpdateAvailable = remoteManagedProfile, + onRouteUpdate = ::openRemoteUpdateEditor, + ) if (!remoteManagedProfile) { CompactTunnelProfileCard( @@ -1178,17 +1052,17 @@ fun SettingsTabContent( onAddLinkClick = ::openUserLinkEditor, onManualClick = ::openUserManualEditor, ) - Spacer(Modifier.height(12.dp)) + Spacer(Modifier.height(8.dp)) } AppSectionCard( - contentPadding = PaddingValues(16.dp), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(0.dp) ) { OutlinedButton( onClick = ::openHashesSettings, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), shape = RoundedCornerShape(16.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp) ) { Icon(Icons.Default.Tag, contentDescription = null, modifier = Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) @@ -1257,11 +1131,11 @@ fun SettingsTabContent( } } - Spacer(Modifier.height(12.dp)) + Spacer(Modifier.height(8.dp)) // ═══ Мощность + Капча ═══ AppSectionCard( - contentPadding = PaddingValues(16.dp), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp), verticalArrangement = Arrangement.spacedBy(0.dp) ) { // — Мощность — @@ -1299,7 +1173,7 @@ fun SettingsTabContent( ) } - Spacer(Modifier.height(4.dp)) + Spacer(Modifier.height(2.dp)) val maxWorkers = dynamicMaxWorkers val minWorkers = WORKERS_PER_GROUP.toFloat() @@ -1332,13 +1206,13 @@ fun SettingsTabContent( // — Разделитель — HorizontalDivider( - modifier = Modifier.padding(vertical = 4.dp), + modifier = Modifier.padding(vertical = 2.dp), color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) ) // — VKCalls preflight — Row( - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), + modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { @@ -1374,13 +1248,13 @@ fun SettingsTabContent( } HorizontalDivider( - modifier = Modifier.padding(vertical = 4.dp), + modifier = Modifier.padding(vertical = 2.dp), color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) ) // — Режим капчи — Row( - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), + modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { @@ -1421,6 +1295,59 @@ fun SettingsTabContent( ) } + HorizontalDivider( + modifier = Modifier.padding(vertical = 2.dp), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) + ) + + // — Ограниченная мобильная сеть Ростелекома — + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + modifier = Modifier.weight(1f), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Text( + "Сеть РТ", + modifier = Modifier + .clickable { showRtNetworkSettings = true } + .padding(vertical = 10.dp), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium + ) + IconButton( + onClick = { showRtNetworkHelp = true }, + modifier = Modifier.size(28.dp), + ) { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Как работает Сеть РТ", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp), + ) + } + } + Switch( + checked = rtNetwork, + enabled = !tunnelRunning, + onCheckedChange = { enabled -> + saveJob?.cancel() + val nextSni = if (enabled) { + normalizeRtTurnSni(rtTurnSniInput) ?: DEFAULT_RT_TURN_SNI + } else { + rtTurnSniInput.trim() + } + rtTurnSniInput = nextSni + scope.launch { settingsStore.saveRtNetwork(enabled, nextSni) } + if (enabled) showRtNetworkSettings = true + } + ) + } + } } @@ -1570,6 +1497,40 @@ fun SettingsTabContent( } } + if (showRtNetworkSettings) { + RtNetworkSettingsDialog( + rtNetwork = rtNetwork, + turnSni = rtTurnSniInput, + turnSniValid = normalizeRtTurnSni(rtTurnSniInput) != null, + rtMasque = rtMasque, + rtMasqueServerBootstrap = effectiveRtMasqueServerBootstrap, + serverAccess = rtMasqueServerAccess, + tunnelRunning = tunnelRunning, + onTurnSniChange = { value -> + val nextSni = value.filterNot(Char::isWhitespace).take(253) + rtTurnSniInput = nextSni + saveJob?.cancel() + saveJob = scope.launch { + delay(300) + settingsStore.saveRtNetwork(enabled = true, turnSni = nextSni) + } + }, + onRtMasqueChange = { enabled -> + if (enabled) { + showRtMasqueConsent = true + } else { + scope.launch { settingsStore.saveRtMasque(false) } + } + }, + onServerBootstrapChange = { enabled -> + scope.launch { settingsStore.saveRtMasqueServerBootstrap(enabled) } + }, + onShowRtHelp = { showRtNetworkHelp = true }, + onShowMasqueHelp = { showRtMasqueHelp = true }, + onShowServerHelp = { showRtMasqueServerBootstrapHelp = true }, + onDismiss = { showRtNetworkSettings = false }, + ) + } if (showPowerHelp) { PowerHelpDialog( minWorkers = WORKERS_PER_GROUP, @@ -1601,6 +1562,407 @@ fun SettingsTabContent( onDismiss = { showAutoCaptchaHelp = false } ) } + if (showRtNetworkHelp) { + SettingsHelpDialog( + title = "Сеть РТ", + paragraphs = listOf( + "Режим предназначен для мобильной сети Ростелекома с белыми списками: разрешённые сайты открываются, но обычный WDTT Plus не подключается. В сети РТ без таких ограничений, у других операторов и по обычному Wi‑Fi он, как правило, не нужен.", + "При включении порядок меняется только для этого профиля: TURN/TLS с указанным SNI → TURN/TCP ко всем адресам, полученным от VK, с разделением первого STUN-запроса → MASQUE HTTP/2 и HTTP/3, если он включён → TURN/UDP как последний резерв. При выключенном режиме сохраняется обычный порядок с приоритетом UDP.", + "SNI по умолчанию — ya.ru; его можно заменить доступным доменом из белого списка. Это только имя во внешнем TLS-рукопожатии TURN/TLS и MASQUE: трафик не становится трафиком этого сайта, а TURN/TCP и TURN/UDP вообще не содержат SNI.", + "Для TURN/TLS приложение продолжает проверять публичную цепочку сертификата, но при подмене SNI не сопоставляет имя сертификата с доменом белого списка. MASQUE проверяет конечную точку по публичному ключу из регистрации WARP. Пароль подключения и шифрование WRAP не меняются.", + "Оператор может одновременно учитывать SNI, IP, порт и протокол, поэтому один SNI не гарантирует результат. TURN/TLS/TCP и MASQUE используют разные адреса и механизмы: рабочий вариант определяется только проверкой в конкретном регионе и тарифе.", + "TLS и TCP обычно дают большую задержку и хуже переносят потери, а MASQUE дополнительно расходует батарею и трафик. Если обычный режим работает, оставьте «Сеть РТ» выключенной.", + "После заблокированной UDP-попытки сеть иногда несколько минут плохо пропускает DNS или другой трафик. Перед повторной проверкой остановите VPN, дождитесь восстановления сайтов или переподключите мобильную сеть, затем запускайте режим заново." + ), + highlightedParagraphIndices = setOf(6), + onDismiss = { showRtNetworkHelp = false } + ) + } + if (showRtMasqueHelp) { + SettingsHelpDialog( + title = "MASQUE в сети РТ", + paragraphs = listOf( + "Экспериментальный резерв только внутри «Сети РТ». После прямых TURN/TLS и TURN/TCP приложение пробует WARP CONNECT-IP с SNI из поля настроек; TURN/UDP остаётся последним аварийным путём.", + "Сначала проверяется HTTP/2 по TCP/443, затем HTTP/3 по QUIC/443. Успешный вариант совместно используется воркерами до остановки VPN; при новом запуске проверка выполняется заново, потому что доступность путей могла измениться.", + "Для первого запуска приложение регистрирует отдельное устройство Cloudflare WARP. Корректная регистрация хранится только в приватном каталоге WDTT Plus и повторно используется после перезапуска приложения и выключения рубильников — заново создавать её при каждом подключении не требуется.", + "Регистрация сначала выполняется через системную сеть и DNS Android с проверкой сертификата Cloudflare. Если прямой TLS не проходит до отправки данных и включён «Через сервер», последняя попытка регистрации идёт по SSH через сервер активного профиля. Обычный MASQUE-трафик через этот сервер не направляется.", + "Cloudflare обрабатывает внешний туннель и может видеть служебные метаданные и адреса назначения. Конечная точка MASQUE проверяется по публичному ключу сохранённой регистрации WARP, а шифрование WRAP между приложением и вашим WDTT-сервером сохраняется.", + "Режим может увеличить первый запуск, задержку, расход батареи и трафика и не гарантирует обход блокировки IP, TCP/443 или QUIC/443. Он активен только при одновременно включённых «Сеть РТ» и MASQUE; остальные режимы не меняются.", + "Сбрасывайте регистрацию WARP только при сообщении о повреждённых или отклонённых данных. Сброс удаляет локальные ключи, и следующему запуску снова понадобится регистрация; обычную сетевую блокировку это не исправляет." + ), + onDismiss = { showRtMasqueHelp = false }, + secondaryActionLabel = "Сбросить регистрацию WARP", + secondaryActionEnabled = !tunnelRunning, + onSecondaryActionDisabled = { + Toast.makeText(context, warpResetBlockedMessage, Toast.LENGTH_LONG).show() + }, + onSecondaryAction = { + if (tunnelRunning) { + Toast.makeText(context, warpResetBlockedMessage, Toast.LENGTH_LONG).show() + } else { + showRtMasqueHelp = false + showRtMasqueResetConfirm = true + } + }, + ) + } + if (showRtMasqueServerBootstrapHelp) { + SettingsHelpDialog( + title = "Регистрация через сервер", + paragraphs = listOf( + "Помогает выполнить первоначальную регистрацию WARP, если Android не может напрямую установить TLS-соединение с API Cloudflare. Режим работает лишь вместе с «Сеть РТ» и MASQUE; обычный трафик WDTT, TURN и последующие соединения MASQUE через сервер не проходят.", + "Рубильник доступен, если в активном профиле раздела «Деплой» указан адрес сервера и выбран рабочий вход по SSH: пароль либо корректный приватный ключ. Если данных не хватает, рядом с выключенным рубильником указана точная причина.", + "Вероятнее всего, нужен иностранный сервер за пределами РФ — российский сервер может встретить те же ограничения доступа к Cloudflare.", + "SSH-сервер должен быть доступен из текущей сети и разрешать TCP-переадресацию.", + "На сервер ничего не устанавливается. WDTT Plus временно использует стандартную SSH-переадресацию только для HTTPS-запросов регистрации; сертификат Cloudflare проверяется сквозным TLS. Cloudflare видит IP сервера, а владелец сервера — факт соединения и объём, но не содержимое HTTPS.", + "Сначала приложение всё равно пробует прямые безопасные HTTPS-пути. К SSH оно переходит только при сбое до отправки регистрационных данных, поэтому запрос не дублируется небезопасным образом. Ошибка SSH записывается в журнал, а незавершённая регистрация не сохраняется.", + "После успешной регистрации SSH-выход закрывается, а данные WARP сохраняются в приватном хранилище. Пока сохранённая регистрация корректна, приложение не создаёт новую и рубильник фактически не используется — даже после перезапуска или временного выключения «Сети РТ» и MASQUE." + ), + highlightedParagraphIndices = setOf(2), + onDismiss = { showRtMasqueServerBootstrapHelp = false }, + ) + } + if (showRtMasqueConsent) { + val linkColor = MaterialTheme.colorScheme.primary + val cloudflareTerms = buildAnnotatedString { + append("Включая механизм, вы соглашаетесь с ") + withLink( + LinkAnnotation.Url( + url = "https://www.cloudflare.com/application/terms/", + styles = TextLinkStyles( + style = SpanStyle( + color = linkColor, + fontWeight = FontWeight.SemiBold, + textDecoration = TextDecoration.Underline, + ), + ), + ), + ) { + append("условиями Cloudflare") + } + append(" и разрешаете WDTT Plus зарегистрировать отдельное устройство WARP.") + } + AlertDialog( + onDismissRequest = { showRtMasqueConsent = false }, + title = { Text("Включить MASQUE?") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text("Это внешний экспериментальный транспорт. Cloudflare будет обрабатывать туннель и сможет видеть метаданные подключений. При первом запуске VPN приложение в фоне зарегистрирует отдельное устройство WARP; для этого может потребоваться обычный интернет.") + Text(cloudflareTerms) + } + }, + confirmButton = { + TextButton( + onClick = { + showRtMasqueConsent = false + scope.launch { settingsStore.saveRtMasque(true) } + }, + ) { Text("Согласен, включить") } + }, + dismissButton = { + TextButton(onClick = { showRtMasqueConsent = false }) { + Text("Отмена") + } + }, + ) + } + if (showRtMasqueResetConfirm) { + AlertDialog( + onDismissRequest = { showRtMasqueResetConfirm = false }, + title = { Text("Сбросить регистрацию WARP?") }, + text = { + Text( + "Будут удалены только локальные ключи и токен WARP. При следующем запуске VPN с включённым MASQUE приложение зарегистрирует новое устройство. Используйте это при сообщении о повреждённой или отклонённой конфигурации; обычную блокировку HTTP/2 или HTTP/3 такой сброс не исправляет." + ) + }, + confirmButton = { + TextButton( + onClick = { + if (TunnelManager.running.value) { + showRtMasqueResetConfirm = false + Toast.makeText(context, warpResetBlockedMessage, Toast.LENGTH_LONG).show() + return@TextButton + } + showRtMasqueResetConfirm = false + scope.launch { + val result = withContext(Dispatchers.IO) { + val config = File(context.filesDir, RT_MASQUE_CONFIG_FILE_NAME) + when { + !config.exists() -> "Регистрация WARP ещё не создана" + config.delete() -> "Локальная регистрация WARP сброшена" + else -> "Не удалось удалить регистрацию WARP" + } + } + Toast.makeText(context, result, Toast.LENGTH_LONG).show() + } + }, + ) { Text("Сбросить") } + }, + dismissButton = { + TextButton(onClick = { showRtMasqueResetConfirm = false }) { + Text("Отмена") + } + }, + ) + } +} + +@Composable +private fun TunnelRemoteActionSection( + settingsStore: SettingsStore, + activeProfile: Int, + interfaceRole: String, + hasConnectionSource: Boolean, + dismissed: Boolean, + onOpenProjectSupport: () -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val lifecycleOwner = LocalLifecycleOwner.current + val fetchAllowed = + usesCompactTunnelInterface(interfaceRole) || + interfaceRole == "admin" || + BuildConfig.REMOTE_ACTION_PREVIEW + var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) } + var actionResolved by remember { + mutableStateOf(RemoteActionCatalogGateway.hasFreshCache()) + } + var dismissCountdown by remember(activeProfile) { mutableIntStateOf(0) } + + LaunchedEffect(fetchAllowed, lifecycleOwner) { + if (!fetchAllowed) { + actionCatalog = com.wdtt.plus.RemoteActionCatalog.Empty + actionResolved = true + return@LaunchedEffect + } + if (RemoteActionCatalogGateway.hasFreshCache()) { + actionCatalog = RemoteActionCatalogGateway.cached() + actionResolved = true + } else { + actionResolved = false + } + lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { + while (isActive) { + actionCatalog = RemoteActionCatalogGateway.fetch(force = true) + actionResolved = true + delay(REMOTE_ACTION_REFRESH_MS) + } + } + } + LaunchedEffect(activeProfile, dismissCountdown > 0) { + if (dismissCountdown <= 0) return@LaunchedEffect + while (dismissCountdown > 0) { + delay(1_000) + dismissCountdown-- + } + } + + val action = actionCatalog.at("tunnel") + if (!shouldShowTunnelRemoteActionCard( + interfaceRole = interfaceRole, + preview = BuildConfig.REMOTE_ACTION_PREVIEW, + hasConnectionSource = hasConnectionSource, + dismissed = dismissed, + dismissCountdown = dismissCountdown, + actionResolved = actionResolved, + actionAvailable = action != null, + ) + ) { + return + } + if (dismissCountdown > 0) { + DismissedNoticeCard( + title = "Предложение скрыто", + message = "Ссылку всегда можно найти в «Инфо» → «Поддержать проект».", + countdown = dismissCountdown, + onProjectSupportClick = onOpenProjectSupport, + ) + } else if (action != null) { + RemoteActionCard( + action = action, + onLinkClick = onOpenProjectSupport, + onClick = { + scope.launch { + val opened = RemoteUiActionLauncher.open(context, action) + if (!opened) { + Toast.makeText( + context, + "Не удалось открыть страницу. Проверьте браузер.", + Toast.LENGTH_LONG, + ).show() + } + } + }, + onDismiss = { + dismissCountdown = 5 + scope.launch { + settingsStore.saveRemoteCardDismissed(activeProfile, true) + } + }, + ) + } + Spacer(Modifier.height(12.dp)) +} + +@Composable +private fun ManagedAccessLifecycleSection( + settingsStore: SettingsStore, + activeProfile: Int, + routeUpdateAvailable: Boolean, + onRouteUpdate: () -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val activeAccessSnapshot by + settingsStore.activeTunnelAccessUiSnapshot.collectAsStateWithLifecycle() + val lifecycle = activeAccessSnapshot + ?.takeIf { it.profileIndex == activeProfile } + ?.lifecycle + ?: AccessLifecycleUiState.Unmanaged + val dismissedSignature = activeAccessSnapshot + ?.takeIf { it.profileIndex == activeProfile } + ?.dismissedSignature + .orEmpty() + val refreshingProfiles by + AccessLifecycleCoordinator.refreshingProfiles.collectAsStateWithLifecycle() + val refreshing = activeProfile in refreshingProfiles + var actionBusy by remember(activeProfile) { mutableStateOf(false) } + var manualRefreshBusy by remember(activeProfile) { mutableStateOf(false) } + var dismissCountdown by remember(activeProfile) { mutableIntStateOf(0) } + + LaunchedEffect(activeProfile, lifecycle.managed) { + if (lifecycle.managed) { + AccessLifecycleCoordinator.refreshProfile(context, activeProfile, force = false) + } else { + TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS) + } + } + LaunchedEffect(activeProfile, dismissCountdown > 0) { + if (dismissCountdown <= 0) return@LaunchedEffect + while (dismissCountdown > 0) { + delay(1_000) + dismissCountdown-- + } + } + + if (!lifecycle.managed) return + val canDismiss = accessLifecycleCanDismiss(lifecycle) + val signature = accessLifecycleDismissalSignature(lifecycle) + val dismissed = canDismiss && signature.isNotBlank() && signature == dismissedSignature + val keepVisibleForRouteUpdate = routeUpdateAvailable && lifecycle.dismissible != true + val cardDismissed = + dismissed && dismissCountdown <= 0 && !keepVisibleForRouteUpdate + if (cardDismissed) return + + if (dismissCountdown > 0 && !keepVisibleForRouteUpdate) { + DismissedNoticeCard( + title = "Карточка скрыта", + message = lifecycle.dismissedMessage.ifBlank { + "Актуальная информация и доступные действия остаются у поставщика профиля." + }, + countdown = dismissCountdown, + ) + } else { + AccessLifecycleCard( + lifecycle = lifecycle, + refreshing = refreshing || manualRefreshBusy, + actionBusy = actionBusy, + onRouteUpdate = if (routeUpdateAvailable) onRouteUpdate else null, + onDismiss = if (canDismiss) { + { + dismissCountdown = 5 + scope.launch { + settingsStore.saveAccessLifecycleDismissedSignature( + activeProfile, + signature, + ) + } + } + } else { + null + }, + onRefresh = { + if (manualRefreshBusy) return@AccessLifecycleCard + manualRefreshBusy = true + scope.launch { + val startedAt = System.currentTimeMillis() + try { + when ( + val result = AccessLifecycleCoordinator.refreshProfile( + context, + activeProfile, + force = true, + ) + ) { + is AccessLifecycleRefreshResult.Success -> Toast.makeText( + context, + "Данные обновлены", + Toast.LENGTH_SHORT, + ).show() + is AccessLifecycleRefreshResult.Cached -> Toast.makeText( + context, + "Данные уже актуальны", + Toast.LENGTH_SHORT, + ).show() + is AccessLifecycleRefreshResult.Throttled -> Toast.makeText( + context, + "Проверено недавно. Повторите через несколько секунд", + Toast.LENGTH_SHORT, + ).show() + is AccessLifecycleRefreshResult.Failed -> Toast.makeText( + context, + result.message, + Toast.LENGTH_LONG, + ).show() + AccessLifecycleRefreshResult.Unmanaged -> Toast.makeText( + context, + "Проверка недоступна", + Toast.LENGTH_SHORT, + ).show() + } + } finally { + val visibleFor = System.currentTimeMillis() - startedAt + if (visibleFor < 450) delay(450 - visibleFor) + manualRefreshBusy = false + } + } + }, + onAction = { + if (actionBusy) return@AccessLifecycleCard + actionBusy = true + scope.launch { + runCatching { + AccessLifecycleCoordinator.beginAction(context, activeProfile) + }.onSuccess { target -> + runCatching { + launchRemoteTarget(context, target) + }.onFailure { error -> + if (error is CancellationException) throw error + Toast.makeText( + context, + error.message ?: "Не удалось открыть страницу.", + Toast.LENGTH_LONG, + ).show() + } + }.onFailure { error -> + if (error is CancellationException) throw error + TunnelManager.noteAccessLifecycleEvent( + key = "action_unavailable_$activeProfile", + message = error.message ?: "Действие сейчас недоступно", + warning = true, + ) + Toast.makeText( + context, + error.message ?: "Действие сейчас недоступно.", + Toast.LENGTH_LONG, + ).show() + } + actionBusy = false + } + }, + ) + } + Spacer(Modifier.height(12.dp)) } @Composable @@ -1629,7 +1991,8 @@ private fun AccessLifecycleCard( val icon = when { lifecycle.checkedAtMillis <= 0 -> Icons.Default.Schedule !lifecycle.allowConnect -> Icons.Default.Lock - severity == AccessLifecycleSeverity.WARNING -> Icons.Default.WarningAmber + severity == AccessLifecycleSeverity.WARNING || + severity == AccessLifecycleSeverity.ERROR -> Icons.Default.WarningAmber else -> Icons.Default.CheckCircle } val title = lifecycle.title.ifBlank { @@ -1724,59 +2087,97 @@ private fun AccessLifecycleCard( ) } if (lifecycle.detailValue.isNotBlank() || lifecycle.actionAvailable) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - if (lifecycle.detailValue.isNotBlank()) { + val actionLabel = lifecycle.actionLabel.ifBlank { "Продолжить" } + val textMeasurer = rememberTextMeasurer() + val density = LocalDensity.current + val detailLabelWidth = with(density) { + textMeasurer.measure( + text = lifecycle.detailLabel, + style = MaterialTheme.typography.bodySmall, + maxLines = 1, + softWrap = false, + ).size.width.toDp() + } + val detailValueWidth = with(density) { + textMeasurer.measure( + text = lifecycle.detailValue, + style = MaterialTheme.typography.bodyMedium.copy( + fontWeight = FontWeight.SemiBold, + ), + maxLines = 1, + softWrap = false, + ).size.width.toDp() + } + val actionLabelWidth = with(density) { + textMeasurer.measure( + text = actionLabel, + style = MaterialTheme.typography.labelLarge.copy( + fontWeight = FontWeight.SemiBold, + ), + maxLines = 1, + softWrap = false, + ).size.width.toDp() + } + + BoxWithConstraints(modifier = Modifier.fillMaxWidth()) { + val hasDetail = lifecycle.detailValue.isNotBlank() + val hasAction = lifecycle.actionAvailable + val detailPreferredWidth = maxOf( + 120.dp, + detailLabelWidth, + detailValueWidth, + ) + val actionPreferredWidth = maxOf( + 132.dp, + actionLabelWidth + 46.dp, + ) + val stackContent = hasAction && ( + !hasDetail || + detailPreferredWidth + 12.dp + actionPreferredWidth > maxWidth + ) + + if (stackContent) { Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(2.dp), + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(10.dp), ) { - if (lifecycle.detailLabel.isNotBlank()) { - Text( - text = lifecycle.detailLabel, - style = MaterialTheme.typography.bodySmall, - color = accent.copy(alpha = 0.78f), + if (hasDetail) { + AccessLifecycleDetail( + lifecycle = lifecycle, + accent = accent, + modifier = Modifier.fillMaxWidth(), ) } - Text( - text = lifecycle.detailValue, - style = MaterialTheme.typography.bodyMedium, - color = accent, - fontWeight = FontWeight.SemiBold, + AccessLifecycleActionButton( + lifecycle = lifecycle, + label = actionLabel, + refreshing = refreshing, + actionBusy = actionBusy, + onAction = onAction, + modifier = Modifier.fillMaxWidth(), ) } } else { - Spacer(Modifier.weight(1f)) - } - if (lifecycle.actionAvailable) { - Button( - onClick = onAction, - enabled = !refreshing && !actionBusy, - modifier = Modifier - .widthIn(min = 132.dp) - .heightIn(min = 46.dp), - shape = RoundedCornerShape(14.dp), - contentPadding = PaddingValues( - horizontal = 8.dp, - vertical = 6.dp, - ), + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - if (actionBusy) { - CircularProgressIndicator( - modifier = Modifier.size(17.dp), - strokeWidth = 2.dp, - color = MaterialTheme.colorScheme.onPrimary, + if (hasDetail) { + AccessLifecycleDetail( + lifecycle = lifecycle, + accent = accent, + modifier = Modifier.weight(1f), ) - } else { - if (lifecycle.actionIcon == "update") { - Icon(Icons.Default.Update, null, Modifier.size(17.dp)) - Spacer(Modifier.width(5.dp)) - } - FlexibleButtonText( - lifecycle.actionLabel.ifBlank { "Продолжить" } + } + if (hasAction) { + AccessLifecycleActionButton( + lifecycle = lifecycle, + label = actionLabel, + refreshing = refreshing, + actionBusy = actionBusy, + onAction = onAction, + modifier = Modifier.width(actionPreferredWidth), ) } } @@ -1787,11 +2188,80 @@ private fun AccessLifecycleCard( } } +@Composable +private fun AccessLifecycleDetail( + lifecycle: AccessLifecycleUiState, + accent: Color, + modifier: Modifier = Modifier, +) { + Column( + modifier = modifier, + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + if (lifecycle.detailLabel.isNotBlank()) { + Text( + text = lifecycle.detailLabel, + style = MaterialTheme.typography.bodySmall, + color = accent.copy(alpha = 0.78f), + ) + } + Text( + text = lifecycle.detailValue, + style = MaterialTheme.typography.bodyMedium, + color = accent, + fontWeight = FontWeight.SemiBold, + ) + } +} + +@Composable +private fun AccessLifecycleActionButton( + lifecycle: AccessLifecycleUiState, + label: String, + refreshing: Boolean, + actionBusy: Boolean, + onAction: () -> Unit, + modifier: Modifier = Modifier, +) { + Button( + onClick = onAction, + enabled = !refreshing && !actionBusy, + modifier = modifier.heightIn(min = 46.dp), + shape = RoundedCornerShape(14.dp), + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 6.dp), + ) { + if (actionBusy) { + CircularProgressIndicator( + modifier = Modifier.size(17.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.onPrimary, + ) + } else { + Icon( + imageVector = if (lifecycle.actionIcon == "update") { + Icons.Default.Update + } else { + Icons.Default.Link + }, + contentDescription = null, + modifier = Modifier.size(17.dp), + ) + Spacer(Modifier.width(5.dp)) + FlexibleButtonText(label) + } + } +} + @Composable private fun SettingsHelpDialog( title: String, paragraphs: List, - onDismiss: () -> Unit + onDismiss: () -> Unit, + highlightedParagraphIndices: Set = emptySet(), + secondaryActionLabel: String? = null, + onSecondaryAction: (() -> Unit)? = null, + secondaryActionEnabled: Boolean = true, + onSecondaryActionDisabled: (() -> Unit)? = null, ) { Dialog(onDismissRequest = onDismiss) { BoxWithConstraints( @@ -1819,6 +2289,7 @@ private fun SettingsHelpDialog( ) { Text( title, + modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary @@ -1827,12 +2298,52 @@ private fun SettingsHelpDialog( Icon(Icons.Default.Close, contentDescription = "Закрыть") } } - paragraphs.forEach { paragraph -> - Text( - paragraph, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) + paragraphs.forEachIndexed { index, paragraph -> + if (index in highlightedParagraphIndices) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.72f), + contentColor = MaterialTheme.colorScheme.onTertiaryContainer, + border = BorderStroke( + 1.dp, + MaterialTheme.colorScheme.tertiary.copy(alpha = 0.32f), + ), + ) { + Text( + paragraph, + modifier = Modifier.padding(12.dp), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold, + ) + } + } else { + Text( + paragraph, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + if (secondaryActionLabel != null && onSecondaryAction != null) { + Box(modifier = Modifier.fillMaxWidth()) { + OutlinedButton( + onClick = onSecondaryAction, + enabled = secondaryActionEnabled, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), + ) { + FlexibleButtonText(secondaryActionLabel) + } + if (!secondaryActionEnabled && onSecondaryActionDisabled != null) { + Box( + modifier = Modifier + .matchParentSize() + .clickable(onClick = onSecondaryActionDisabled), + ) + } + } } Button( onClick = onDismiss, @@ -2026,7 +2537,7 @@ private fun CompactSteppedSlider( Canvas( modifier = modifier - .height(34.dp) + .height(30.dp) .pointerInput(enabled, valueRange, stepSize) { if (!enabled) return@pointerInput detectTapGestures { offset -> @@ -2357,8 +2868,8 @@ private fun CompactTunnelProfileCard( onManualClick: () -> Unit, ) { AppSectionCard( - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp) + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) ) { Text( "Способ подключения", @@ -2389,7 +2900,7 @@ private fun CompactTunnelProfileCard( onClick = onAddLinkClick, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), shape = RoundedCornerShape(16.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp) ) { Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) @@ -2403,7 +2914,7 @@ private fun CompactTunnelProfileCard( onClick = onManualClick, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), shape = RoundedCornerShape(16.dp), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp) + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp) ) { Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) @@ -2644,7 +3155,6 @@ private fun UserWdttLinkDialog( remoteUpdateOnly: Boolean, cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable, onCachedAction: () -> Unit = {}, - importedLinkStoredAsManualFields: Boolean, title: String, subtitle: String, onDismiss: () -> Unit, @@ -2773,13 +3283,6 @@ private fun UserWdttLinkDialog( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp) ) { - if (!remoteUpdateOnly && importedLinkStoredAsManualFields && linkText.isBlank()) { - Text( - "Ссылка принята. Данные сохранены в «Вручную»: там их можно изменить, либо здесь вставить новую ссылку.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.primary - ) - } OutlinedTextField( value = linkText, onValueChange = onLinkTextChange, @@ -2935,6 +3438,56 @@ private fun RemoteUpdateHelpDialog( } } +@Composable +private fun ManagedHashStatusCard(lifecycle: AccessLifecycleUiState) { + val accent = MaterialTheme.colorScheme.primary + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.52f), + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + border = BorderStroke(1.dp, accent.copy(alpha = 0.36f)), + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(14.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(9.dp), + ) { + Icon( + Icons.Default.CheckCircle, + contentDescription = null, + tint = accent, + modifier = Modifier.size(21.dp), + ) + Text( + lifecycle.title.ifBlank { "Автоматическое получение VK-хешей" }, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + ) + } + if (lifecycle.message.isNotBlank()) { + Text( + lifecycle.message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.86f), + ) + } + if (lifecycle.detailLabel.isNotBlank() || lifecycle.detailValue.isNotBlank()) { + AccessLifecycleDetail( + lifecycle = lifecycle, + accent = accent, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} + @Composable private fun RemoteActionCard( action: RemoteUiAction, @@ -3109,6 +3662,7 @@ private fun DismissedNoticeCard( @Composable fun HashesDialog( settingsStore: SettingsStore, + profileIndex: Int, hash1: String, hash2: String, hash3: String, @@ -3119,6 +3673,7 @@ fun HashesDialog( customVkClientId: String, customVkClientSecret: String, remoteContinuation: RemoteContinuation, + remoteAccessLifecycle: AccessLifecycleUiState, remoteAction: RemoteUiAction?, vkCallsPreflight: Boolean, captchaMode: String, @@ -3283,7 +3838,8 @@ fun HashesDialog( ?: "Открываю продолжение..." val target = RemoteContinuationLauncher.begin( capability = remoteContinuation, - device = settingsStore.getOrCreateConnectDeviceId() + device = settingsStore.getOrCreateConnectDeviceId(), + localDocument = settingsStore.remoteActionProfileDocument(profileIndex), ) try { launchRemoteTarget(context, target) @@ -3720,6 +4276,13 @@ fun HashesDialog( ) } } + } else if ( + shouldShowManagedHashStatusCard( + continuationAvailable = remoteContinuation.available, + lifecycle = remoteAccessLifecycle, + ) + ) { + ManagedHashStatusCard(remoteAccessLifecycle) } else if (remoteAction != null) { RemoteActionCard( action = remoteAction, diff --git a/app/src/test/java/com/wdtt/plus/DeviceCompatibilityTest.kt b/app/src/test/java/com/wdtt/plus/DeviceCompatibilityTest.kt new file mode 100644 index 0000000..cff02f9 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/DeviceCompatibilityTest.kt @@ -0,0 +1,53 @@ +package com.wdtt.plus + +import java.nio.file.Files +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class DeviceCompatibilityTest { + @Test + fun sixteenKibPagesAreSupportedByThe64BitRelease() { + val item = pageSizeCompatibilityItem(16L * 1024L, processIs64Bit = true) + + assertEquals(DeviceCheckSeverity.Ok, item.severity) + assertTrue(item.status.contains("поддерживается")) + } + + @Test + fun nonStandardPageSizeStillWarnsWhenItIsNotThe64BitPath() { + val item = pageSizeCompatibilityItem(16L * 1024L, processIs64Bit = false) + + assertEquals(DeviceCheckSeverity.Warning, item.severity) + } + + @Test + fun masqueEnrollmentInspectorRejectsIncompleteFiles() { + val directory = Files.createTempDirectory("wdtt-masque-check-").toFile() + val config = directory.resolve(RT_MASQUE_CONFIG_FILE_NAME) + try { + config.writeText("{\"version\":1,\"private_key\":\"secret\"}") + + assertEquals(RtMasqueEnrollmentState.Invalid, inspectRtMasqueEnrollment(config)) + } finally { + config.delete() + directory.delete() + } + } + + @Test + fun masqueEnrollmentInspectorAcceptsTheVersionOneShape() { + val directory = Files.createTempDirectory("wdtt-masque-check-").toFile() + val config = directory.resolve(RT_MASQUE_CONFIG_FILE_NAME) + try { + config.writeText( + """{"version":1,"private_key":"private","endpoint_v4":"192.0.2.1","endpoint_pub_key":"public","ipv4":"172.16.0.2"}""" + ) + + assertEquals(RtMasqueEnrollmentState.Ready, inspectRtMasqueEnrollment(config)) + } finally { + config.delete() + directory.delete() + } + } +} diff --git a/app/src/test/java/com/wdtt/plus/RtTurnSniTest.kt b/app/src/test/java/com/wdtt/plus/RtTurnSniTest.kt new file mode 100644 index 0000000..56cdcc5 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/RtTurnSniTest.kt @@ -0,0 +1,285 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class RtTurnSniTest { + @Test + fun allRtNetworkSettingsAreRegisteredAsProfilePreferences() { + val profilePreferenceNames = SettingsStore.resettableProfilePreferenceNames() + + assertTrue( + profilePreferenceNames.containsAll( + setOf( + "rt_network", + "rt_masque", + "rt_masque_server_bootstrap", + "rt_turn_sni", + ) + ) + ) + } + + @Test + fun masqueRequiresBothSwitches() { + assertFalse(shouldUseRtMasque(rtNetwork = false, rtMasque = false)) + assertFalse(shouldUseRtMasque(rtNetwork = false, rtMasque = true)) + assertFalse(shouldUseRtMasque(rtNetwork = true, rtMasque = false)) + assertTrue(shouldUseRtMasque(rtNetwork = true, rtMasque = true)) + assertFalse( + shouldUseRtMasqueServerBootstrap( + rtNetwork = false, + rtMasque = true, + serverBootstrap = true, + ) + ) + assertFalse( + shouldUseRtMasqueServerBootstrap( + rtNetwork = true, + rtMasque = false, + serverBootstrap = true, + ) + ) + assertTrue( + shouldUseRtMasqueServerBootstrap( + rtNetwork = true, + rtMasque = true, + serverBootstrap = true, + ) + ) + } + + @Test + fun masqueLogsExposeProtocolFallbackAndRegistrationRecovery() { + val h2 = classifyMasqueLog( + "[СЕССИЯ #1] [MASQUE] turns:443 через HTTP/2 не сработал: timeout" + ) + assertEquals("masque_h2_failed", h2?.key) + assertTrue(h2?.warning == true) + assertTrue(h2?.message?.contains("таймаут") == true) + + val selected = classifyMasqueLog( + "[СЕССИЯ #1] Relay: 1.2.3.4:5 через TURN TURNS внутри MASQUE HTTP/3 ✓" + ) + assertEquals("masque_selected", selected?.key) + assertTrue(selected?.startsDtls == true) + + val invalid = classifyMasqueLog( + "[MASQUE] фоновая подготовка WARP пока не выполнена: сохранённая конфигурация WARP повреждена" + ) + assertEquals("masque_registration_invalid", invalid?.key) + assertTrue(invalid?.message?.contains("Сбросить регистрацию WARP") == true) + + assertNull(classifyMasqueLog("[TURN] обычный режим")) + } + + @Test + fun enrollmentLogKeepsSafeCloudflareFailureReason() { + val rateLimit = classifyMasqueLog( + "[MASQUE] фоновая подготовка WARP пока не выполнена: регистрация WARP: WARP API HTTP 429: code=1042" + ) + assertEquals("masque_enrollment_pending", rateLimit?.key) + assertTrue(rateLimit?.message?.contains("HTTP 429") == true) + assertTrue(rateLimit?.message?.contains("этап 1/4") == true) + assertTrue(rateLimit?.message?.contains("код API 1042") == true) + + val serverFailure = classifyMasqueLog( + "[MASQUE] фоновая подготовка WARP пока не выполнена: этап 2/4, включение MASQUE: WARP API HTTP 500" + ) + assertTrue(serverFailure?.message?.contains("временная ошибка Cloudflare") == true) + assertTrue(serverFailure?.message?.contains("этап 2/4") == true) + + val unexpectedBody = classifyMasqueLog( + "[MASQUE] фоновая подготовка WARP пока не выполнена: этап 1/4, создание устройства WARP: " + + "WARP API вернул ответ не в формате JSON: HTTP 200, Content-Type=text/html, размер=1240 байт" + ) + assertTrue(unexpectedBody?.message?.contains("не в формате JSON") == true) + assertTrue(unexpectedBody?.message?.contains("Content-Type=text/html") == true) + + val unknownFailure = classifyMasqueLog( + "[MASQUE] фоновая подготовка WARP пока не выполнена: этап 1/4, создание ключа устройства WARP: " + + "ошибка генератора случайных чисел" + ) + assertTrue(unknownFailure?.message?.contains("ошибка генератора случайных чисел") == true) + + val tlsTimeout = classifyMasqueLog( + "[MASQUE] фоновая подготовка WARP пока не выполнена: этап 1/4, создание устройства WARP: " + + "WARP API: тайм-аут TLS-рукопожатия (8 с) после успешного TCP/443" + ) + assertTrue(tlsTimeout?.message?.contains("TLS-рукопожатие") == true) + assertTrue(tlsTimeout?.message?.contains("после успешного TCP/443") == true) + + val responseTimeout = classifyMasqueLog( + "[MASQUE] фоновая подготовка WARP пока не выполнена: этап 1/4, создание устройства WARP: " + + "WARP API: HTTP-запрос отправлен, но Cloudflare не прислал ответ за 12 с" + ) + assertTrue(responseTimeout?.message?.contains("уже отправленный HTTPS-запрос") == true) + + val accountCreated = classifyMasqueLog( + "[MASQUE] этап 1/4 завершён: устройство WARP создано в Cloudflare; этап 2/4 — включаем для него MASQUE" + ) + assertEquals("masque_account_created", accountCreated?.key) + assertTrue(accountCreated?.message?.contains("устройство WARP создано") == true) + + val saved = classifyMasqueLog( + "[MASQUE] этап 4/4 завершён: регистрация WARP сохранена в приватном хранилище приложения ✓" + ) + assertEquals("masque_enrollment_saved", saved?.key) + assertTrue(saved?.message?.contains("приватном хранилище") == true) + } + + @Test + fun cloudflareApiPhasesRemainSeparateInTheVisibleLog() { + assertEquals( + "masque_api_dns", + classifyMasqueLog("[MASQUE] API Cloudflare: системный DNS Android разрешил адрес ✓")?.key, + ) + assertEquals( + "masque_api_tcp", + classifyMasqueLog("[MASQUE] API Cloudflare: TCP/443 через системную сеть Android установлен ✓")?.key, + ) + assertEquals( + "masque_api_tls", + classifyMasqueLog("[MASQUE] API Cloudflare: TLS-рукопожатие завершено, согласован HTTP/2 ✓")?.key, + ) + assertEquals( + "masque_api_request", + classifyMasqueLog("[MASQUE] API Cloudflare: HTTP-запрос отправлен, ожидаем ответ...")?.key, + ) + assertEquals( + "masque_api_response", + classifyMasqueLog("[MASQUE] API Cloudflare: получен первый байт HTTP-ответа ✓")?.key, + ) + assertEquals( + "masque_api_retry", + classifyMasqueLog( + "[MASQUE] API Cloudflare: TLS timeout; данные устройства ещё не отправлялись — " + + "выполняем одну безопасную повторную попытку" + )?.key, + ) + assertEquals( + "masque_api_tls_fallback", + classifyMasqueLog( + "[MASQUE] API Cloudflare: обычный TLS не прошёл до отправки данных — " + + "повторяем через TLS 1.2/HTTP 1.1 с разделённым ClientHello" + )?.key, + ) + assertEquals( + "masque_api_server_retry", + classifyMasqueLog( + "[MASQUE] API Cloudflare: прямые HTTPS-пути недоступны до отправки данных — " + + "пробуем защищённый выход через сервер профиля" + )?.key, + ) + assertEquals( + "masque_api_server_connected", + classifyMasqueLog( + "[MASQUE] API Cloudflare: защищённый выход через сервер профиля доступен ✓" + )?.key, + ) + assertEquals( + "masque_api_tls_fallback_ok", + classifyMasqueLog( + "[MASQUE] API Cloudflare: TLS-рукопожатие завершено, согласован HTTP/1.1 ✓" + )?.key, + ) + } + + @Test + fun normalizesValidDomain() { + assertEquals("ya.ru", normalizeRtTurnSni(" Ya.RU ")) + assertEquals("telemost.yandex.ru", normalizeRtTurnSni("telemost.yandex.ru")) + } + + @Test + fun rejectsValuesThatCannotBeTlsSni() { + listOf("", "ya", "127.0.0.1", "я.рф", "-ya.ru", "ya..ru").forEach { value -> + assertNull(value, normalizeRtTurnSni(value)) + } + } + + @Test + fun rtTurnSniDoesNotReplaceExistingServerSni() { + val params = buildTunnelParams( + TunnelProfileSnapshot( + profileIndex = 0, + remoteManaged = false, + linkMode = false, + link = "", + peer = "vpn.example", + vkHashes = "hash", + secondaryVkHash = "", + connectionPassword = "password", + workersPerHash = 18, + profileMaxWorkers = 0, + manualPortsEnabled = false, + serverDtlsPort = 56000, + listenPort = 9000, + sni = "server.example", + protocol = "udp", + vkCallsPreflight = true, + rtNetwork = true, + rtMasque = true, + rtMasqueServerBootstrap = true, + rtMasqueServerAccessReady = true, + rtTurnSni = "ya.ru", + captchaMode = "auto", + captchaSolveMethod = "auto", + fingerprint = "firefox", + clientIds = DEFAULT_VK_CLIENT_IDS, + customVkCredentialsEnabled = false, + customVkClientId = "", + customVkClientSecret = "", + ) + ) + + assertNotNull(params) + assertEquals("server.example", params?.sni) + assertEquals("ya.ru", params?.rtTurnSni) + assertEquals(true, params?.rtMasque) + assertEquals(true, params?.rtMasqueServerBootstrap) + } + + @Test + fun serverBootstrapIsNotStartedWithoutDeploySshAccess() { + val params = buildTunnelParams( + TunnelProfileSnapshot( + profileIndex = 0, + remoteManaged = false, + linkMode = false, + link = "", + peer = "vpn.example", + vkHashes = "hash", + secondaryVkHash = "", + connectionPassword = "password", + workersPerHash = 18, + profileMaxWorkers = 0, + manualPortsEnabled = false, + serverDtlsPort = 56000, + listenPort = 9000, + sni = "", + protocol = "udp", + vkCallsPreflight = true, + rtNetwork = true, + rtMasque = true, + rtMasqueServerBootstrap = true, + rtMasqueServerAccessReady = false, + rtTurnSni = "ya.ru", + captchaMode = "auto", + captchaSolveMethod = "auto", + fingerprint = "firefox", + clientIds = DEFAULT_VK_CLIENT_IDS, + customVkCredentialsEnabled = false, + customVkClientId = "", + customVkClientSecret = "", + ) + ) + + assertNotNull(params) + assertEquals(false, params?.rtMasqueServerBootstrap) + } +} diff --git a/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt b/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt index 6def1f1..4a9a5e8 100644 --- a/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt +++ b/app/src/test/java/com/wdtt/plus/ServerMigrationTest.kt @@ -66,6 +66,22 @@ class ServerMigrationTest { assertEquals(7, result.acknowledgedLevel) } + @Test + fun updateFrom13To14RequiresServerMigration() { + val result = resolveServerMigrationInitialization( + currentVersionCode = 14, + isUpdatedInstall = true, + storedLastSeenAppVersionCode = 13, + storedPendingLevel = 12, + storedAcknowledgedLevel = 12, + legacyAcknowledgedLevel = 5 + ) + + assertEquals(14, result.pendingLevel) + assertEquals(12, result.acknowledgedLevel) + assertEquals(14, latestServerMigrationLevel(14)) + } + @Test fun stateSeparatesReadNoticeFromCompletedDeployment() { val state = ServerMigrationState( diff --git a/app/src/test/java/com/wdtt/plus/SshAuthenticationTest.kt b/app/src/test/java/com/wdtt/plus/SshAuthenticationTest.kt index ee55ca4..bde1855 100644 --- a/app/src/test/java/com/wdtt/plus/SshAuthenticationTest.kt +++ b/app/src/test/java/com/wdtt/plus/SshAuthenticationTest.kt @@ -50,6 +50,46 @@ class SshAuthenticationTest { assertFalse(keyMode.allowPasswordAuthentication) } + @Test + fun serverBootstrapAcceptsPasswordOrValidPrivateKeyFromDeploy() { + assertTrue( + sshProfileAccessStatus( + host = "server.example", + authMode = "password", + password = "secret", + privateKey = "", + ).available + ) + assertTrue( + sshProfileAccessStatus( + host = "server.example", + authMode = "key", + password = "", + privateKey = openSshKey, + ).available + ) + } + + @Test + fun serverBootstrapExplainsMissingOrInvalidDeployAccess() { + val missingHost = sshProfileAccessStatus("", "password", "secret", "") + assertFalse(missingHost.available) + assertTrue(missingHost.unavailableReason.contains("адрес сервера")) + + val missingPassword = sshProfileAccessStatus("server.example", "password", "", "") + assertFalse(missingPassword.available) + assertTrue(missingPassword.unavailableReason.contains("SSH-пароль")) + + val invalidKey = sshProfileAccessStatus( + host = "server.example", + authMode = "key", + password = "", + privateKey = "ssh-ed25519 AAAA public-only", + ) + assertFalse(invalidKey.available) + assertTrue(invalidKey.unavailableReason.contains("приватный SSH-ключ")) + } + @Test fun ed25519UsesBundledAndroidCompatibleImplementation() { configureJschEdDsaCompatibility() diff --git a/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt b/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt index e204f07..2fb3652 100644 --- a/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt +++ b/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt @@ -109,6 +109,7 @@ class TrustedWifiTest { assertTrue( shouldKeepTunnelServiceAlive( tunnelRunning = false, + tunnelStarting = false, tunnelPaused = false, trustedWifiWaiting = false, trustedWifiResumeInProgress = true @@ -117,6 +118,20 @@ class TrustedWifiTest { assertFalse( shouldKeepTunnelServiceAlive( tunnelRunning = false, + tunnelStarting = false, + tunnelPaused = false, + trustedWifiWaiting = false, + trustedWifiResumeInProgress = false + ) + ) + } + + @Test + fun `service stays alive while tunnel process is starting`() { + assertTrue( + shouldKeepTunnelServiceAlive( + tunnelRunning = false, + tunnelStarting = true, tunnelPaused = false, trustedWifiWaiting = false, trustedWifiResumeInProgress = false diff --git a/app/src/test/java/com/wdtt/plus/TunnelProfilePresentationTest.kt b/app/src/test/java/com/wdtt/plus/TunnelProfilePresentationTest.kt index fdf2e63..7c141cc 100644 --- a/app/src/test/java/com/wdtt/plus/TunnelProfilePresentationTest.kt +++ b/app/src/test/java/com/wdtt/plus/TunnelProfilePresentationTest.kt @@ -21,7 +21,7 @@ class TunnelProfilePresentationTest { assertEquals("link", resolveConnectionInputMethod("", false, false, true)) assertEquals("manual", resolveConnectionInputMethod("", false, false, false)) assertEquals("manual", resolveConnectionInputMethod("", false, true, true)) - assertEquals("link", resolveConnectionInputMethod("link", false, true, false)) + assertEquals("manual", resolveConnectionInputMethod("link", false, true, false)) } @Test @@ -81,7 +81,7 @@ class TunnelProfilePresentationTest { manualValid = true, ) ) - assertTrue( + assertFalse( isSelectedCompactConnectionReady( selectedMethod = "link", savedMethod = "link", @@ -91,7 +91,7 @@ class TunnelProfilePresentationTest { manualValid = true, ) ) - assertFalse( + assertTrue( isSelectedCompactConnectionReady( selectedMethod = "manual", savedMethod = "link", diff --git a/app/src/test/java/com/wdtt/plus/TunnelRecoveryPolicyTest.kt b/app/src/test/java/com/wdtt/plus/TunnelRecoveryPolicyTest.kt index f68d822..5ddf92e 100644 --- a/app/src/test/java/com/wdtt/plus/TunnelRecoveryPolicyTest.kt +++ b/app/src/test/java/com/wdtt/plus/TunnelRecoveryPolicyTest.kt @@ -13,22 +13,225 @@ class TunnelRecoveryPolicyTest { } @Test - fun failedTransportRecoveryRecreatesVpnOnce() { + fun repeatedStableRecoveryRemainsTransportOnly() { assertEquals( - NetworkRecoveryAction.RecreateVpn, + NetworkRecoveryAction.SoftRestart, stableNetworkRecoveryAction(completedAttempts = 1), ) + assertEquals( + NetworkRecoveryAction.SoftRestart, + stableNetworkRecoveryAction(completedAttempts = 2), + ) + assertEquals( + NetworkRecoveryAction.SoftRestart, + stableNetworkRecoveryAction(completedAttempts = 3), + ) } @Test - fun failedVpnRecreationStopsFailOpen() { + fun vpnInterfaceRecoveryRequiresAwakeDeviceAndValidatedNetwork() { assertEquals( - NetworkRecoveryAction.StopVpn, - stableNetworkRecoveryAction(completedAttempts = 2), + false, + shouldAttemptVpnInterfaceRecovery( + deviceInteractive = false, + startupWindow = false, + captchaActive = false, + missingForMs = 120_000L, + validatedNetworkAvailable = true, + sinceLastAttemptMs = Long.MAX_VALUE, + ), ) assertEquals( - NetworkRecoveryAction.StopVpn, - stableNetworkRecoveryAction(completedAttempts = 3), + false, + shouldAttemptVpnInterfaceRecovery( + deviceInteractive = true, + startupWindow = false, + captchaActive = false, + missingForMs = 120_000L, + validatedNetworkAvailable = false, + sinceLastAttemptMs = Long.MAX_VALUE, + ), + ) + assertEquals( + true, + shouldAttemptVpnInterfaceRecovery( + deviceInteractive = true, + startupWindow = false, + captchaActive = false, + missingForMs = 120_000L, + validatedNetworkAvailable = true, + sinceLastAttemptMs = Long.MAX_VALUE, + ), + ) + assertEquals( + false, + shouldAttemptVpnInterfaceRecovery( + deviceInteractive = true, + startupWindow = false, + captchaActive = false, + missingForMs = 30_000L, + validatedNetworkAvailable = true, + sinceLastAttemptMs = Long.MAX_VALUE, + ), + ) + assertEquals( + false, + shouldAttemptVpnInterfaceRecovery( + deviceInteractive = true, + startupWindow = false, + captchaActive = false, + missingForMs = 120_000L, + validatedNetworkAvailable = true, + sinceLastAttemptMs = 60_000L, + ), ) } + + @Test + fun sleepBatteryModePausesOnlyAnActiveTunnel() { + assertEquals( + true, + shouldPauseVpnForSleep( + pauseEnabled = true, + deviceInteractive = false, + tunnelRunning = true, + tunnelPaused = false, + trustedWifiWaiting = false, + ), + ) + assertEquals( + false, + shouldPauseVpnForSleep( + pauseEnabled = false, + deviceInteractive = false, + tunnelRunning = true, + tunnelPaused = false, + trustedWifiWaiting = false, + ), + ) + assertEquals( + false, + shouldPauseVpnForSleep( + pauseEnabled = true, + deviceInteractive = true, + tunnelRunning = true, + tunnelPaused = false, + trustedWifiWaiting = false, + ), + ) + assertEquals( + false, + shouldPauseVpnForSleep( + pauseEnabled = true, + deviceInteractive = false, + tunnelRunning = true, + tunnelPaused = true, + trustedWifiWaiting = false, + ), + ) + } + + @Test + fun sleepBatteryModeResumesOnlyItsOwnPause() { + assertEquals( + true, + shouldResumeVpnAfterSleep( + sleepPausedByPolicy = true, + tunnelRunning = true, + tunnelPaused = true, + trustedWifiWaiting = false, + ), + ) + assertEquals( + false, + shouldResumeVpnAfterSleep( + sleepPausedByPolicy = false, + tunnelRunning = true, + tunnelPaused = true, + trustedWifiWaiting = false, + ), + ) + assertEquals( + false, + shouldResumeVpnAfterSleep( + sleepPausedByPolicy = true, + tunnelRunning = true, + tunnelPaused = true, + trustedWifiWaiting = true, + ), + ) + } + + @Test + fun freshActiveHeartbeatDoesNotRequireTrafficGrowth() { + assertEquals( + true, + hasFreshTransportHeartbeat( + running = true, + activeWorkers = 9, + lastActiveAtMs = 120_000L, + lastStatsAtMs = 120_000L, + sinceMs = 100_000L, + nowMs = 130_000L, + ), + ) + } + + @Test + fun oldOrEmptyHeartbeatStillRequiresRecovery() { + assertEquals( + false, + hasFreshTransportHeartbeat( + running = true, + activeWorkers = 9, + lastActiveAtMs = 90_000L, + lastStatsAtMs = 90_000L, + sinceMs = 100_000L, + nowMs = 130_000L, + ), + ) + assertEquals( + false, + hasFreshTransportHeartbeat( + running = true, + activeWorkers = 0, + lastActiveAtMs = 120_000L, + lastStatsAtMs = 120_000L, + sinceMs = 100_000L, + nowMs = 130_000L, + ), + ) + } + + @Test + fun tunnelHealthIsNotJudgedDuringSleepOrWakeStabilization() { + assertEquals( + false, + shouldObserveTunnelHealth( + deviceInteractive = false, + wakeRecoveryGraceActive = false, + ), + ) + assertEquals( + false, + shouldObserveTunnelHealth( + deviceInteractive = true, + wakeRecoveryGraceActive = true, + ), + ) + assertEquals( + true, + shouldObserveTunnelHealth( + deviceInteractive = true, + wakeRecoveryGraceActive = false, + ), + ) + } + + @Test + fun phantomVpnCleanupDoesNotRaceExpectedRestore() { + assertEquals(false, shouldClearPhantomVpn(activeTunnelProfile = 0)) + assertEquals(false, shouldClearPhantomVpn(activeTunnelProfile = 2)) + assertEquals(true, shouldClearPhantomVpn(activeTunnelProfile = null)) + } } diff --git a/app/src/test/java/com/wdtt/plus/TunnelSessionTrafficTest.kt b/app/src/test/java/com/wdtt/plus/TunnelSessionTrafficTest.kt new file mode 100644 index 0000000..e43306d --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TunnelSessionTrafficTest.kt @@ -0,0 +1,49 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Test + +class TunnelSessionTrafficTest { + @Test + fun trafficSurvivesAnIntentionalTransportRestart() { + val accumulator = TunnelSessionTrafficAccumulator() + + assertEquals( + "Активных: 9 | ↓12.50 МБ / ↑3.25 МБ", + accumulator.accumulate("Активных: 9 | ↓12.50 МБ / ↑3.25 МБ"), + ) + + accumulator.noteTransportRestart() + + assertEquals( + "Активных: 9 | ↓13.00 МБ / ↑3.35 МБ", + accumulator.accumulate("Активных: 9 | ↓0.50 МБ / ↑0.10 МБ"), + ) + } + + @Test + fun unexpectedCounterResetIsAccumulatedWithoutLosingSessionTotals() { + val accumulator = TunnelSessionTrafficAccumulator() + accumulator.accumulate("Активных: 9 | ↓4,00 МБ / ↑2,00 МБ") + + assertEquals( + "Активных: 9 | ↓4.25 МБ / ↑2.50 МБ", + accumulator.accumulate("Активных: 9 | ↓0,25 МБ / ↑0,50 МБ"), + ) + } + + @Test + fun newSessionStartsFromFreshCounters() { + val accumulator = TunnelSessionTrafficAccumulator() + accumulator.accumulate("Активных: 9 | ↓8.00 МБ / ↑1.00 МБ") + accumulator.noteTransportRestart() + accumulator.accumulate("Активных: 9 | ↓1.00 МБ / ↑0.50 МБ") + + accumulator.reset() + + assertEquals( + "Активных: 9 | ↓0.25 МБ / ↑0.10 МБ", + accumulator.accumulate("Активных: 9 | ↓0.25 МБ / ↑0.10 МБ"), + ) + } +} diff --git a/go.mod b/go.mod index 3b5ccac..d1a9e7b 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/pion/dtls/v3 v3.1.2 github.com/pion/transport/v4 v4.0.1 golang.org/x/crypto v0.51.0 - golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb + golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 ) require ( diff --git a/go.sum b/go.sum index 525a57b..ebdb553 100644 --- a/go.sum +++ b/go.sum @@ -22,8 +22,8 @@ golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4= golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg= golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= -golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb h1:whnFRlWMcXI9d+ZbWg+4sHnLp52d5yiIPUxMBSt4X9A= -golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw= +golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w= +golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI= diff --git a/go_client/THIRD_PARTY_NOTICES.md b/go_client/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..80c9566 --- /dev/null +++ b/go_client/THIRD_PARTY_NOTICES.md @@ -0,0 +1,27 @@ +# Third-party notices + +The Cloudflare WARP MASQUE interoperability in `masque_warp.go` is adapted +from [Diniboy1123/usque](https://github.com/Diniboy1123/usque), commit +`6aa03fc97d12848dce34eedbd187fb1077b5d1ea`. + +The MIT License (MIT) + +Copyright © 2025, github.com/Diniboy1123 + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the “Software”), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/go_client/creds.go b/go_client/creds.go index d085679..2de13d8 100644 --- a/go_client/creds.go +++ b/go_client/creds.go @@ -234,9 +234,16 @@ func isAuthError(err error) bool { strings.Contains(errStr, "stale nonce") } -func handleAuthError(streamID int) bool { +func handleAuthError(streamID int, username, password string) bool { cache := getStreamCache(streamID) cacheID := getCacheID(streamID) + cache.mutex.Lock() + defer cache.mutex.Unlock() + if cache.creds.Username == "" || cache.creds.Password == "" || + cache.creds.Username != username || cache.creds.Password != password { + log.Printf("[STREAM %d] [TURN] Креды уже заменены; поздняя ошибка авторизации проигнорирована (cache=%d)", streamID, cacheID) + return false + } now := time.Now().Unix() @@ -251,7 +258,10 @@ func handleAuthError(streamID int) bool { if count >= maxCacheErrors { log.Printf("[VK Auth] Multiple auth errors detected (%d), invalidating cache %d", count, cacheID) - cache.invalidate(streamID) + cache.creds = TurnCredentials{} + cache.errorCount.Store(0) + cache.lastErrorTime.Store(0) + log.Printf("[STREAM %d] [VK Auth] Credentials cache invalidated", streamID) return true } return false diff --git a/go_client/creds_test.go b/go_client/creds_test.go index ea277ea..cff10da 100644 --- a/go_client/creds_test.go +++ b/go_client/creds_test.go @@ -79,3 +79,47 @@ func TestClassifyHashCheckErrorKeepsTerminalAndTransientStatusesSeparate(t *test }) } } + +func TestAuthErrorsFromSupersededCredentialsDoNotInvalidateFreshCache(t *testing.T) { + const streamID = 9876540 + cacheID := getCacheID(streamID) + credentialsStore.mu.Lock() + delete(credentialsStore.caches, cacheID) + credentialsStore.mu.Unlock() + t.Cleanup(func() { + credentialsStore.mu.Lock() + delete(credentialsStore.caches, cacheID) + credentialsStore.mu.Unlock() + }) + + cache := getStreamCache(streamID) + cache.mutex.Lock() + cache.creds = TurnCredentials{ + Username: "fresh-user", + Password: "fresh-pass", + ServerAddrs: []string{"turn:fresh.example:3478"}, + Link: "fresh-link", + } + cache.mutex.Unlock() + + for attempt := 0; attempt < maxCacheErrors+2; attempt++ { + if handleAuthError(streamID, "stale-user", "stale-pass") { + t.Fatal("superseded credentials invalidated the fresh cache") + } + } + if got := cache.errorCount.Load(); got != 0 { + t.Fatalf("superseded errors were counted: %d", got) + } + + for attempt := 1; attempt <= maxCacheErrors; attempt++ { + invalidated := handleAuthError(streamID, "fresh-user", "fresh-pass") + if invalidated != (attempt == maxCacheErrors) { + t.Fatalf("attempt %d invalidated=%v", attempt, invalidated) + } + } + cache.mutex.RLock() + defer cache.mutex.RUnlock() + if cache.creds.Username != "" || cache.creds.Password != "" { + t.Fatal("current credential failures did not invalidate the cache") + } +} diff --git a/go_client/dns_resolver.go b/go_client/dns_resolver.go index 57d08fd..6af9a0d 100644 --- a/go_client/dns_resolver.go +++ b/go_client/dns_resolver.go @@ -11,6 +11,12 @@ import ( const dnsProbeHost = "login.vk.ru" +// Keep Android's resolver before setupGlobalResolver optionally replaces the +// process-wide resolver with a direct DNS route optimized for VK. Some public +// resolvers return different Cloudflare WARP API edges, so MASQUE enrollment +// must be able to consult the device resolver independently. +var deviceSystemResolver = net.DefaultResolver + type dnsRoute struct { Label string Network string @@ -27,7 +33,7 @@ type directDNSProbe func(context.Context, dnsRoute, time.Duration) error type systemDNSProbe func(context.Context, *net.Resolver, time.Duration) error func setupGlobalResolver() { - systemResolver := net.DefaultResolver + systemResolver := deviceSystemResolver route, probes := chooseDNSRoute(context.Background(), systemResolver) if route.System { logDNSSystemRoute(probes) diff --git a/go_client/go.mod b/go_client/go.mod index c2a293f..b7d31d2 100644 --- a/go_client/go.mod +++ b/go_client/go.mod @@ -10,24 +10,33 @@ require ( github.com/pion/dtls/v3 v3.1.2 github.com/pion/logging v0.2.4 github.com/pion/turn/v5 v5.0.2 - golang.org/x/crypto v0.46.0 + golang.org/x/crypto v0.51.0 ) require ( + github.com/Diniboy1123/connect-ip-go v0.0.0-20260613064811-66cba32d7d33 // indirect github.com/andybalholm/brotli v1.2.0 // indirect github.com/bdandy/go-errors v1.2.2 // indirect github.com/bdandy/go-socks4 v1.2.3 // indirect github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect github.com/bogdanfinn/utls v1.7.7-barnius // indirect github.com/bogdanfinn/websocket v1.5.5-barnius // indirect + github.com/dunglas/httpsfv v1.0.2 // indirect + github.com/google/btree v1.1.2 // indirect github.com/klauspost/compress v1.18.2 // indirect github.com/pion/randutil v0.1.0 // indirect github.com/pion/stun/v3 v3.1.1 // indirect github.com/pion/transport/v4 v4.0.1 // indirect github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.60.0 // indirect github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect github.com/wlynxg/anet v0.0.5 // indirect - golang.org/x/net v0.48.0 // indirect - golang.org/x/sys v0.39.0 // indirect - golang.org/x/text v0.36.0 // indirect + github.com/yosida95/uritemplate/v3 v3.0.2 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/sys v0.45.0 // indirect + golang.org/x/text v0.37.0 // indirect + golang.org/x/time v0.10.0 // indirect + golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect + golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 // indirect + gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c // indirect ) diff --git a/go_client/go.sum b/go_client/go.sum index 8002bf7..ac11518 100644 --- a/go_client/go.sum +++ b/go_client/go.sum @@ -1,3 +1,5 @@ +github.com/Diniboy1123/connect-ip-go v0.0.0-20260613064811-66cba32d7d33 h1:HHEVWeNlF1ytUyi4xH+K0yVrkAwCOBAz2WvriKbs7HQ= +github.com/Diniboy1123/connect-ip-go v0.0.0-20260613064811-66cba32d7d33/go.mod h1:wi7UWeMy3b9dwZZeMcJjgZfjmmJn4z+ulsfdljz+Y/E= github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q= @@ -18,6 +20,10 @@ github.com/cbeuw/connutil v1.0.1 h1:LWuNYjwm7JEDYG/ISAO1TfU4G+q2dA5NhR97eq2roCA= github.com/cbeuw/connutil v1.0.1/go.mod h1:lKofNtrW7Atmosgp1eNnTt2j2NjA2IkifapgLVI1QtA= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dunglas/httpsfv v1.0.2 h1:iERDp/YAfnojSDJ7PW3dj1AReJz4MrwbECSSE59JWL0= +github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg= +github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= +github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= @@ -38,6 +44,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0= +github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc= @@ -46,23 +54,39 @@ github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= +github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= +golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI= +golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4= golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg= +golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= +golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w= +golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI= +gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c/go.mod h1:3r5CMtNQMKIvBlrmM9xWUNamjKBYPOWyXOjmg5Kts3g= diff --git a/go_client/group.go b/go_client/group.go index 12f083d..2d5225b 100644 --- a/go_client/group.go +++ b/go_client/group.go @@ -12,14 +12,62 @@ import ( ) const ( - workersPerGroup = 9 - defaultCycleSecs = 36000 - defaultWorkerRetryMin = 5 * time.Second - defaultWorkerRetryMax = 15 * time.Second - wrapHandshakeRetryMin = 1 * time.Second - wrapHandshakeRetryMax = 3 * time.Second + workersPerGroup = 9 + defaultCycleSecs = 36000 + defaultWorkerRetryMin = 5 * time.Second + defaultWorkerRetryMax = 15 * time.Second + wrapHandshakeRetryMin = 1 * time.Second + wrapHandshakeRetryMax = 3 * time.Second + refreshedCredsRetryMin = 500 * time.Millisecond + refreshedCredsRetrySlot = 250 * time.Millisecond + refreshedCredsRetryJitterMax = 250 * time.Millisecond ) +type credentialRefreshResult uint8 + +const ( + credentialRefreshNone credentialRefreshResult = iota + credentialRefreshApplied + credentialRefreshSuperseded +) + +type groupCredentialsState struct { + mu sync.RWMutex + value Credentials + revision uint64 +} + +func newGroupCredentialsState(value Credentials) *groupCredentialsState { + value.TurnURLs = cloneStringSlice(value.TurnURLs) + return &groupCredentialsState{value: value, revision: 1} +} + +func (state *groupCredentialsState) snapshot() (Credentials, uint64) { + state.mu.RLock() + defer state.mu.RUnlock() + value := state.value + value.TurnURLs = cloneStringSlice(value.TurnURLs) + return value, state.revision +} + +func (state *groupCredentialsState) isCurrent(revision uint64) bool { + state.mu.RLock() + defer state.mu.RUnlock() + return state.revision == revision +} + +func (state *groupCredentialsState) replaceIfCurrent(revision uint64, value Credentials) bool { + state.mu.Lock() + defer state.mu.Unlock() + if state.revision != revision { + return false + } + value.TurnURLs = cloneStringSlice(value.TurnURLs) + state.value = value + state.revision++ + return true +} + func workerRetryDelayBounds(err error) (time.Duration, time.Duration) { if err != nil && strings.Contains(strings.ToUpper(err.Error()), "WRAP_AUTH_TIMEOUT") { return wrapHandshakeRetryMin, wrapHandshakeRetryMax @@ -33,6 +81,18 @@ func workerRetryDelay(err error) time.Duration { return minDelay + time.Duration(rand.Intn(steps))*time.Second } +func workerRetryDelayAfterCredentialRefresh(err error, result credentialRefreshResult, workerIndex int) time.Duration { + if result != credentialRefreshApplied && result != credentialRefreshSuperseded { + return workerRetryDelay(err) + } + if workerIndex < 0 { + workerIndex = 0 + } + slot := workerIndex % workersPerGroup + jitter := time.Duration(rand.Int63n(int64(refreshedCredsRetryJitterMax) + 1)) + return refreshedCredsRetryMin + time.Duration(slot)*refreshedCredsRetrySlot + jitter +} + type workerPolicyRetryGate struct { mu sync.Mutex blockedUntil time.Time @@ -140,6 +200,7 @@ func WorkerGroup( pauseFlag *int32, deviceID, password, deviceInfo, transportSession string, stats *Stats, + turnStreamFirst bool, waitReady <-chan struct{}, signalReady chan<- struct{}, ) { @@ -240,26 +301,35 @@ func WorkerGroup( user, pass, turnURLs, err = GetCreds(ctx, hash, credStreamID) } } - creds := &Credentials{User: user, Pass: pass, TurnURLs: turnURLs, CacheStreamID: credStreamID} + credsState := newGroupCredentialsState(Credentials{ + User: user, + Pass: pass, + TurnURLs: turnURLs, + CacheStreamID: credStreamID, + }) - log.Printf("[ГРУППА #%d] Креды OK, TURN: %v, %d воркеров", groupID, creds.TurnURLs, len(workerIDs)) + initialCreds, _ := credsState.snapshot() + log.Printf("[ГРУППА #%d] Креды OK, TURN: %v, %d воркеров", groupID, initialCreds.TurnURLs, len(workerIDs)) var configRequestInFlight int32 var wg sync.WaitGroup - var credsMu sync.RWMutex var refreshMu sync.Mutex var lastCredRefresh atomic.Int64 var policyRetryGate workerPolicyRetryGate - refreshCreds := func(reason string) bool { + refreshCreds := func(reason string, failedRevision uint64) credentialRefreshResult { refreshMu.Lock() defer refreshMu.Unlock() + if !credsState.isCurrent(failedRevision) { + log.Printf("[TURN] Креды уже заменены после этой попытки, используем актуальные (%s)", reason) + return credentialRefreshSuperseded + } now := time.Now().Unix() last := lastCredRefresh.Load() if last > 0 && now-last < 15 { log.Printf("[TURN] Креды уже обновлялись %d сек назад, ждём следующий retry (%s)", now-last, reason) - return true + return credentialRefreshNone } rotateForTurnFailure := hashFallback && @@ -295,17 +365,24 @@ func WorkerGroup( } if refreshErr != nil { log.Printf("[TURN] Не удалось обновить креды после %s: %v", reason, refreshErr) - return false + return credentialRefreshNone } selectedHash = nextHashIndex hash = hashCandidates[selectedHash] - credsMu.Lock() - creds = &Credentials{User: u, Pass: p, TurnURLs: urls, CacheStreamID: credStreamID} - credsMu.Unlock() + replaced := credsState.replaceIfCurrent(failedRevision, Credentials{ + User: u, + Pass: p, + TurnURLs: urls, + CacheStreamID: credStreamID, + }) + if !replaced { + log.Printf("[TURN] Креды уже заменены во время обновления, используем актуальные (%s)", reason) + return credentialRefreshSuperseded + } lastCredRefresh.Store(time.Now().Unix()) log.Printf("[TURN] Креды обновлены после %s, TURN urls=%d", reason, len(urls)) - return true + return credentialRefreshApplied } // Сигнализируем следующей группе, что мы успешно запустились (креды получены + 2 сек форы) @@ -358,15 +435,13 @@ func WorkerGroup( } } - credsMu.RLock() - credsSnapshot := *creds - credsSnapshot.TurnURLs = cloneStringSlice(creds.TurnURLs) - credsMu.RUnlock() + credsSnapshot, credsRevision := credsState.snapshot() configDelivered, sessErr := RunSession(ctx, tp, peer, d, localPort, getConf, cc, requireConfig, onConfigDelivered, wid, &credsSnapshot, deviceID, password, deviceInfo, - transportSession, stats) + transportSession, stats, turnStreamFirst) + refreshResult := credentialRefreshNone if getConf { if configDelivered { @@ -406,14 +481,8 @@ func WorkerGroup( turnAllocAttrMissing := strings.Contains(errStrLower, "turn allocate") && strings.Contains(errStrLower, "attribute not found") - turnCredRefreshNeeded := turnAllocAttrMissing || - strings.Contains(errStrLower, "turn allocate auth") || - strings.Contains(errStrLower, "invalid credential") || - strings.Contains(errStrLower, "stale nonce") || - strings.Contains(errStrLower, "allocation mismatch") || - strings.Contains(errStrLower, "error 508") || - strings.Contains(errStrLower, "turn квота") || - strings.Contains(errStrLower, "quota") + turnCredRefreshNeeded := turnAllocAttrMissing || isCredentialTURNError(sessErr) + turnCapacityLimited := isTURNCapacityError(sessErr) if strings.Contains(errStrLower, "rate limit") || strings.Contains(errStrLower, "flood control") || @@ -431,10 +500,12 @@ func WorkerGroup( attempt++ if turnAllocAttrMissing { log.Printf("[ВОРКЕР #%d] [TURN] Allocate вернул неполный ответ, обновляем TURN-креды и повторяем (попытка %d): %s", wid, attempt, errStr) - refreshCreds("TURN Allocate attribute-not-found") + refreshResult = refreshCreds("TURN Allocate attribute-not-found", credsRevision) } else if turnCredRefreshNeeded { log.Printf("[ВОРКЕР #%d] [TURN] Ошибка allocation/кредов, обновляем TURN-креды и повторяем (попытка %d): %s", wid, attempt, errStr) - refreshCreds("TURN allocation error") + refreshResult = refreshCreds("TURN allocation error", credsRevision) + } else if turnCapacityLimited { + log.Printf("[ВОРКЕР #%d] [TURN] Узел временно ограничил новые allocation; сохраняем креды и повторяем другие TURN-пути (попытка %d): %s", wid, attempt, errStr) } else { log.Printf("[ВОРКЕР #%d] Ошибка (попытка %d): %s", wid, attempt, errStr) } @@ -453,7 +524,7 @@ func WorkerGroup( return } - retryDelay := workerRetryDelay(sessErr) + retryDelay := workerRetryDelayAfterCredentialRefresh(sessErr, refreshResult, workerIndex) select { case <-time.After(retryDelay): case <-ctx.Done(): @@ -554,10 +625,12 @@ func normalizeVKJoinHash(input string) string { // TurnParams — конфигурация TURN type TurnParams struct { - Host string - Port string - Hashes []string - WrapKey []byte // Password-derived WRAP key (32 bytes), nil = disabled + Host string + Port string + Hashes []string + TLSFrontSNI string + Masque *warpMasqueManager + WrapKey []byte // Password-derived WRAP key (32 bytes), nil = disabled } // Credentials — учетные данные TURN diff --git a/go_client/group_test.go b/go_client/group_test.go index d83c1a2..db65a2b 100644 --- a/go_client/group_test.go +++ b/go_client/group_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "reflect" + "sync" "testing" "time" ) @@ -61,6 +62,127 @@ func TestWorkerPolicyRetryDelayIsBounded(t *testing.T) { } } +func TestGroupCredentialsStateRejectsStaleReplacement(t *testing.T) { + state := newGroupCredentialsState(Credentials{ + User: "first-user", + Pass: "first-pass", + TurnURLs: []string{"turn:first.example:3478"}, + }) + + first, revision := state.snapshot() + first.TurnURLs[0] = "mutated-outside-state" + unchanged, unchangedRevision := state.snapshot() + if unchanged.TurnURLs[0] != "turn:first.example:3478" { + t.Fatal("snapshot must not expose the stored TURN URL slice") + } + if unchangedRevision != revision { + t.Fatalf("initial revision changed: got %d, want %d", unchangedRevision, revision) + } + + if !state.replaceIfCurrent(revision, Credentials{ + User: "fresh-user", + Pass: "fresh-pass", + TurnURLs: []string{"turn:fresh.example:3478"}, + }) { + t.Fatal("current credential revision was not replaced") + } + if state.replaceIfCurrent(revision, first) { + t.Fatal("a stale worker replaced newer credentials") + } + fresh, freshRevision := state.snapshot() + if fresh.User != "fresh-user" || freshRevision != revision+1 { + t.Fatalf("fresh credentials = %#v at revision %d", fresh, freshRevision) + } +} + +func TestCredentialRefreshRetryUsesShortBoundedJitter(t *testing.T) { + for _, result := range []credentialRefreshResult{ + credentialRefreshApplied, + credentialRefreshSuperseded, + } { + for workerIndex := 0; workerIndex < workersPerGroup; workerIndex++ { + minimum := refreshedCredsRetryMin + time.Duration(workerIndex)*refreshedCredsRetrySlot + maximum := minimum + refreshedCredsRetryJitterMax + for attempt := 0; attempt < 100; attempt++ { + delay := workerRetryDelayAfterCredentialRefresh(errors.New("TURN auth"), result, workerIndex) + if delay < minimum || delay > maximum { + t.Fatalf("worker %d short retry delay %v outside %v..%v", workerIndex, delay, minimum, maximum) + } + } + } + } + + delay := workerRetryDelayAfterCredentialRefresh(errors.New("TURN timeout"), credentialRefreshNone, 8) + if delay < defaultWorkerRetryMin || delay > defaultWorkerRetryMax { + t.Fatalf("ordinary retry delay %v outside %v..%v", delay, defaultWorkerRetryMin, defaultWorkerRetryMax) + } +} + +func TestCredentialRevisionsStayIndependentAtMaximumPower(t *testing.T) { + const groupCount = 108 / workersPerGroup + states := make([]*groupCredentialsState, groupCount) + for group := range states { + states[group] = newGroupCredentialsState(Credentials{ + User: "initial", + TurnURLs: []string{"turn:initial.example:3478"}, + }) + } + + var wg sync.WaitGroup + wins := make([]int, groupCount) + var winsMu sync.Mutex + for group, state := range states { + _, revision := state.snapshot() + for worker := 0; worker < workersPerGroup; worker++ { + wg.Add(1) + go func(group, worker int, state *groupCredentialsState, revision uint64) { + defer wg.Done() + if state.replaceIfCurrent(revision, Credentials{ + User: "fresh", + TurnURLs: []string{"turn:fresh.example:3478"}, + }) { + winsMu.Lock() + wins[group]++ + winsMu.Unlock() + } + }(group, worker, state, revision) + } + } + wg.Wait() + + for group, state := range states { + if wins[group] != 1 { + t.Fatalf("group %d accepted %d replacements, want exactly one", group, wins[group]) + } + credentials, revision := state.snapshot() + if credentials.User != "fresh" || revision != 2 { + t.Fatalf("group %d credentials = %#v at revision %d", group, credentials, revision) + } + } +} + +func TestTURNCapacityDoesNotInvalidateCredentials(t *testing.T) { + for _, message := range []string{"TURN квота: error 486", "TURN Allocate: error 508", "allocation quota reached"} { + err := errors.New(message) + if !isTURNCapacityError(err) { + t.Fatalf("%q must be classified as endpoint capacity", message) + } + if isCredentialTURNError(err) { + t.Fatalf("%q must not invalidate VK credentials", message) + } + } + + for _, message := range []string{"TURN Allocate: error 401 Unauthorized", "invalid credential", "stale nonce", "allocation mismatch"} { + err := errors.New(message) + if !isCredentialTURNError(err) { + t.Fatalf("%q must refresh credentials", message) + } + if isTURNCapacityError(err) { + t.Fatalf("%q must not be classified as endpoint capacity", message) + } + } +} + func TestWrapHandshakeRetryUsesShortDedicatedWindow(t *testing.T) { minDelay, maxDelay := workerRetryDelayBounds( errors.New("WRAP_AUTH_TIMEOUT: отдельный DTLS-канал не ответил вовремя"), diff --git a/go_client/main.go b/go_client/main.go index c07e90e..eca85c3 100644 --- a/go_client/main.go +++ b/go_client/main.go @@ -235,6 +235,9 @@ func enqueueCaptchaResult(result CaptchaResult) { func main() { log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) os.Args = normalizeBooleanFlagArgs(os.Args, "-vkcalls-preflight") + os.Args = normalizeBooleanFlagArgs(os.Args, "-turn-stream-first") + os.Args = normalizeBooleanFlagArgs(os.Args, "-rt-masque") + os.Args = normalizeBooleanFlagArgs(os.Args, "-rt-masque-accept-tos") setupGlobalResolver() @@ -322,6 +325,36 @@ func main() { connPassword := flag.String("password", "", "пароль подключения") captchaMode := flag.String("captcha-mode", "auto", "режим обхода капчи (auto/wv/rjs)") vkCallsPreflight := flag.Bool("vkcalls-preflight", true, "пробовать VKCalls до captcha-цепочки") + turnStreamFirst := flag.Bool( + "turn-stream-first", + false, + "сначала пробовать TURN/TLS и TURN/TCP, сохраняя UDP как резерв", + ) + turnSNI := flag.String( + "turn-sni", + "", + "SNI белого списка для TURN/TLS (используется только внешним TLS-соединением)", + ) + rtMasque := flag.Bool( + "rt-masque", + false, + "после прямых путей Сети РТ пробовать WARP CONNECT-IP по HTTP/2 и HTTP/3", + ) + rtMasqueConfig := flag.String( + "rt-masque-config", + "", + "путь к приватной конфигурации enrollment WARP MASQUE", + ) + rtMasqueAcceptTOS := flag.Bool( + "rt-masque-accept-tos", + false, + "пользователь подтвердил условия Cloudflare для первой регистрации WARP", + ) + warpAPIRelay := flag.String( + "warp-api-relay", + "", + "локальный loopback-выход только для регистрации WARP API", + ) fingerprint := flag.String("fingerprint", "firefox", "браузерный фингерпринт (firefox, chrome, safari, ios, android)") clientIdsFlag := flag.String("client-ids", "", "ID клиентов VK через запятую") @@ -332,6 +365,22 @@ func main() { } activeCaptchaMode := setCaptchaMode(*captchaMode) setVKCallsPreflight(*vkCallsPreflight, *deviceID) + var normalizedTurnSNI string + if *turnStreamFirst { + var turnSNIErr error + normalizedTurnSNI, turnSNIErr = normalizeTURNFrontSNI(*turnSNI) + if turnSNIErr != nil { + log.Fatalf("[КЛИЕНТ] Некорректный TURN SNI: %v", turnSNIErr) + } + if normalizedTurnSNI != "" { + log.Printf("[TURN] Режим «Сеть РТ»: TURN/TLS, затем TCP ко всем адресам VK с разделением первого STUN-запроса; UDP остаётся резервом; внешний TLS SNI=%s", normalizedTurnSNI) + } else { + log.Printf("[TURN] Режим «Сеть РТ»: TURN/TLS, затем TCP ко всем адресам VK с разделением первого STUN-запроса; UDP остаётся резервом") + } + } + if *rtMasque && !*turnStreamFirst { + log.Printf("[MASQUE] Проигнорирован: механизм доступен только вместе с режимом «Сеть РТ»") + } if *vkHash == "" { log.Fatal("[КЛИЕНТ] Нужен -vk") @@ -404,11 +453,29 @@ func main() { useConfigFirstStart := *configFirstStart && *numW == workersPerGroup useHashFallback := *hashFallback && *numW == workersPerGroup + var masqueManager *warpMasqueManager + if *turnStreamFirst && *rtMasque { + if err := configureWarpAPIRelay(*warpAPIRelay); err != nil { + log.Printf("[MASQUE] Локальный выход для регистрации WARP отклонён: %v; продолжаем прямые попытки", err) + } + masqueManager, err = newWarpMasqueManager(ctx, *rtMasqueConfig, normalizedTurnSNI, *rtMasqueAcceptTOS) + if err != nil { + log.Printf("[MASQUE] Не удалось включить новый механизм: %v; прямые пути «Сети РТ» остаются доступны", err) + masqueManager = nil + } else { + defer masqueManager.Close() + log.Printf("[MASQUE] Включён резерв после прямых путей: HTTP/2 (TCP/443), затем HTTP/3 (QUIC/443)") + go masqueManager.prewarmConfig() + } + } + tp := &TurnParams{ - Host: *host, - Port: *port, - Hashes: hashes, - WrapKey: wrapKey, + Host: *host, + Port: *port, + Hashes: hashes, + TLSFrontSNI: normalizedTurnSNI, + Masque: masqueManager, + WrapKey: wrapKey, } // Слушаем локально с ожиданием (если старый процесс еще не убит Parent Watcher'ом) @@ -555,7 +622,7 @@ func main() { defer wg.Done() WorkerGroup(ctx, cancel, groupID, startHashIndex, tp, peer, disp, localPort, isFirstGroup, configChan, workerIds, *numW, useConfigFirstStart, useHashFallback, &pauseFlag, - *deviceID, *connPassword, *deviceInfo, transportSession, stats, waitR, sigR) + *deviceID, *connPassword, *deviceInfo, transportSession, stats, *turnStreamFirst, waitR, sigR) }(gID, isFirst, cc, ids, g, myWaitReady, mySignalReady) } diff --git a/go_client/masque_warp.go b/go_client/masque_warp.go new file mode 100644 index 0000000..faf679c --- /dev/null +++ b/go_client/masque_warp.go @@ -0,0 +1,1407 @@ +package main + +// The Cloudflare WARP MASQUE interoperability in this file is adapted from +// Diniboy1123/usque (MIT, commit 6aa03fc97d12848dce34eedbd187fb1077b5d1ea). +// It is intentionally isolated behind the explicit Android «Сеть РТ» + +// «MASQUE» opt-in. The ordinary WDTT transport never constructs this manager. + +import ( + "bytes" + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io" + "log" + "math/big" + "net" + "net/http" + "net/http/httptrace" + "net/netip" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + connectip "github.com/Diniboy1123/connect-ip-go" + "github.com/quic-go/quic-go" + "github.com/quic-go/quic-go/http3" + "github.com/yosida95/uritemplate/v3" + "golang.org/x/net/http2" + "golang.zx2c4.com/wireguard/tun" + "golang.zx2c4.com/wireguard/tun/netstack" +) + +const ( + warpConnectURI = "https://cloudflareaccess.com" + warpDefaultH2Endpoint = "162.159.198.2" + warpMasqueMTU = 1280 + warpConnectTimeout = 12 * time.Second + warpInnerDialTimeout = 10 * time.Second + warpAPIDialTimeout = 10 * time.Second + warpAPITLSTimeout = 8 * time.Second + warpAPIHeaderTimeout = 12 * time.Second + warpAPIFragmentSize = 32 + warpAPIFragmentDelay = 4 * time.Millisecond + warpConfigVersion = 1 + warpPacketHeadroom = 1 +) + +var ( + warpAPIBaseURL = "https://api.cloudflareclient.com/v0a4471" + warpHTTPClient = newWarpHTTPClient(false) + warpFragmentedHTTPClient = newWarpHTTPClient(true) + warpRelayHTTPClient *http.Client + warpRelayPreferred atomic.Bool +) + +// warpAPIFragmentConn divides only the first TLS ClientHello write. It leaves +// DNS, addresses, certificate validation and all later HTTPS bytes untouched. +// The wrapper is used only after a normal WARP API TLS handshake times out and +// only while the explicit Android «Сеть РТ» + «MASQUE» mode is enrolling. +type warpAPIFragmentConn struct { + net.Conn + mu sync.Mutex + fragmented bool + chunkSize int + delay time.Duration +} + +func isTLSClientHello(payload []byte) bool { + // TLS record: handshake(0x16), legacy record version 3.x, followed by + // ClientHello handshake type(0x01). + return len(payload) >= 9 && payload[0] == 0x16 && payload[1] == 0x03 && payload[5] == 0x01 +} + +func (conn *warpAPIFragmentConn) Write(payload []byte) (int, error) { + conn.mu.Lock() + shouldFragment := !conn.fragmented && isTLSClientHello(payload) + if shouldFragment { + conn.fragmented = true + } + conn.mu.Unlock() + if !shouldFragment { + return conn.Conn.Write(payload) + } + + chunkSize := conn.chunkSize + if chunkSize <= 0 { + chunkSize = warpAPIFragmentSize + } + total := 0 + for offset := 0; offset < len(payload); { + end := min(offset+chunkSize, len(payload)) + written, err := writeFull(conn.Conn, payload[offset:end]) + total += written + if err != nil { + return total, err + } + offset = end + if offset < len(payload) && conn.delay > 0 { + time.Sleep(conn.delay) + } + } + return total, nil +} + +func newWarpHTTPClient(fragmentClientHello bool) *http.Client { + // setupGlobalResolver may replace net.DefaultResolver with a direct route + // selected for VK. WARP enrollment must instead retain Android's original + // resolver and normal hostname-based HTTPS. No public DNS, pinned API IPs or + // address iteration are used here. + dialer := &net.Dialer{ + Timeout: warpAPIDialTimeout, + KeepAlive: 30 * time.Second, + Resolver: deviceSystemResolver, + } + dialContext := dialer.DialContext + forceHTTP2 := true + var tlsConfig *tls.Config + if fragmentClientHello { + forceHTTP2 = false + tlsConfig = &tls.Config{ + MinVersion: tls.VersionTLS12, + MaxVersion: tls.VersionTLS12, + NextProtos: []string{"http/1.1"}, + } + dialContext = func(ctx context.Context, network, address string) (net.Conn, error) { + connection, err := dialer.DialContext(ctx, network, address) + if err != nil { + return nil, err + } + if tcp, ok := connection.(*net.TCPConn); ok { + _ = tcp.SetNoDelay(true) + } + return &warpAPIFragmentConn{ + Conn: connection, + chunkSize: warpAPIFragmentSize, + delay: warpAPIFragmentDelay, + }, nil + } + } + return &http.Client{ + Timeout: 30 * time.Second, + Transport: &http.Transport{ + Proxy: http.ProxyFromEnvironment, + // Keep the normal dual-stack "tcp" network selected by net/http. + // Android can therefore use IPv6 or its standard IPv4 fallback without + // direct DNS servers, pinned addresses or manual address iteration. + DialContext: dialContext, + TLSClientConfig: tlsConfig, + ForceAttemptHTTP2: forceHTTP2, + MaxIdleConns: 4, + IdleConnTimeout: 30 * time.Second, + TLSHandshakeTimeout: warpAPITLSTimeout, + ResponseHeaderTimeout: warpAPIHeaderTimeout, + }, + } +} + +func normalizeWarpAPIRelayAddress(address string) (string, error) { + address = strings.TrimSpace(address) + if address == "" { + return "", nil + } + host, port, err := net.SplitHostPort(address) + if err != nil { + return "", errors.New("локальный выход API WARP должен иметь формат адрес:порт") + } + ip, err := netip.ParseAddr(strings.Trim(host, "[]")) + if err != nil || !ip.IsLoopback() { + return "", errors.New("выход API WARP разрешён только через loopback Android") + } + parsedPort, err := strconv.Atoi(port) + if err != nil || !inRange(parsedPort, 1, 65535) { + return "", errors.New("некорректный локальный порт выхода API WARP") + } + return net.JoinHostPort(ip.String(), fmt.Sprintf("%d", parsedPort)), nil +} + +func newWarpRelayHTTPClient(address string) (*http.Client, error) { + normalized, err := normalizeWarpAPIRelayAddress(address) + if err != nil { + return nil, err + } + if normalized == "" { + return nil, nil + } + dialer := &net.Dialer{Timeout: warpAPIDialTimeout, KeepAlive: 30 * time.Second} + return &http.Client{ + Timeout: 30 * time.Second, + Transport: &http.Transport{ + Proxy: nil, + DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { + return dialer.DialContext(ctx, network, normalized) + }, + ForceAttemptHTTP2: true, + MaxIdleConns: 4, + IdleConnTimeout: 30 * time.Second, + TLSHandshakeTimeout: warpAPITLSTimeout, + ResponseHeaderTimeout: warpAPIHeaderTimeout, + }, + }, nil +} + +func configureWarpAPIRelay(address string) error { + client, err := newWarpRelayHTTPClient(address) + if err != nil { + return err + } + warpRelayHTTPClient = client + warpRelayPreferred.Store(false) + return nil +} + +func inRange(value, minimum, maximum int) bool { + return value >= minimum && value <= maximum +} + +type warpMasqueProtocol string + +const ( + warpMasqueHTTP2 warpMasqueProtocol = "HTTP/2" + warpMasqueHTTP3 warpMasqueProtocol = "HTTP/3" +) + +func warpMasqueProtocolOrder(preferred warpMasqueProtocol) []warpMasqueProtocol { + if preferred == warpMasqueHTTP3 { + return []warpMasqueProtocol{warpMasqueHTTP3, warpMasqueHTTP2} + } + return []warpMasqueProtocol{warpMasqueHTTP2, warpMasqueHTTP3} +} + +type warpMasqueConfig struct { + Version int `json:"version"` + PrivateKey string `json:"private_key"` + EndpointV4 string `json:"endpoint_v4"` + EndpointH2V4 string `json:"endpoint_h2_v4"` + EndpointPubKey string `json:"endpoint_pub_key"` + DeviceID string `json:"device_id"` + AccessToken string `json:"access_token"` + IPv4 string `json:"ipv4"` + IPv6 string `json:"ipv6"` +} + +func (cfg *warpMasqueConfig) validate() error { + if cfg == nil { + return errors.New("пустая конфигурация WARP") + } + if cfg.Version != warpConfigVersion { + return fmt.Errorf("неподдерживаемая версия конфигурации WARP: %d", cfg.Version) + } + if _, err := cfg.privateKey(); err != nil { + return err + } + if _, err := cfg.endpointPublicKey(); err != nil { + return err + } + if net.ParseIP(cfg.EndpointV4) == nil { + return fmt.Errorf("некорректный WARP HTTP/3 endpoint: %q", cfg.EndpointV4) + } + if cfg.EndpointH2V4 == "" { + cfg.EndpointH2V4 = warpDefaultH2Endpoint + } + if net.ParseIP(cfg.EndpointH2V4) == nil { + return fmt.Errorf("некорректный WARP HTTP/2 endpoint: %q", cfg.EndpointH2V4) + } + if ip, err := netip.ParseAddr(cfg.IPv4); err != nil || !ip.Is4() { + return fmt.Errorf("некорректный внутренний IPv4 WARP: %q", cfg.IPv4) + } + return nil +} + +func (cfg *warpMasqueConfig) privateKey() (*ecdsa.PrivateKey, error) { + encoded, err := base64.StdEncoding.DecodeString(cfg.PrivateKey) + if err != nil { + return nil, fmt.Errorf("декодирование приватного ключа WARP: %w", err) + } + key, err := x509.ParseECPrivateKey(encoded) + if err != nil { + return nil, fmt.Errorf("разбор приватного ключа WARP: %w", err) + } + return key, nil +} + +func (cfg *warpMasqueConfig) endpointPublicKey() (*ecdsa.PublicKey, error) { + block, _ := pem.Decode([]byte(cfg.EndpointPubKey)) + if block == nil { + return nil, errors.New("декодирование закреплённого ключа WARP endpoint") + } + parsed, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("разбор закреплённого ключа WARP endpoint: %w", err) + } + key, ok := parsed.(*ecdsa.PublicKey) + if !ok { + return nil, errors.New("закреплённый ключ WARP endpoint не является ECDSA") + } + return key, nil +} + +func loadWarpMasqueConfig(path string) (*warpMasqueConfig, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var cfg warpMasqueConfig + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, fmt.Errorf("разбор конфигурации WARP: %w", err) + } + if err := cfg.validate(); err != nil { + return nil, err + } + return &cfg, nil +} + +func saveWarpMasqueConfig(path string, cfg *warpMasqueConfig) error { + if err := cfg.validate(); err != nil { + return err + } + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("создание каталога конфигурации WARP: %w", err) + } + data, err := json.Marshal(cfg) + if err != nil { + return fmt.Errorf("кодирование конфигурации WARP: %w", err) + } + tmp, err := os.CreateTemp(dir, ".rt-masque-*.tmp") + if err != nil { + return fmt.Errorf("создание временной конфигурации WARP: %w", err) + } + tmpPath := tmp.Name() + committed := false + defer func() { + _ = tmp.Close() + if !committed { + _ = os.Remove(tmpPath) + } + }() + if err := tmp.Chmod(0o600); err != nil { + return fmt.Errorf("права конфигурации WARP: %w", err) + } + if _, err := tmp.Write(data); err != nil { + return fmt.Errorf("запись конфигурации WARP: %w", err) + } + if err := tmp.Sync(); err != nil { + return fmt.Errorf("синхронизация конфигурации WARP: %w", err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("закрытие конфигурации WARP: %w", err) + } + if err := os.Rename(tmpPath, path); err != nil { + return fmt.Errorf("сохранение конфигурации WARP: %w", err) + } + committed = true + return nil +} + +type warpRegistrationRequest struct { + Key string `json:"key"` + InstallID string `json:"install_id"` + FCMToken string `json:"fcm_token"` + TOS string `json:"tos"` + Model string `json:"model"` + Serial string `json:"serial_number"` + OSVersion string `json:"os_version"` + KeyType string `json:"key_type"` + TunType string `json:"tunnel_type"` + Locale string `json:"locale"` +} + +type warpEnrollRequest struct { + Key string `json:"key"` + KeyType string `json:"key_type"` + TunType string `json:"tunnel_type"` + Name string `json:"name,omitempty"` +} + +type warpAccountData struct { + ID string `json:"id"` + Token string `json:"token"` + Config struct { + Interface struct { + Addresses struct { + V4 string `json:"v4"` + V6 string `json:"v6"` + } `json:"addresses"` + } `json:"interface"` + Peers []struct { + PublicKey string `json:"public_key"` + Endpoint struct { + V4 string `json:"v4"` + } `json:"endpoint"` + } `json:"peers"` + } `json:"config"` +} + +type warpAPIRequestPhase string + +const ( + warpAPIPhasePreparing warpAPIRequestPhase = "подготовка HTTPS-запроса" + warpAPIPhaseDNS warpAPIRequestPhase = "системный DNS Android" + warpAPIPhaseTCP warpAPIRequestPhase = "подключение TCP/443" + warpAPIPhaseTLS warpAPIRequestPhase = "TLS-рукопожатие" + warpAPIPhaseWrite warpAPIRequestPhase = "отправка HTTP-запроса" + warpAPIPhaseResponse warpAPIRequestPhase = "ожидание HTTP-ответа" +) + +// warpAPIRequestTrace records only protocol phases. It deliberately does not +// retain the request URL, device ID, authorization token or resolved address. +type warpAPIRequestTrace struct { + mu sync.Mutex + phase warpAPIRequestPhase + requestWritten bool + dnsLogged bool + tcpLogged bool + tlsLogged bool + writeLogged bool + responseLogged bool + serverRelay bool +} + +func newWarpAPIRequestTrace(serverRelay ...bool) *warpAPIRequestTrace { + return &warpAPIRequestTrace{ + phase: warpAPIPhasePreparing, + serverRelay: len(serverRelay) > 0 && serverRelay[0], + } +} + +func (trace *warpAPIRequestTrace) setPhase(phase warpAPIRequestPhase) { + trace.mu.Lock() + trace.phase = phase + trace.mu.Unlock() +} + +func (trace *warpAPIRequestTrace) snapshot() (warpAPIRequestPhase, bool) { + trace.mu.Lock() + defer trace.mu.Unlock() + return trace.phase, trace.requestWritten +} + +func (trace *warpAPIRequestTrace) clientTrace() *httptrace.ClientTrace { + return &httptrace.ClientTrace{ + DNSStart: func(httptrace.DNSStartInfo) { + trace.setPhase(warpAPIPhaseDNS) + }, + DNSDone: func(info httptrace.DNSDoneInfo) { + if info.Err != nil { + return + } + trace.mu.Lock() + shouldLog := !trace.dnsLogged + trace.dnsLogged = true + trace.mu.Unlock() + if shouldLog { + logMasque("API Cloudflare: системный DNS Android разрешил адрес ✓") + } + }, + ConnectStart: func(_, _ string) { + trace.setPhase(warpAPIPhaseTCP) + }, + ConnectDone: func(_, _ string, err error) { + if err != nil { + return + } + trace.mu.Lock() + shouldLog := !trace.tcpLogged + trace.tcpLogged = true + trace.mu.Unlock() + if shouldLog { + if trace.serverRelay { + logMasque("API Cloudflare: защищённый выход через сервер профиля доступен ✓") + } else { + logMasque("API Cloudflare: TCP/443 через системную сеть Android установлен ✓") + } + } + }, + TLSHandshakeStart: func() { + trace.setPhase(warpAPIPhaseTLS) + }, + TLSHandshakeDone: func(state tls.ConnectionState, err error) { + if err != nil { + return + } + trace.mu.Lock() + shouldLog := !trace.tlsLogged + trace.tlsLogged = true + trace.mu.Unlock() + if shouldLog { + protocol := state.NegotiatedProtocol + if protocol == "h2" { + protocol = "HTTP/2" + } else if protocol == "" { + protocol = "HTTP/1.1" + } + logMasque("API Cloudflare: TLS-рукопожатие завершено, согласован %s ✓", protocol) + } + }, + WroteRequest: func(info httptrace.WroteRequestInfo) { + trace.mu.Lock() + trace.phase = warpAPIPhaseWrite + if info.Err == nil { + trace.requestWritten = true + trace.phase = warpAPIPhaseResponse + } + shouldLog := info.Err == nil && !trace.writeLogged + if shouldLog { + trace.writeLogged = true + } + trace.mu.Unlock() + if shouldLog { + logMasque("API Cloudflare: HTTP-запрос отправлен, ожидаем ответ...") + } + }, + GotFirstResponseByte: func() { + trace.mu.Lock() + trace.phase = warpAPIPhaseResponse + shouldLog := !trace.responseLogged + trace.responseLogged = true + trace.mu.Unlock() + if shouldLog { + logMasque("API Cloudflare: получен первый байт HTTP-ответа ✓") + } + }, + } +} + +func warpAPIRequest(ctx context.Context, method, url, token string, body any, out any) error { + encoded, err := json.Marshal(body) + if err != nil { + return err + } + var resp *http.Response + requestClient := warpHTTPClient + fragmentedTLSAttempt := false + serverRelayAttempt := false + maxAttempts := 2 + if warpRelayHTTPClient != nil && warpRelayPreferred.Load() { + requestClient = warpRelayHTTPClient + serverRelayAttempt = true + maxAttempts = 1 + } else if warpRelayHTTPClient != nil { + maxAttempts = 3 + } + for attempt := 1; attempt <= maxAttempts; attempt++ { + req, requestErr := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(encoded)) + if requestErr != nil { + return requestErr + } + req.Header.Set("User-Agent", "WARP for Android") + req.Header.Set("CF-Client-Version", "a-6.35-4471") + req.Header.Set("Content-Type", "application/json; charset=UTF-8") + req.Header.Set("Connection", "Keep-Alive") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + + requestTrace := newWarpAPIRequestTrace(serverRelayAttempt) + req = req.WithContext(httptrace.WithClientTrace(req.Context(), requestTrace.clientTrace())) + resp, err = requestClient.Do(req) + if err == nil { + break + } + phase, requestWritten := requestTrace.snapshot() + diagnosis := warpAPINetworkError(err, phase) + if serverRelayAttempt { + diagnosis = warpAPIRelayNetworkError(err, phase) + } + if attempt == 1 && !requestWritten && ctx.Err() == nil && warpAPICanRetryBeforeWrite(err) { + requestClient.CloseIdleConnections() + if warpAPIIsTLSHandshakeTimeout(err, phase) { + fragmentedTLSAttempt = true + requestClient = warpFragmentedHTTPClient + logMasque("API Cloudflare: обычный TLS не прошёл до отправки данных — повторяем через TLS 1.2/HTTP 1.1 с разделённым ClientHello") + } else { + logMasque("API Cloudflare: %v; данные устройства ещё не отправлялись — выполняем одну безопасную повторную попытку", diagnosis) + } + continue + } + if attempt == 2 && warpRelayHTTPClient != nil && !requestWritten && + ctx.Err() == nil && warpAPICanRetryBeforeWrite(err) { + requestClient.CloseIdleConnections() + requestClient = warpRelayHTTPClient + serverRelayAttempt = true + logMasque("API Cloudflare: прямые HTTPS-пути недоступны до отправки данных — пробуем защищённый выход через сервер профиля") + continue + } + if serverRelayAttempt { + return diagnosis + } + if fragmentedTLSAttempt { + detail := strings.TrimPrefix(diagnosis.Error(), "WARP API: ") + return fmt.Errorf("WARP API: резерв TLS 1.2/HTTP 1.1 с разделённым ClientHello не сработал: %s", detail) + } + return diagnosis + } + if serverRelayAttempt { + warpRelayPreferred.Store(true) + logMasque("API Cloudflare: защищённый выход через сервер профиля сработал ✓") + } + defer resp.Body.Close() + limited := io.LimitReader(resp.Body, 1<<20) + responseBody, err := io.ReadAll(limited) + if err != nil { + return fmt.Errorf("чтение ответа WARP API (HTTP %d): %w", resp.StatusCode, err) + } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return errors.New(warpAPIErrorMessage(resp.StatusCode, responseBody)) + } + contentType := strings.Join(strings.Fields(resp.Header.Get("Content-Type")), " ") + if len(contentType) > 80 { + contentType = contentType[:80] + } + if contentType == "" { + contentType = "не указан" + } + trimmedBody := bytes.TrimSpace(responseBody) + if len(trimmedBody) == 0 { + return fmt.Errorf("WARP API вернул пустой ответ: HTTP %d, Content-Type=%s", resp.StatusCode, contentType) + } + if !json.Valid(trimmedBody) { + return fmt.Errorf( + "WARP API вернул ответ не в формате JSON: HTTP %d, Content-Type=%s, размер=%d байт", + resp.StatusCode, + contentType, + len(responseBody), + ) + } + if err := json.Unmarshal(responseBody, out); err != nil { + return fmt.Errorf( + "структура JSON-ответа WARP API несовместима: HTTP %d, Content-Type=%s: %w", + resp.StatusCode, + contentType, + err, + ) + } + return nil +} + +func warpAPIRelayNetworkError(err error, phase warpAPIRequestPhase) error { + var requestErr *url.Error + if errors.As(err, &requestErr) { + err = requestErr.Err + } + var certificateErr x509.UnknownAuthorityError + if errors.As(err, &certificateErr) { + return errors.New("WARP API: выход через сервер профиля получил недоверенный сертификат Cloudflare; регистрация остановлена") + } + lowerDetail := strings.ToLower(err.Error()) + if strings.Contains(lowerDetail, "tls handshake timeout") || phase == warpAPIPhaseTLS { + return fmt.Errorf( + "WARP API: выход через сервер профиля установлен, но TLS-рукопожатие Cloudflare не завершилось за %d с", + int(warpAPITLSTimeout/time.Second), + ) + } + if phase == warpAPIPhaseResponse { + return fmt.Errorf( + "WARP API: HTTPS-запрос через сервер профиля отправлен, но Cloudflare не ответил за %d с", + int(warpAPIHeaderTimeout/time.Second), + ) + } + if phase == warpAPIPhaseTCP { + return fmt.Errorf( + "WARP API: локальный SSH-выход не установил TCP-путь к Cloudflare за %d с", + int(warpAPIDialTimeout/time.Second), + ) + } + base := strings.TrimPrefix(warpAPINetworkError(err, phase).Error(), "WARP API: ") + return fmt.Errorf("WARP API: выход через сервер профиля не сработал: %s", base) +} + +// http.Client includes the full request URL in *url.Error. The MASQUE PATCH +// URL contains the Cloudflare device ID, so unwrap it before logging while +// retaining a useful network diagnosis. +func warpAPINetworkError(err error, phase warpAPIRequestPhase) error { + var requestErr *url.Error + if errors.As(err, &requestErr) { + err = requestErr.Err + } + detail := strings.Join(strings.Fields(err.Error()), " ") + lowerDetail := strings.ToLower(detail) + if strings.Contains(lowerDetail, "tls handshake timeout") { + return fmt.Errorf( + "WARP API: тайм-аут TLS-рукопожатия (%d с) после успешного TCP/443; Cloudflare не завершил установку защищённого HTTPS-соединения", + int(warpAPITLSTimeout/time.Second), + ) + } + if strings.Contains(lowerDetail, "timeout awaiting response headers") || + strings.Contains(lowerDetail, "timeout awaiting response") { + return fmt.Errorf( + "WARP API: HTTP-запрос отправлен, но Cloudflare не прислал заголовки ответа за %d с", + int(warpAPIHeaderTimeout/time.Second), + ) + } + if errors.Is(err, context.DeadlineExceeded) { + return warpAPITimeoutForPhase(phase) + } + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) { + dnsDetail := strings.Join(strings.Fields(dnsErr.Err), " ") + if dnsDetail == "" { + dnsDetail = "адрес не найден" + } + return fmt.Errorf("WARP API: системный DNS Android не разрешил %s: %s", dnsErr.Name, dnsDetail) + } + var certificateErr x509.UnknownAuthorityError + if errors.As(err, &certificateErr) { + return errors.New("WARP API: сертификат TLS выпущен неизвестным центром сертификации") + } + var networkErr net.Error + if errors.As(err, &networkErr) && networkErr.Timeout() { + return warpAPITimeoutForPhase(phase) + } + if len(detail) > 200 { + detail = detail[:200] + } + return fmt.Errorf("WARP API: сетевая ошибка на фазе «%s»: %s", phase, detail) +} + +func warpAPITimeoutForPhase(phase warpAPIRequestPhase) error { + switch phase { + case warpAPIPhaseDNS: + return errors.New("WARP API: тайм-аут системного DNS Android при разрешении адреса Cloudflare") + case warpAPIPhaseTCP: + return fmt.Errorf( + "WARP API: тайм-аут подключения TCP/443 к Cloudflare (%d с) после ответа системного DNS Android", + int(warpAPIDialTimeout/time.Second), + ) + case warpAPIPhaseTLS: + return fmt.Errorf( + "WARP API: тайм-аут TLS-рукопожатия (%d с) после успешного TCP/443; Cloudflare не завершил установку защищённого HTTPS-соединения", + int(warpAPITLSTimeout/time.Second), + ) + case warpAPIPhaseWrite: + return errors.New("WARP API: тайм-аут при отправке HTTPS-запроса в Cloudflare") + case warpAPIPhaseResponse: + return fmt.Errorf( + "WARP API: HTTP-запрос отправлен, но Cloudflare не прислал ответ за %d с", + int(warpAPIHeaderTimeout/time.Second), + ) + default: + return errors.New("WARP API: превышено общее время ожидания HTTPS-запроса") + } +} + +func warpAPICanRetryBeforeWrite(err error) bool { + var requestErr *url.Error + if errors.As(err, &requestErr) { + err = requestErr.Err + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return false + } + var certificateErr x509.UnknownAuthorityError + if errors.As(err, &certificateErr) { + return false + } + var networkErr net.Error + return errors.As(err, &networkErr) && (networkErr.Timeout() || networkErr.Temporary()) +} + +func warpAPIIsTLSHandshakeTimeout(err error, phase warpAPIRequestPhase) bool { + if phase != warpAPIPhaseTLS { + return false + } + var requestErr *url.Error + if errors.As(err, &requestErr) { + err = requestErr.Err + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return false + } + if strings.Contains(strings.ToLower(err.Error()), "tls handshake timeout") { + return true + } + var networkErr net.Error + return errors.As(err, &networkErr) && networkErr.Timeout() +} + +func warpAPIErrorMessage(status int, responseBody []byte) string { + var payload struct { + Errors []struct { + Code int `json:"code"` + Message string `json:"message"` + } `json:"errors"` + } + details := make([]string, 0, 2) + if json.Unmarshal(responseBody, &payload) == nil { + for _, item := range payload.Errors { + message := strings.Join(strings.Fields(item.Message), " ") + if len(message) > 160 { + message = message[:160] + } + if item.Code != 0 && message != "" { + details = append(details, fmt.Sprintf("code=%d %s", item.Code, message)) + } else if item.Code != 0 { + details = append(details, fmt.Sprintf("code=%d", item.Code)) + } else if message != "" { + details = append(details, message) + } + if len(details) == 2 { + break + } + } + } + if len(details) == 0 { + return fmt.Sprintf("WARP API HTTP %d", status) + } + return fmt.Sprintf("WARP API HTTP %d: %s", status, strings.Join(details, "; ")) +} + +func randomBytes(size int) ([]byte, error) { + value := make([]byte, size) + if _, err := rand.Read(value); err != nil { + return nil, err + } + return value, nil +} + +func endpointHost(raw string) (string, error) { + raw = strings.TrimSpace(raw) + if host, _, err := net.SplitHostPort(raw); err == nil { + host = strings.Trim(host, "[]") + if net.ParseIP(host) == nil { + return "", fmt.Errorf("некорректный endpoint %q", raw) + } + return host, nil + } + host := strings.Trim(raw, "[]") + if net.ParseIP(host) == nil { + return "", fmt.Errorf("некорректный endpoint %q", raw) + } + return host, nil +} + +func enrollWarpMasque(ctx context.Context, deviceName string) (*warpMasqueConfig, error) { + wgKey, err := randomBytes(32) + if err != nil { + return nil, fmt.Errorf("этап 1/4, создание ключа устройства WARP: %w", err) + } + serial, err := randomBytes(8) + if err != nil { + return nil, fmt.Errorf("этап 1/4, создание идентификатора устройства WARP: %w", err) + } + registration := warpRegistrationRequest{ + Key: base64.StdEncoding.EncodeToString(wgKey), + TOS: time.Now().Format("2006-01-02T15:04:05.000-07:00"), + Model: "Android", + Serial: hex.EncodeToString(serial), + KeyType: "curve25519", + TunType: "wireguard", + Locale: "ru_RU", + InstallID: "", + FCMToken: "", + OSVersion: "", + } + var registered warpAccountData + if err := warpAPIRequest(ctx, http.MethodPost, warpAPIBaseURL+"/reg", "", registration, ®istered); err != nil { + return nil, fmt.Errorf("этап 1/4, создание устройства WARP: %w", err) + } + if registered.ID == "" || registered.Token == "" { + return nil, errors.New("этап 1/4, создание устройства WARP: Cloudflare не вернул ID или токен") + } + logMasque("этап 1/4 завершён: устройство WARP создано в Cloudflare; этап 2/4 — включаем для него MASQUE") + + privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, fmt.Errorf("этап 2/4, создание ключа MASQUE: %w", err) + } + privateDER, err := x509.MarshalECPrivateKey(privateKey) + if err != nil { + return nil, fmt.Errorf("этап 2/4, кодирование приватного ключа MASQUE: %w", err) + } + publicDER, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey) + if err != nil { + return nil, fmt.Errorf("этап 2/4, кодирование публичного ключа MASQUE: %w", err) + } + enrollment := warpEnrollRequest{ + Key: base64.StdEncoding.EncodeToString(publicDER), + KeyType: "secp256r1", + TunType: "masque", + Name: deviceName, + } + var enrolled warpAccountData + url := warpAPIBaseURL + "/reg/" + registered.ID + if err := warpAPIRequest(ctx, http.MethodPatch, url, registered.Token, enrollment, &enrolled); err != nil { + return nil, fmt.Errorf("этап 2/4, включение MASQUE для устройства WARP: %w", err) + } + if len(enrolled.Config.Peers) == 0 { + return nil, errors.New("этап 2/4, включение MASQUE: Cloudflare не вернул адрес MASQUE") + } + logMasque("этап 2/4 завершён: Cloudflare принял ключ MASQUE; этап 3/4 — проверяем адреса и ключ сервера") + endpoint, err := endpointHost(enrolled.Config.Peers[0].Endpoint.V4) + if err != nil { + return nil, fmt.Errorf("этап 3/4, проверка адреса MASQUE: %w", err) + } + cfg := &warpMasqueConfig{ + Version: warpConfigVersion, + PrivateKey: base64.StdEncoding.EncodeToString(privateDER), + EndpointV4: endpoint, + EndpointH2V4: warpDefaultH2Endpoint, + EndpointPubKey: enrolled.Config.Peers[0].PublicKey, + DeviceID: enrolled.ID, + AccessToken: registered.Token, + IPv4: enrolled.Config.Interface.Addresses.V4, + IPv6: enrolled.Config.Interface.Addresses.V6, + } + if err := cfg.validate(); err != nil { + return nil, fmt.Errorf("этап 3/4, проверка ответа Cloudflare: неполная конфигурация WARP: %w", err) + } + logMasque("этап 3/4 завершён: конфигурация MASQUE корректна") + return cfg, nil +} + +func warpMasqueTLSConfig(cfg *warpMasqueConfig, sni string, protocol warpMasqueProtocol) (*tls.Config, error) { + privateKey, err := cfg.privateKey() + if err != nil { + return nil, err + } + endpointKey, err := cfg.endpointPublicKey() + if err != nil { + return nil, err + } + certificateDER, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{ + SerialNumber: big.NewInt(time.Now().UnixNano()), + NotBefore: time.Now().Add(-time.Minute), + NotAfter: time.Now().Add(24 * time.Hour), + }, &x509.Certificate{}, &privateKey.PublicKey, privateKey) + if err != nil { + return nil, fmt.Errorf("клиентский сертификат WARP: %w", err) + } + nextProto := http3.NextProtoH3 + if protocol == warpMasqueHTTP2 { + nextProto = "h2" + } + tlsConfig := &tls.Config{ + Certificates: []tls.Certificate{{ + Certificate: [][]byte{certificateDER}, + PrivateKey: privateKey, + }}, + ServerName: sni, + NextProtos: []string{nextProto}, + MinVersion: tls.VersionTLS12, + InsecureSkipVerify: true, // имя подменено; ниже обязательный pin ключа endpoint + } + tlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error { + if len(rawCerts) == 0 { + return errors.New("WARP endpoint не прислал сертификат") + } + cert, err := x509.ParseCertificate(rawCerts[0]) + if err != nil { + return err + } + actual, ok := cert.PublicKey.(*ecdsa.PublicKey) + if !ok || !actual.Equal(endpointKey) { + return errors.New("публичный ключ WARP endpoint не совпал с enrollment") + } + return nil + } + return tlsConfig, nil +} + +type warpMasqueOuter struct { + ipConn *connectip.Conn + cancel context.CancelFunc + udpConn *net.UDPConn + quicConn *quic.Conn + h3Transport *http3.Transport + h2Transport *http2.Transport + h2RawConnLock sync.Mutex + h2RawConn net.Conn +} + +func (outer *warpMasqueOuter) close() { + if outer == nil { + return + } + if outer.ipConn != nil { + _ = outer.ipConn.Close() + } + if outer.cancel != nil { + outer.cancel() + } + if outer.h3Transport != nil { + _ = outer.h3Transport.Close() + } + if outer.quicConn != nil { + _ = outer.quicConn.CloseWithError(0, "WDTT shutdown") + } + if outer.udpConn != nil { + _ = outer.udpConn.Close() + } + if outer.h2Transport != nil { + outer.h2Transport.CloseIdleConnections() + } + outer.h2RawConnLock.Lock() + if outer.h2RawConn != nil { + _ = outer.h2RawConn.Close() + outer.h2RawConn = nil + } + outer.h2RawConnLock.Unlock() +} + +func connectWarpMasque(ctx context.Context, cfg *warpMasqueConfig, sni string, protocol warpMasqueProtocol) (*warpMasqueOuter, error) { + tlsConfig, err := warpMasqueTLSConfig(cfg, sni, protocol) + if err != nil { + return nil, err + } + template := uritemplate.MustNew(warpConnectURI) + headers := http.Header{"User-Agent": []string{""}} + + if protocol == warpMasqueHTTP2 { + endpoint := &net.TCPAddr{IP: net.ParseIP(cfg.EndpointH2V4), Port: 443} + outer := &warpMasqueOuter{} + transport := &http2.Transport{ + DialTLSContext: func(dialCtx context.Context, network, _ string, _ *tls.Config) (net.Conn, error) { + raw, err := (&net.Dialer{Timeout: warpConnectTimeout, KeepAlive: 30 * time.Second}).DialContext(dialCtx, network, endpoint.String()) + if err != nil { + return nil, err + } + tlsConn := tls.Client(raw, tlsConfig.Clone()) + if err := tlsConn.HandshakeContext(dialCtx); err != nil { + _ = raw.Close() + return nil, err + } + outer.h2RawConnLock.Lock() + outer.h2RawConn = tlsConn + outer.h2RawConnLock.Unlock() + return tlsConn, nil + }, + } + outer.h2Transport = transport + h2Headers := headers.Clone() + h2Headers.Set("cf-connect-proto", "cf-connect-ip") + h2Headers.Set("pq-enabled", "false") + ipConn, _, err := connectip.DialH2(ctx, &http.Client{Transport: transport}, template, h2Headers) + if err != nil { + outer.close() + return nil, fmt.Errorf("CONNECT-IP HTTP/2: %w", err) + } + outer.ipConn = ipConn + return outer, nil + } + + endpoint := &net.UDPAddr{IP: net.ParseIP(cfg.EndpointV4), Port: 443} + udpConn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero}) + if err != nil { + return nil, err + } + outer := &warpMasqueOuter{udpConn: udpConn} + qtr := &quic.Transport{Conn: udpConn, ConnectionIDLength: 20} + quicConn, err := qtr.Dial(ctx, endpoint, tlsConfig, &quic.Config{ + EnableDatagrams: true, + KeepAlivePeriod: 20 * time.Second, + }) + if err != nil { + outer.close() + return nil, fmt.Errorf("QUIC WARP: %w", err) + } + outer.quicConn = quicConn + h3Transport := &http3.Transport{ + EnableDatagrams: true, + AdditionalSettings: map[uint64]uint64{ + 0x276: 1, + }, + DisableCompression: true, + } + outer.h3Transport = h3Transport + ipConn, _, err := connectip.Dial(ctx, h3Transport.NewClientConn(quicConn), template, "cf-connect-ip", headers, true) + if err != nil { + outer.close() + return nil, fmt.Errorf("CONNECT-IP HTTP/3: %w", err) + } + outer.ipConn = ipConn + return outer, nil +} + +type warpMasqueTransport struct { + protocol warpMasqueProtocol + device tun.Device + network *netstack.Net + outer *warpMasqueOuter + done chan struct{} + close sync.Once +} + +func startWarpMasqueTransport(ctx context.Context, cfg *warpMasqueConfig, sni string, protocol warpMasqueProtocol) (*warpMasqueTransport, error) { + localAddresses := make([]netip.Addr, 0, 2) + v4, err := netip.ParseAddr(cfg.IPv4) + if err != nil { + return nil, err + } + localAddresses = append(localAddresses, v4) + if v6, err := netip.ParseAddr(cfg.IPv6); err == nil && v6.Is6() { + localAddresses = append(localAddresses, v6) + } + dnsServers := []netip.Addr{netip.MustParseAddr("1.1.1.1"), netip.MustParseAddr("1.0.0.1")} + device, network, err := netstack.CreateNetTUN(localAddresses, dnsServers, warpMasqueMTU) + if err != nil { + return nil, fmt.Errorf("создание MASQUE netstack: %w", err) + } + // CONNECT-IP uses the request context for the lifetime of the HTTP stream. + // Keep it alive after setup, but still bound a stalled handshake. + connectCtx, cancel := context.WithCancel(ctx) + timeout := time.AfterFunc(warpConnectTimeout, cancel) + outer, err := connectWarpMasque(connectCtx, cfg, sni, protocol) + timeout.Stop() + if err != nil { + cancel() + _ = device.Close() + return nil, err + } + outer.cancel = cancel + transport := &warpMasqueTransport{ + protocol: protocol, + device: device, + network: network, + outer: outer, + done: make(chan struct{}), + } + transport.startPumps(ctx) + return transport, nil +} + +func (transport *warpMasqueTransport) alive() bool { + select { + case <-transport.done: + return false + default: + return true + } +} + +func (transport *warpMasqueTransport) Close() { + if transport == nil { + return + } + transport.close.Do(func() { + close(transport.done) + if transport.outer != nil { + transport.outer.close() + } + if transport.device != nil { + _ = transport.device.Close() + } + }) +} + +func (transport *warpMasqueTransport) startPumps(ctx context.Context) { + fail := func(err error) { + if err != nil && ctx.Err() == nil && transport.alive() { + logMasque("туннель %s потерян: %v", transport.protocol, err) + } + transport.Close() + } + go func() { + buffer := make([]byte, warpMasqueMTU+warpPacketHeadroom) + bufs := [][]byte{buffer[warpPacketHeadroom:]} + sizes := []int{0} + for { + _, err := transport.device.Read(bufs, sizes, 0) + if err != nil { + fail(err) + return + } + n := sizes[0] + if n <= 0 { + continue + } + icmp, err := transport.outer.ipConn.WritePacketBuffer(buffer, warpPacketHeadroom, n) + if err != nil { + fail(err) + return + } + if len(icmp) > 0 { + if _, err := transport.device.Write([][]byte{icmp}, 0); err != nil { + fail(err) + return + } + } + } + }() + go func() { + for { + packet, err := transport.outer.ipConn.ReadPacketZeroCopy(true) + if err != nil { + fail(err) + return + } + if _, err := transport.device.Write([][]byte{packet}, 0); err != nil { + fail(err) + return + } + } + }() + go func() { + select { + case <-ctx.Done(): + transport.Close() + case <-transport.done: + } + }() +} + +func (transport *warpMasqueTransport) DialContext(ctx context.Context, target string) (net.Conn, error) { + if transport == nil || !transport.alive() { + return nil, net.ErrClosed + } + dialCtx, cancel := context.WithTimeout(ctx, warpInnerDialTimeout) + defer cancel() + return transport.network.DialContext(dialCtx, "tcp", target) +} + +type warpMasqueManager struct { + ctx context.Context + path string + sni string + acceptTOS bool + + mu sync.Mutex + config *warpMasqueConfig + configErr error + retryAfter time.Time + preferred warpMasqueProtocol + transports map[warpMasqueProtocol]*warpMasqueTransport + failures map[warpMasqueProtocol]warpMasqueFailure +} + +type warpMasqueFailure struct { + err error + retryAfter time.Time +} + +func newWarpMasqueManager(ctx context.Context, path, sni string, acceptTOS bool) (*warpMasqueManager, error) { + path = strings.TrimSpace(path) + if path == "" { + return nil, errors.New("не указан путь конфигурации WARP MASQUE") + } + if normalized, err := normalizeTURNFrontSNI(sni); err != nil || normalized == "" { + return nil, errors.New("для WARP MASQUE нужен корректный SNI белого списка") + } else { + sni = normalized + } + return &warpMasqueManager{ + ctx: ctx, + path: path, + sni: sni, + acceptTOS: acceptTOS, + transports: make(map[warpMasqueProtocol]*warpMasqueTransport), + failures: make(map[warpMasqueProtocol]warpMasqueFailure), + }, nil +} + +func (manager *warpMasqueManager) ensureConfigLocked() (*warpMasqueConfig, error) { + if manager.config != nil { + return manager.config, nil + } + if manager.configErr != nil && time.Now().Before(manager.retryAfter) { + return nil, manager.configErr + } + cfg, err := loadWarpMasqueConfig(manager.path) + if err == nil { + manager.config = cfg + manager.configErr = nil + return cfg, nil + } + if !errors.Is(err, os.ErrNotExist) { + manager.configErr = fmt.Errorf("сохранённая конфигурация WARP повреждена: %w", err) + manager.retryAfter = time.Now().Add(5 * time.Minute) + return nil, manager.configErr + } + if !manager.acceptTOS { + return nil, errors.New("для первой регистрации WARP требуется согласие с условиями Cloudflare") + } + logMasque("регистрация начата: этап 1/4 — создаём отдельное устройство WARP в Cloudflare") + enrollCtx, cancel := context.WithTimeout(manager.ctx, 40*time.Second) + defer cancel() + cfg, err = enrollWarpMasque(enrollCtx, "WDTT Plus") + if err != nil { + manager.configErr = err + manager.retryAfter = time.Now().Add(30 * time.Second) + return nil, manager.configErr + } + logMasque("этап 4/4 — сохраняем регистрацию WARP только в приватном хранилище приложения") + if err := saveWarpMasqueConfig(manager.path, cfg); err != nil { + manager.configErr = fmt.Errorf("этап 4/4, сохранение регистрации WARP: %w", err) + manager.retryAfter = time.Now().Add(30 * time.Second) + return nil, manager.configErr + } + manager.config = cfg + manager.configErr = nil + logMasque("этап 4/4 завершён: регистрация WARP сохранена в приватном хранилище приложения ✓") + return cfg, nil +} + +func (manager *warpMasqueManager) transportLocked(protocol warpMasqueProtocol) (*warpMasqueTransport, error) { + if current := manager.transports[protocol]; current != nil { + if current.alive() { + return current, nil + } + delete(manager.transports, protocol) + } + if failure, ok := manager.failures[protocol]; ok { + if time.Now().Before(failure.retryAfter) { + return nil, failure.err + } + delete(manager.failures, protocol) + } + cfg, err := manager.ensureConfigLocked() + if err != nil { + return nil, err + } + logMasque("устанавливаем CONNECT-IP %s через TCP/443 или QUIC/443; внешний SNI=%s", protocol, manager.sni) + transport, err := startWarpMasqueTransport(manager.ctx, cfg, manager.sni, protocol) + if err != nil { + manager.failures[protocol] = warpMasqueFailure{ + err: err, + retryAfter: time.Now().Add(30 * time.Second), + } + return nil, err + } + manager.transports[protocol] = transport + delete(manager.failures, protocol) + logMasque("CONNECT-IP %s установлен ✓", protocol) + return transport, nil +} + +func (manager *warpMasqueManager) DialContext(ctx context.Context, target string) (net.Conn, warpMasqueProtocol, error) { + order := manager.protocolOrder() + + var failures []string + for _, protocol := range order { + conn, err := manager.dialProtocol(ctx, target, protocol) + if err == nil { + manager.markPreferred(protocol) + return conn, protocol, nil + } + failures = append(failures, fmt.Sprintf("%s к %s: %v", protocol, target, err)) + } + return nil, "", fmt.Errorf("ни один MASQUE-путь не сработал: %s", strings.Join(failures, "; ")) +} + +func (manager *warpMasqueManager) prewarmConfig() { + if manager == nil { + return + } + manager.mu.Lock() + _, err := manager.ensureConfigLocked() + manager.mu.Unlock() + if err != nil { + if manager.ctx.Err() == nil { + logMasque("фоновая подготовка WARP пока не выполнена: %v", err) + } + return + } + logMasque("конфигурация WARP подготовлена; прямые пути продолжают иметь приоритет ✓") +} + +func (manager *warpMasqueManager) protocolOrder() []warpMasqueProtocol { + manager.mu.Lock() + defer manager.mu.Unlock() + return warpMasqueProtocolOrder(manager.preferred) +} + +func (manager *warpMasqueManager) dialProtocol(ctx context.Context, target string, protocol warpMasqueProtocol) (net.Conn, error) { + manager.mu.Lock() + transport, err := manager.transportLocked(protocol) + manager.mu.Unlock() + if err != nil { + return nil, err + } + return transport.DialContext(ctx, target) +} + +func (manager *warpMasqueManager) markPreferred(protocol warpMasqueProtocol) { + manager.mu.Lock() + manager.preferred = protocol + manager.mu.Unlock() +} + +func (manager *warpMasqueManager) Close() { + if manager == nil { + return + } + manager.mu.Lock() + defer manager.mu.Unlock() + for protocol, transport := range manager.transports { + transport.Close() + delete(manager.transports, protocol) + } +} + +func logMasque(format string, args ...any) { + log.Printf("[MASQUE] "+format, args...) +} diff --git a/go_client/masque_warp_test.go b/go_client/masque_warp_test.go new file mode 100644 index 0000000..fa983be --- /dev/null +++ b/go_client/masque_warp_test.go @@ -0,0 +1,337 @@ +package main + +import ( + "bytes" + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "errors" + "net" + "net/http" + "net/http/httptest" + "net/http/httptrace" + "net/url" + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +func testWarpMasqueConfig(t *testing.T) *warpMasqueConfig { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + privateDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + publicDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey) + if err != nil { + t.Fatal(err) + } + return &warpMasqueConfig{ + Version: warpConfigVersion, + PrivateKey: base64.StdEncoding.EncodeToString(privateDER), + EndpointV4: "162.159.197.1", + EndpointH2V4: warpDefaultH2Endpoint, + EndpointPubKey: string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER})), + DeviceID: "device", + AccessToken: "token", + IPv4: "172.16.0.2", + IPv6: "2606:4700:110:8f1b::2", + } +} + +func TestWarpMasqueProtocolOrder(t *testing.T) { + if got, want := warpMasqueProtocolOrder(""), []warpMasqueProtocol{warpMasqueHTTP2, warpMasqueHTTP3}; !reflect.DeepEqual(got, want) { + t.Fatalf("default order = %v, want %v", got, want) + } + if got, want := warpMasqueProtocolOrder(warpMasqueHTTP3), []warpMasqueProtocol{warpMasqueHTTP3, warpMasqueHTTP2}; !reflect.DeepEqual(got, want) { + t.Fatalf("remembered order = %v, want %v", got, want) + } +} + +func TestEndpointHost(t *testing.T) { + for input, want := range map[string]string{ + "162.159.197.1:0": "162.159.197.1", + "[2606:4700::1]:0": "2606:4700::1", + "162.159.197.1": "162.159.197.1", + } { + got, err := endpointHost(input) + if err != nil || got != want { + t.Fatalf("endpointHost(%q) = %q, %v; want %q", input, got, err, want) + } + } + if _, err := endpointHost("warp.invalid:0"); err == nil { + t.Fatal("hostname endpoint must be rejected") + } +} + +func TestWarpMasqueConfigRoundTripIsPrivate(t *testing.T) { + path := filepath.Join(t.TempDir(), "nested", "warp.json") + want := testWarpMasqueConfig(t) + if err := saveWarpMasqueConfig(path, want); err != nil { + t.Fatal(err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if got := info.Mode().Perm(); got != 0o600 { + t.Fatalf("config mode = %o, want 600", got) + } + got, err := loadWarpMasqueConfig(path) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("round trip mismatch:\n got %#v\nwant %#v", got, want) + } +} + +func TestWarpMasqueRequiresExplicitSNIAndConfigPath(t *testing.T) { + if _, err := newWarpMasqueManager(context.Background(), "", "ya.ru", true); err == nil { + t.Fatal("empty config path must be rejected") + } + if _, err := newWarpMasqueManager(context.Background(), "warp.json", "", true); err == nil { + t.Fatal("empty outer SNI must be rejected") + } +} + +func TestWarpAPIErrorMessageKeepsSafeStatusAndBackendCode(t *testing.T) { + got := warpAPIErrorMessage(429, []byte(`{"errors":[{"code":1042,"message":" rate limited "}]}`)) + want := "WARP API HTTP 429: code=1042 rate limited" + if got != want { + t.Fatalf("warpAPIErrorMessage = %q, want %q", got, want) + } +} + +func TestWarpAPINetworkErrorRemovesDeviceURL(t *testing.T) { + got := warpAPINetworkError(&url.Error{ + Op: "Patch", + URL: "https://api.cloudflareclient.com/v0a4471/reg/secret-device-id", + Err: context.DeadlineExceeded, + }, warpAPIPhaseResponse).Error() + if strings.Contains(got, "secret-device-id") || strings.Contains(got, "https://") { + t.Fatalf("network error leaked request URL: %q", got) + } + if !strings.Contains(got, "HTTP-запрос отправлен") { + t.Fatalf("network error lacks Russian diagnosis: %q", got) + } +} + +func TestWarpAPINetworkErrorNamesExactHTTPSPhase(t *testing.T) { + tlsError := warpAPINetworkError( + errors.New("net/http: TLS handshake timeout"), + warpAPIPhaseTLS, + ).Error() + if !strings.Contains(tlsError, "тайм-аут TLS-рукопожатия") || + !strings.Contains(tlsError, "после успешного TCP/443") { + t.Fatalf("TLS diagnosis = %q", tlsError) + } + + headerError := warpAPINetworkError( + errors.New("net/http: timeout awaiting response headers"), + warpAPIPhaseResponse, + ).Error() + if !strings.Contains(headerError, "HTTP-запрос отправлен") || + !strings.Contains(headerError, "не прислал заголовки ответа") { + t.Fatalf("response diagnosis = %q", headerError) + } +} + +func TestWarpAPIRelayErrorKeepsRussianPhaseWithoutEndpoint(t *testing.T) { + got := warpAPIRelayNetworkError( + &url.Error{ + Op: "Post", + URL: "https://api.cloudflareclient.com/private-device-path", + Err: errors.New("net/http: TLS handshake timeout"), + }, + warpAPIPhaseTLS, + ).Error() + if !strings.Contains(got, "через сервер профиля") || + !strings.Contains(got, "TLS-рукопожатие") { + t.Fatalf("relay diagnosis = %q", got) + } + if strings.Contains(got, "private-device-path") || strings.Contains(got, "https://") { + t.Fatalf("relay diagnosis leaked request URL: %q", got) + } +} + +func TestWarpAPITraceDistinguishesSafePreWriteFailure(t *testing.T) { + requestTrace := newWarpAPIRequestTrace() + clientTrace := requestTrace.clientTrace() + clientTrace.TLSHandshakeStart() + phase, written := requestTrace.snapshot() + if phase != warpAPIPhaseTLS || written { + t.Fatalf("before write: phase=%q written=%v", phase, written) + } + if !warpAPICanRetryBeforeWrite(&net.DNSError{Err: "timeout", IsTimeout: true}) { + t.Fatal("pre-write network timeout must allow one safe retry") + } + + clientTrace.WroteRequest(httptrace.WroteRequestInfo{}) + phase, written = requestTrace.snapshot() + if phase != warpAPIPhaseResponse || !written { + t.Fatalf("after write: phase=%q written=%v", phase, written) + } +} + +func TestWarpAPIFragmentConnOnlyFragmentsFirstTLSClientHello(t *testing.T) { + underlying := &recordingConn{} + connection := &warpAPIFragmentConn{ + Conn: underlying, + chunkSize: 8, + } + + proxyConnect := []byte("CONNECT api.cloudflareclient.com:443 HTTP/1.1\r\n\r\n") + if written, err := connection.Write(proxyConnect); err != nil || written != len(proxyConnect) { + t.Fatalf("proxy CONNECT write = %d, %v", written, err) + } + if len(underlying.writes) != 1 { + t.Fatalf("plain proxy request writes = %d, want 1", len(underlying.writes)) + } + + clientHello := append([]byte{0x16, 0x03, 0x01, 0x00, 0x18, 0x01, 0x00, 0x00, 0x14}, make([]byte, 20)...) + if written, err := connection.Write(clientHello); err != nil || written != len(clientHello) { + t.Fatalf("ClientHello write = %d, %v", written, err) + } + if got := len(underlying.writes); got != 1+4 { + t.Fatalf("writes after fragmented ClientHello = %d, want 5", got) + } + if reconstructed := bytes.Join(underlying.writes[1:], nil); !bytes.Equal(reconstructed, clientHello) { + t.Fatalf("fragmented ClientHello changed: %x", reconstructed) + } + + applicationData := []byte{0x17, 0x03, 0x03, 0x00, 0x03, 1, 2, 3} + if _, err := connection.Write(applicationData); err != nil { + t.Fatal(err) + } + if got := len(underlying.writes); got != 6 { + t.Fatalf("later TLS record was fragmented: writes=%d, want 6", got) + } +} + +func TestWarpHTTPClientsKeepCertificateVerificationAndIsolateFallback(t *testing.T) { + normalTransport, ok := newWarpHTTPClient(false).Transport.(*http.Transport) + if !ok { + t.Fatal("normal WARP client does not use net/http transport") + } + if !normalTransport.ForceAttemptHTTP2 || normalTransport.TLSClientConfig != nil { + t.Fatalf("normal WARP client changed: HTTP/2=%v TLS=%#v", normalTransport.ForceAttemptHTTP2, normalTransport.TLSClientConfig) + } + + fallbackTransport, ok := newWarpHTTPClient(true).Transport.(*http.Transport) + if !ok { + t.Fatal("fallback WARP client does not use net/http transport") + } + tlsConfig := fallbackTransport.TLSClientConfig + if tlsConfig == nil { + t.Fatal("fallback TLS configuration is missing") + } + if tlsConfig.MinVersion != tls.VersionTLS12 || tlsConfig.MaxVersion != tls.VersionTLS12 { + t.Fatalf("fallback TLS range = %x..%x, want TLS 1.2 only", tlsConfig.MinVersion, tlsConfig.MaxVersion) + } + if fallbackTransport.ForceAttemptHTTP2 || !reflect.DeepEqual(tlsConfig.NextProtos, []string{"http/1.1"}) { + t.Fatalf("fallback HTTP protocol = HTTP/2:%v ALPN:%v", fallbackTransport.ForceAttemptHTTP2, tlsConfig.NextProtos) + } + if tlsConfig.InsecureSkipVerify || tlsConfig.RootCAs != nil { + t.Fatal("fallback must retain system roots and full certificate verification") + } +} + +func TestWarpAPIRelayAcceptsOnlyLoopbackAndKeepsEndToEndTLS(t *testing.T) { + if _, err := normalizeWarpAPIRelayAddress("192.0.2.1:443"); err == nil { + t.Fatal("non-loopback relay must be rejected") + } + address, err := normalizeWarpAPIRelayAddress("127.0.0.1:19443") + if err != nil || address != "127.0.0.1:19443" { + t.Fatalf("loopback relay = %q, %v", address, err) + } + client, err := newWarpRelayHTTPClient(address) + if err != nil { + t.Fatal(err) + } + transport, ok := client.Transport.(*http.Transport) + if !ok { + t.Fatal("relay client does not use net/http transport") + } + if transport.Proxy != nil || transport.TLSClientConfig != nil || !transport.ForceAttemptHTTP2 { + t.Fatalf( + "relay changed HTTPS security: proxySet=%v TLS=%#v HTTP/2=%v", + transport.Proxy != nil, + transport.TLSClientConfig, + transport.ForceAttemptHTTP2, + ) + } +} + +func TestWarpAPIRecognizesOnlyTLSPhaseTimeoutForFragmentedRetry(t *testing.T) { + tlsTimeout := errors.New("net/http: TLS handshake timeout") + if !warpAPIIsTLSHandshakeTimeout(tlsTimeout, warpAPIPhaseTLS) { + t.Fatal("TLS handshake timeout must select the fragmented fallback") + } + if warpAPIIsTLSHandshakeTimeout(tlsTimeout, warpAPIPhaseTCP) { + t.Fatal("TCP-phase timeout must not select the TLS fallback") + } + if warpAPIIsTLSHandshakeTimeout(&net.DNSError{Err: "timeout", IsTimeout: true}, warpAPIPhaseDNS) { + t.Fatal("DNS timeout must not select the TLS fallback") + } +} + +func TestWarpAPIRequestDiagnosesUnexpectedSuccessfulResponse(t *testing.T) { + for name, body := range map[string]string{ + "empty": "", + "html": "challenge", + } { + t.Run(name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(body)) + })) + defer server.Close() + + var out warpAccountData + err := warpAPIRequest(context.Background(), http.MethodPost, server.URL, "", struct{}{}, &out) + if err == nil { + t.Fatal("unexpected response must fail") + } + message := err.Error() + if !strings.Contains(message, "HTTP 200") || !strings.Contains(message, "Content-Type=text/html") { + t.Fatalf("diagnosis lacks status or content type: %q", message) + } + if strings.Contains(message, body) && body != "" { + t.Fatalf("diagnosis leaked response body: %q", message) + } + }) + } +} + +func TestTurnCandidateStagesAreIsolatedBehindMasque(t *testing.T) { + candidates := []turnEndpoint{ + {Host: "turns.example", Port: "443", Transport: turnTransportTLS}, + {Host: "turn.example", Port: "443", Transport: turnTransportTCP}, + {Host: "turn.example", Port: "3478", Transport: turnTransportUDP}, + } + + direct, masque, finalUDP := turnCandidateStages(candidates, false) + if !reflect.DeepEqual(direct, candidates) || masque != nil || finalUDP != nil { + t.Fatalf("ordinary stages changed: direct=%v masque=%v udp=%v", direct, masque, finalUDP) + } + + direct, masque, finalUDP = turnCandidateStages(candidates, true) + wantStream := candidates[:2] + wantUDP := candidates[2:] + if !reflect.DeepEqual(direct, wantStream) || !reflect.DeepEqual(masque, wantStream) || !reflect.DeepEqual(finalUDP, wantUDP) { + t.Fatalf("MASQUE stages = direct=%v masque=%v udp=%v", direct, masque, finalUDP) + } +} diff --git a/go_client/session.go b/go_client/session.go index b3f66c5..08d6d27 100644 --- a/go_client/session.go +++ b/go_client/session.go @@ -3,7 +3,10 @@ package main import ( "context" "crypto/tls" + "crypto/x509" + "errors" "fmt" + "io" "log" "net" "strings" @@ -64,12 +67,136 @@ type connectedUDPConn struct{ *net.UDPConn } func (c *connectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) { return c.Write(p) } +// splitFirstWriteConn fragments the first STUN request so its magic cookie +// crosses TCP segment boundaries. Some shallow DPI rules classify plain TURN +// by looking only at the first segment. This wrapper is enabled exclusively by +// the explicit «Сеть РТ» mode; ordinary operators keep the original writes. +type splitFirstWriteConn struct { + net.Conn + splitAt int + delay time.Duration + done atomic.Bool +} + +func writeFull(conn net.Conn, payload []byte) (int, error) { + total := 0 + for len(payload) > 0 { + n, err := conn.Write(payload) + total += n + payload = payload[n:] + if err != nil { + return total, err + } + if n == 0 { + return total, io.ErrShortWrite + } + } + return total, nil +} + +func (conn *splitFirstWriteConn) Write(payload []byte) (int, error) { + if !conn.done.CompareAndSwap(false, true) || len(payload) <= conn.splitAt { + return conn.Conn.Write(payload) + } + first, err := writeFull(conn.Conn, payload[:conn.splitAt]) + if err != nil { + return first, err + } + if conn.delay > 0 { + time.Sleep(conn.delay) + } + second, err := writeFull(conn.Conn, payload[conn.splitAt:]) + return first + second, err +} + +func normalizeTURNFrontSNI(value string) (string, error) { + host := strings.ToLower(strings.TrimSpace(value)) + if host == "" { + return "", nil + } + if len(host) > 253 || net.ParseIP(host) != nil || strings.HasPrefix(host, ".") || + strings.HasSuffix(host, ".") || strings.Contains(host, "..") { + return "", fmt.Errorf("ожидалось доменное имя длиной до 253 символов") + } + labels := strings.Split(host, ".") + if len(labels) < 2 { + return "", fmt.Errorf("ожидалось доменное имя как ya.ru") + } + for _, label := range labels { + if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' { + return "", fmt.Errorf("некорректная метка домена") + } + for _, ch := range label { + if (ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '-' { + return "", fmt.Errorf("разрешены только латинские буквы, цифры, дефис и точки") + } + } + } + return host, nil +} + +func verifyTURNCertificateChainWithoutHostname(state tls.ConnectionState) error { + if len(state.PeerCertificates) == 0 { + return fmt.Errorf("TURN TLS не прислал сертификат") + } + intermediates := x509.NewCertPool() + for _, cert := range state.PeerCertificates[1:] { + intermediates.AddCert(cert) + } + _, err := state.PeerCertificates[0].Verify(x509.VerifyOptions{ + Intermediates: intermediates, + KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + }) + if err != nil { + return fmt.Errorf("проверка цепочки сертификата TURN TLS: %w", err) + } + return nil +} + +func turnTLSConfig(endpoint turnEndpoint, frontSNI string) *tls.Config { + config := &tls.Config{MinVersion: tls.VersionTLS12} + serverName := endpoint.Host + if frontSNI != "" { + serverName = frontSNI + } + if net.ParseIP(serverName) == nil { + config.ServerName = serverName + } + + // При подмене SNI имя сертификата ожидаемо относится к TURN-узлу, а не к + // домену белого списка. Отключаем только сопоставление имени: публичная CA- + // цепочка всё равно проверяется в VerifyConnection. + if frontSNI != "" && !strings.EqualFold(frontSNI, endpoint.Host) { + config.InsecureSkipVerify = true // проверка перенесена в VerifyConnection + config.VerifyConnection = verifyTURNCertificateChainWithoutHostname + } + return config +} + +func turnPathSNI(endpoint turnEndpoint, frontSNI string, rtMode bool) string { + if endpoint.Transport != turnTransportTLS { + if endpoint.Transport == turnTransportTCP && rtMode { + return "SNI не применяется, первый STUN-запрос разделён для DPI" + } + return "SNI не применяется" + } + if frontSNI != "" { + return "SNI=" + frontSNI + } + if net.ParseIP(endpoint.Host) == nil { + return "SNI=" + endpoint.Host + } + return "без SNI" +} + func openTURNAllocation( ctx context.Context, endpoint turnEndpoint, peer *net.UDPAddr, creds *Credentials, sessionID int, + frontSNI string, + splitTCPFirstWrite bool, ) (*turn.Client, net.PacketConn, error) { turnAddr := endpoint.address() @@ -91,21 +218,21 @@ func openTURNAllocation( dialCtx, cancel := context.WithTimeout(ctx, 6*time.Second) defer cancel() dialer := &net.Dialer{Timeout: 6 * time.Second, KeepAlive: 30 * time.Second} - conn, err := dialer.DialContext(dialCtx, "tcp", turnAddr) + rawConn, err := dialer.DialContext(dialCtx, "tcp", turnAddr) if err != nil { return nil, nil, fmt.Errorf("TURN TCP подключение %s: %w", turnAddr, err) } + var conn net.Conn = rawConn + if splitTCPFirstWrite { + conn = &splitFirstWriteConn{Conn: rawConn, splitAt: 6, delay: 20 * time.Millisecond} + } turnConn = turn.NewSTUNConn(conn) case turnTransportTLS: dialCtx, cancel := context.WithTimeout(ctx, 8*time.Second) defer cancel() - tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12} - if net.ParseIP(endpoint.Host) == nil { - tlsConfig.ServerName = endpoint.Host - } dialer := &tls.Dialer{ NetDialer: &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second}, - Config: tlsConfig, + Config: turnTLSConfig(endpoint, frontSNI), } conn, err := dialer.DialContext(dialCtx, "tcp", turnAddr) if err != nil { @@ -116,6 +243,17 @@ func openTURNAllocation( return nil, nil, fmt.Errorf("неподдерживаемый TURN transport: %s", endpoint.Transport) } + return allocateTURNOnConn(endpoint, peer, creds, turnConn) +} + +func allocateTURNOnConn( + endpoint turnEndpoint, + peer *net.UDPAddr, + creds *Credentials, + turnConn net.PacketConn, +) (*turn.Client, net.PacketConn, error) { + turnAddr := endpoint.address() + // RequestedAddressFamily var addrFamily turn.RequestedAddressFamily if peer.IP.To4() != nil { @@ -146,7 +284,7 @@ func openTURNAllocation( relay, err := tc.Allocate() if err != nil { if isAuthError(err) { - handleAuthError(creds.CacheStreamID) + handleAuthError(creds.CacheStreamID, creds.User, creds.Pass) } errStr := err.Error() if strings.Contains(errStr, "Quota") || strings.Contains(errStr, "486") { @@ -160,21 +298,78 @@ func openTURNAllocation( return tc, relay, nil } +func openTURNAllocationOverMasque( + ctx context.Context, + endpoint turnEndpoint, + peer *net.UDPAddr, + creds *Credentials, + manager *warpMasqueManager, + protocol warpMasqueProtocol, +) (*turn.Client, net.PacketConn, error) { + if endpoint.Transport == turnTransportUDP { + return nil, nil, errors.New("TURN/UDP нельзя передать через TCP-поток CONNECT-IP") + } + + rawConn, err := manager.dialProtocol(ctx, endpoint.address(), protocol) + if err != nil { + return nil, nil, fmt.Errorf("MASQUE %s к %s: %w", protocol, endpoint.address(), err) + } + var conn net.Conn = rawConn + if endpoint.Transport == turnTransportTLS { + tlsConn := tls.Client(rawConn, turnTLSConfig(endpoint, "")) + handshakeCtx, cancel := context.WithTimeout(ctx, 8*time.Second) + err = tlsConn.HandshakeContext(handshakeCtx) + cancel() + if err != nil { + _ = rawConn.Close() + return nil, nil, fmt.Errorf("TURN TLS внутри MASQUE %s к %s: %w", protocol, endpoint.address(), err) + } + conn = tlsConn + } + + return allocateTURNOnConn(endpoint, peer, creds, turn.NewSTUNConn(conn)) +} + func isCredentialTURNError(err error) bool { if err == nil { return false } text := strings.ToLower(err.Error()) - return strings.Contains(text, "turn квота") || - strings.Contains(text, "turn allocate auth") || + return strings.Contains(text, "turn allocate auth") || + strings.Contains(text, "unauthorized") || + strings.Contains(text, "authentication") || + strings.Contains(text, "error 401") || strings.Contains(text, "invalid credential") || strings.Contains(text, "stale nonce") || strings.Contains(text, "allocation mismatch") || - strings.Contains(text, "attribute not found") || + strings.Contains(text, "attribute not found") +} + +func isTURNCapacityError(err error) bool { + if err == nil { + return false + } + text := strings.ToLower(err.Error()) + return strings.Contains(text, "turn квота") || strings.Contains(text, "error 508") || strings.Contains(text, "quota") } +func turnCandidateStages(candidates []turnEndpoint, useMasque bool) (direct, masque, finalUDP []turnEndpoint) { + if !useMasque { + return candidates, nil, nil + } + for _, candidate := range candidates { + if candidate.Transport == turnTransportUDP { + finalUDP = append(finalUDP, candidate) + continue + } + direct = append(direct, candidate) + masque = append(masque, candidate) + } + return direct, masque, finalUDP +} + func RunSession( ctx context.Context, tp *TurnParams, @@ -189,30 +384,42 @@ func RunSession( creds *Credentials, deviceID, password, deviceInfo, transportSession string, stats *Stats, + preferTURNStream bool, ) (bool, error) { configDelivered := false if len(creds.TurnURLs) == 0 { return false, fmt.Errorf("нет TURN URL в учетных данных") } - candidates := sessionTURNCandidates(creds.TurnURLs, sessionID, tp) + candidates := sessionTURNCandidatesWithPreference( + creds.TurnURLs, + sessionID, + tp, + preferTURNStream, + ) if len(candidates) == 0 { return false, fmt.Errorf("нет пригодных TURN URL в учетных данных") } + directCandidates, masqueCandidates, finalUDPCandidates := turnCandidateStages(candidates, tp.Masque != nil) var tc *turn.Client var relay net.PacketConn var selectedEndpoint turnEndpoint + var selectedMasqueProtocol warpMasqueProtocol var lastTURNErr error var err error - for idx, candidate := range candidates { - if idx == 0 { + for idx, candidate := range directCandidates { + if !preferTURNStream && idx == 0 { log.Printf("[СЕССИЯ #%d] TURN %s (%s)", sessionID, candidate.label(), candidate.address()) - } else { + } else if !preferTURNStream { log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s) после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr) + } else if idx == 0 { + log.Printf("[СЕССИЯ #%d] [TURN] Путь %s (%s), %s", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream)) + } else { + log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s), %s, после ошибки: %v", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream), lastTURNErr) } - tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID) + tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream) if err == nil { selectedEndpoint = candidate break @@ -222,6 +429,41 @@ func RunSession( return false, err } } + if relay == nil && tp.Masque != nil { + log.Printf("[СЕССИЯ #%d] [MASQUE] Прямые TCP/TLS-пути «Сети РТ» не сработали; до UDP пробуем WARP CONNECT-IP: %v", sessionID, lastTURNErr) + masqueProtocols: + for _, protocol := range tp.Masque.protocolOrder() { + for _, candidate := range masqueCandidates { + log.Printf("[СЕССИЯ #%d] [MASQUE] Пробуем TURN %s (%s) внутри CONNECT-IP %s", sessionID, candidate.label(), candidate.address(), protocol) + tc, relay, err = openTURNAllocationOverMasque(ctx, candidate, peer, creds, tp.Masque, protocol) + if err == nil { + selectedEndpoint = candidate + selectedMasqueProtocol = protocol + tp.Masque.markPreferred(protocol) + break masqueProtocols + } + lastTURNErr = err + log.Printf("[СЕССИЯ #%d] [MASQUE] %s через %s не сработал: %v", sessionID, candidate.label(), protocol, err) + if isCredentialTURNError(err) { + return false, err + } + } + } + } + if relay == nil && tp.Masque != nil { + for _, candidate := range finalUDPCandidates { + log.Printf("[СЕССИЯ #%d] [TURN] Последний резерв после MASQUE: %s (%s), после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr) + tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream) + if err == nil { + selectedEndpoint = candidate + break + } + lastTURNErr = err + if isCredentialTURNError(err) { + return false, err + } + } + } if lastTURNErr != nil && relay == nil { return false, lastTURNErr } @@ -231,7 +473,11 @@ func RunSession( // Reset error count on successful allocation getStreamCache(creds.CacheStreamID).errorCount.Store(0) - log.Printf("[СЕССИЯ #%d] Relay: %s через TURN %s", sessionID, relay.LocalAddr(), selectedEndpoint.label()) + if selectedMasqueProtocol != "" { + log.Printf("[СЕССИЯ #%d] Relay: %s через TURN %s внутри MASQUE %s ✓", sessionID, relay.LocalAddr(), selectedEndpoint.label(), selectedMasqueProtocol) + } else { + log.Printf("[СЕССИЯ #%d] Relay: %s через TURN %s", sessionID, relay.LocalAddr(), selectedEndpoint.label()) + } // Pipe для DTLS ↔ TURN relay pipeA, pipeB := connutil.AsyncPacketPipe() diff --git a/go_client/session_tls_test.go b/go_client/session_tls_test.go new file mode 100644 index 0000000..a197b5e --- /dev/null +++ b/go_client/session_tls_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "net" + "testing" + "time" +) + +type recordingConn struct { + writes [][]byte +} + +func (conn *recordingConn) Read(_ []byte) (int, error) { return 0, nil } +func (conn *recordingConn) Close() error { return nil } +func (conn *recordingConn) LocalAddr() net.Addr { return nil } +func (conn *recordingConn) RemoteAddr() net.Addr { return nil } +func (conn *recordingConn) SetDeadline(_ time.Time) error { return nil } +func (conn *recordingConn) SetReadDeadline(_ time.Time) error { return nil } +func (conn *recordingConn) SetWriteDeadline(_ time.Time) error { return nil } + +func (conn *recordingConn) Write(payload []byte) (int, error) { + copyOfPayload := append([]byte(nil), payload...) + conn.writes = append(conn.writes, copyOfPayload) + return len(payload), nil +} + +func TestNormalizeTURNFrontSNI(t *testing.T) { + tests := []struct { + input string + want string + ok bool + }{ + {input: " Ya.RU ", want: "ya.ru", ok: true}, + {input: "telemost.yandex.ru", want: "telemost.yandex.ru", ok: true}, + {input: "", want: "", ok: true}, + {input: "ya", ok: false}, + {input: "127.0.0.1", ok: false}, + {input: "я.рф", ok: false}, + {input: "-ya.ru", ok: false}, + {input: "ya..ru", ok: false}, + } + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + got, err := normalizeTURNFrontSNI(tt.input) + if (err == nil) != tt.ok { + t.Fatalf("normalizeTURNFrontSNI(%q) error=%v", tt.input, err) + } + if got != tt.want { + t.Fatalf("normalizeTURNFrontSNI(%q)=%q, want %q", tt.input, got, tt.want) + } + }) + } +} + +func TestTurnTLSConfigUsesFrontSNIWithoutDisablingChainCheck(t *testing.T) { + endpoint := turnEndpoint{Host: "turn.example", Port: "443", Transport: turnTransportTLS} + config := turnTLSConfig(endpoint, "ya.ru") + if config.ServerName != "ya.ru" { + t.Fatalf("ServerName=%q, want ya.ru", config.ServerName) + } + if !config.InsecureSkipVerify || config.VerifyConnection == nil { + t.Fatal("front SNI must replace hostname matching with explicit CA-chain verification") + } + + normal := turnTLSConfig(endpoint, "") + if normal.ServerName != "turn.example" || normal.InsecureSkipVerify || normal.VerifyConnection != nil { + t.Fatalf("normal TLS verification changed unexpectedly: %#v", normal) + } +} + +func TestSplitFirstWriteConnOnlySplitsFirstWrite(t *testing.T) { + underlying := &recordingConn{} + conn := &splitFirstWriteConn{Conn: underlying, splitAt: 6} + + first := []byte("0123456789") + if n, err := conn.Write(first); err != nil || n != len(first) { + t.Fatalf("first Write() = (%d, %v), want (%d, nil)", n, err, len(first)) + } + second := []byte("abcdef") + if n, err := conn.Write(second); err != nil || n != len(second) { + t.Fatalf("second Write() = (%d, %v), want (%d, nil)", n, err, len(second)) + } + + if len(underlying.writes) != 3 { + t.Fatalf("underlying writes=%q, want three writes", underlying.writes) + } + if got := string(underlying.writes[0]); got != "012345" { + t.Fatalf("first fragment=%q, want %q", got, "012345") + } + if got := string(underlying.writes[1]); got != "6789" { + t.Fatalf("second fragment=%q, want %q", got, "6789") + } + if got := string(underlying.writes[2]); got != "abcdef" { + t.Fatalf("subsequent write=%q, want %q", got, "abcdef") + } +} diff --git a/go_client/turn_endpoint.go b/go_client/turn_endpoint.go index 29095d9..727291a 100644 --- a/go_client/turn_endpoint.go +++ b/go_client/turn_endpoint.go @@ -90,6 +90,19 @@ func legacyUDPEndpoint(raw string) (turnEndpoint, error) { return endpoint, nil } +// legacyTCPEndpoint preserves the behaviour of the original vk-turn-proxy +// client: VK may advertise an address as UDP even though the same TURN +// listener also accepts a TCP control connection. +func legacyTCPEndpoint(raw string) (turnEndpoint, error) { + endpoint, err := parseTURNEndpoint(raw) + if err != nil { + return turnEndpoint{}, err + } + endpoint.Transport = turnTransportTCP + endpoint.LegacyUDP = false + return endpoint, nil +} + func splitTURNHostPort(address string, transport turnTransport) (string, string, error) { host, port, err := net.SplitHostPort(address) if err == nil { @@ -135,6 +148,19 @@ func (e turnEndpoint) label() string { } func sessionTURNCandidates(rawURLs []string, sessionID int, tp *TurnParams) []turnEndpoint { + return sessionTURNCandidatesWithPreference(rawURLs, sessionID, tp, false) +} + +// sessionTURNCandidatesWithPreference keeps the historical UDP-first order +// unless the user explicitly enables the restricted-network mode. That mode +// prefers stream transports so a mobile network that silently drops relayed +// UDP is not retried forever. +func sessionTURNCandidatesWithPreference( + rawURLs []string, + sessionID int, + tp *TurnParams, + preferStream bool, +) []turnEndpoint { if len(rawURLs) == 0 { return nil } @@ -165,27 +191,62 @@ func sessionTURNCandidates(rawURLs []string, sessionID int, tp *TurnParams) []tu result = append(result, endpoint) } - if endpoint, err := legacyUDPEndpoint(rawURLs[selectedIndex]); err == nil { - add(endpoint) - } - - for offset := 1; offset < len(rawURLs); offset++ { - idx := (selectedIndex + offset) % len(rawURLs) - if endpoint, err := legacyUDPEndpoint(rawURLs[idx]); err == nil { + addLegacyUDP := func() { + if endpoint, err := legacyUDPEndpoint(rawURLs[selectedIndex]); err == nil { add(endpoint) } + + for offset := 1; offset < len(rawURLs); offset++ { + idx := (selectedIndex + offset) % len(rawURLs) + if endpoint, err := legacyUDPEndpoint(rawURLs[idx]); err == nil { + add(endpoint) + } + } } - for offset := 0; offset < len(rawURLs); offset++ { - idx := (selectedIndex + offset) % len(rawURLs) - endpoint, err := parseTURNEndpoint(rawURLs[idx]) - if err != nil { - continue + addStreamCandidates := func(tlsFirst bool) { + if !tlsFirst { + for offset := 0; offset < len(rawURLs); offset++ { + idx := (selectedIndex + offset) % len(rawURLs) + endpoint, err := parseTURNEndpoint(rawURLs[idx]) + if err != nil || endpoint.Transport == turnTransportUDP { + continue + } + add(endpoint) + } + return } - if endpoint.Transport == turnTransportUDP { - continue + + // A restricted allow-list is most likely to accept the TLS endpoint: + // it uses the real TURN hostname supplied by VK as outer SNI. + for _, transport := range []turnTransport{turnTransportTLS, turnTransportTCP} { + for offset := 0; offset < len(rawURLs); offset++ { + idx := (selectedIndex + offset) % len(rawURLs) + endpoint, err := parseTURNEndpoint(rawURLs[idx]) + if err != nil || endpoint.Transport != transport { + continue + } + add(endpoint) + } } - add(endpoint) + + // The upstream vk-turn-proxy uses TCP to the selected TURN address even + // when VK marks that URL as transport=udp. Keep this compatibility path + // behind stream preference so the normal UDP-first mode is untouched. + for offset := 0; offset < len(rawURLs); offset++ { + idx := (selectedIndex + offset) % len(rawURLs) + if endpoint, err := legacyTCPEndpoint(rawURLs[idx]); err == nil { + add(endpoint) + } + } + } + + if preferStream { + addStreamCandidates(true) + addLegacyUDP() + } else { + addLegacyUDP() + addStreamCandidates(false) } return result diff --git a/go_client/turn_endpoint_test.go b/go_client/turn_endpoint_test.go index 938b1f1..863a3e6 100644 --- a/go_client/turn_endpoint_test.go +++ b/go_client/turn_endpoint_test.go @@ -32,24 +32,78 @@ func TestSessionTURNCandidatesKeepLegacyUDPFirst(t *testing.T) { "turn:turn.example:3478?transport=tcp", } got := sessionTURNCandidates(raw, 0, nil) + want := []struct { + host string + port string + transport turnTransport + legacyUDP bool + }{ + {"turn.example", "443", turnTransportUDP, true}, + {"1.2.3.4", "3478", turnTransportUDP, true}, + {"turn.example", "3478", turnTransportUDP, true}, + {"turn.example", "443", turnTransportTLS, false}, + {"turn.example", "3478", turnTransportTCP, false}, + } + if len(got) != len(want) { + t.Fatalf("normal-mode candidates=%#v, want %d entries", got, len(want)) + } + for index, expected := range want { + actual := got[index] + if actual.Host != expected.host || actual.Port != expected.port || + actual.Transport != expected.transport || actual.LegacyUDP != expected.legacyUDP { + t.Fatalf("normal-mode candidate[%d]=%#v, want %#v", index, actual, expected) + } + } +} + +func TestSessionTURNCandidatesPreferStreamForRtMode(t *testing.T) { + raw := []string{ + "turn:turn.example:443?transport=tcp", + "turn:1.2.3.4:3478?transport=udp", + "turns:turn.example:443?transport=tcp", + } + got := sessionTURNCandidatesWithPreference(raw, 0, nil, true) if len(got) < 3 { t.Fatalf("not enough candidates: %#v", got) } - if got[0].Transport != turnTransportUDP || !got[0].LegacyUDP || got[0].Host != "turn.example" || got[0].Port != "443" { - t.Fatalf("first candidate must preserve old UDP behavior, got %#v", got[0]) + if got[0].Transport != turnTransportTLS || got[0].LegacyUDP { + t.Fatalf("first candidate must be the real TLS transport, got %#v", got[0]) } - foundTLS := false - foundTCP := false - for _, endpoint := range got[1:] { - if endpoint.Transport == turnTransportTLS { - foundTLS = true - } - if endpoint.Transport == turnTransportTCP { - foundTCP = true - } + if got[1].Transport != turnTransportTCP || got[1].LegacyUDP { + t.Fatalf("second candidate must be the real TCP transport, got %#v", got[1]) } - if !foundTLS || !foundTCP { - t.Fatalf("expected TCP/TLS fallbacks, got %#v", got) + if got[len(got)-1].Transport != turnTransportUDP || !got[len(got)-1].LegacyUDP { + t.Fatalf("legacy UDP candidates must remain as a final fallback, got %#v", got) + } +} + +func TestSessionTURNCandidatesPreferStreamSynthesizesTCPFromUDPURL(t *testing.T) { + got := sessionTURNCandidatesWithPreference( + []string{"turn:1.2.3.4:3478?transport=udp"}, + 0, + nil, + true, + ) + if len(got) != 2 { + t.Fatalf("expected synthetic TCP plus UDP fallback, got %#v", got) + } + if got[0].Transport != turnTransportTCP || got[0].Host != "1.2.3.4" || got[0].Port != "3478" { + t.Fatalf("first candidate must be synthetic TCP to the VK TURN address, got %#v", got[0]) + } + if got[1].Transport != turnTransportUDP || !got[1].LegacyUDP { + t.Fatalf("last candidate must preserve UDP fallback, got %#v", got[1]) + } +} + +func TestSessionTURNCandidatesNormalModeDoesNotSynthesizeTCP(t *testing.T) { + got := sessionTURNCandidatesWithPreference( + []string{"turn:1.2.3.4:3478?transport=udp"}, + 0, + nil, + false, + ) + if len(got) != 1 || got[0].Transport != turnTransportUDP || !got[0].LegacyUDP { + t.Fatalf("normal mode must keep the historical UDP-only candidate, got %#v", got) } } diff --git a/gradle.properties b/gradle.properties index 6f2d376..d3a16fb 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,8 @@ -org.gradle.jvmargs=-Xmx8G -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1024m +# Keep enough heap for release builds without allowing Gradle and Kotlin +# daemons to exhaust a typical development machine when the IDE is open. +org.gradle.jvmargs=-Xmx4G -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1024m +org.gradle.daemon.idletimeout=900000 +kotlin.daemon.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=768m android.useAndroidX=true android.nonTransitiveRClass=true org.gradle.caching=true diff --git a/gradlew b/gradlew index f5feea6..5cad163 100755 --- a/gradlew +++ b/gradlew @@ -115,6 +115,22 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac +# Gradle starts another daemon when the compatible daemon is busy. On Linux, +# serialize wrapper invocations for this checkout so an accidental repeated +# command waits instead of running a second memory-heavy Android build. The +# lock descriptor stays in flock's parent process and is not inherited by the +# long-lived Gradle or Kotlin daemons. +if [ "${WDTT_GRADLE_LOCK_HELD:-0}" != 1 ] && + ! "$cygwin" && ! "$msys" && ! "$darwin" && ! "$nonstop" && + command -v flock >/dev/null 2>&1 +then + gradle_lock_dir=$APP_HOME/.gradle + mkdir -p "$gradle_lock_dir" || die "Could not create Gradle lock directory: $gradle_lock_dir" + WDTT_GRADLE_LOCK_HELD=1 + export WDTT_GRADLE_LOCK_HELD + exec flock --exclusive --close "$gradle_lock_dir/wdtt-build.lock" "$0" "$@" +fi + CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar diff --git a/server.go b/server.go index da7b686..e946881 100644 --- a/server.go +++ b/server.go @@ -43,7 +43,7 @@ import ( ) const ( - wdttServerVersion = "13" + wdttServerVersion = "14" wgIfaceName = "wdtt0" wgServerAddr = "10.66.66.1" wgServerCIDR = wgServerAddr + "/24"