Выпуск WDTT Plus v17

This commit is contained in:
Ivan4537 committed 2026-09-04 19:38:52 +03:00
1 parent 4be5f36c88
commit abf0a0f130
33 files changed
+763 -262

No files matched your search

+43 -3
View File
@@ -2,20 +2,22 @@
# ==============================================================================
# WDTT Plus Server — Универсальный установщик для VPS
# Поддержка: Debian 11+, Ubuntu 20.04+, CentOS/RHEL/Fedora/AlmaLinux/Rocky
# Версия: 3.9 | Дата: 2026-09-02
# Версия: 3.10 | Дата: 2026-09-04
# NAT: MASQUERADE через iptables
# WG: порт 56001 (не конфликтует с существующим WG на 51820)
# DTLS: порт 56000
# ==============================================================================
set -euo pipefail
readonly SCRIPT_VERSION="3.9"
readonly SCRIPT_VERSION="3.10"
readonly WDTT_DEPLOY_CONTRACT_VERSION="1"
readonly WDTT_SERVER_VERSION="16"
readonly WDTT_SERVER_VERSION="17"
readonly WDTT_SERVER_BINARY_PATH="/usr/local/bin/wdtt-server"
readonly WDTT_SYSTEMD_UNIT_PATH="/etc/systemd/system/wdtt.service"
readonly WDTT_ANDROID_DEPLOY_MARKER="Managed by WDTT Plus Android deploy"
readonly WDTT_ANDROID_CONTRACT_MARKER="WDTT deploy compatibility: 1"
readonly WDTT_STANDALONE_MARKER="Managed by WDTT Plus standalone server installer"
readonly WDTT_STANDALONE_OWNERSHIP_PATH="/var/lib/wdtt-server-installer/ownership"
readonly LOG_FILE="/var/log/wdtt-install.log"
readonly WG_PORT="${WDTT_WG_PORT:-56001}"
readonly DTLS_PORT="${WDTT_DTLS_PORT:-56000}"
@@ -27,6 +29,7 @@ readonly HANDSHAKE_RATE="${WDTT_HANDSHAKE_RATE:-24}"
readonly MAX_CLIENT_MBPS="${WDTT_MAX_CLIENT_MBPS:-0}"
readonly WG_BACKEND="${WDTT_WG_BACKEND:-auto}"
readonly WDTT_PRESERVE_DATA="${WDTT_PRESERVE_DATA:-0}"
readonly WDTT_INSTALL_MODE="${WDTT_INSTALL_MODE:-}"
readonly WDTT_IFACE="wdtt0"
readonly WDTT_CONFIG_DIR="/etc/wdtt"
readonly WDTT_ACCESS_DB="passwords.json"
@@ -387,6 +390,43 @@ secure_preserved_config() {
validate_deploy_data_mode() {
local database="$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB"
case "$WDTT_INSTALL_MODE" in
fresh)
[ "$WDTT_PRESERVE_DATA" = "0" ] ||
die "Первичная установка несовместима с режимом сохранения"
if [ -e "$WDTT_SYSTEMD_UNIT_PATH" ] || [ -e "$WDTT_SERVER_BINARY_PATH" ] ||
[ -e "$WDTT_CONFIG_DIR" ]; then
die "Первичная установка остановлена: после проверки появились следы WDTT"
fi
;;
preserve)
[ "$WDTT_PRESERVE_DATA" = "1" ] ||
die "Обновление с сохранением запущено без защиты данных"
if [ -f "$WDTT_STANDALONE_OWNERSHIP_PATH" ] &&
grep -Fqx "${WDTT_STANDALONE_MARKER}" "$WDTT_STANDALONE_OWNERSHIP_PATH"; then
die "Обновление остановлено: сервер управляется standalone-инсталлером"
fi
[ -f "$WDTT_SYSTEMD_UNIT_PATH" ] && [ ! -L "$WDTT_SYSTEMD_UNIT_PATH" ] &&
[ -x "$WDTT_SERVER_BINARY_PATH" ] && [ ! -L "$WDTT_SERVER_BINARY_PATH" ] &&
[ -d "$WDTT_CONFIG_DIR" ] && [ ! -L "$WDTT_CONFIG_DIR" ] ||
die "Обновление остановлено: признаки Android-установки изменились после проверки"
if ! grep -Fqx "# ${WDTT_ANDROID_DEPLOY_MARKER}" "$WDTT_SYSTEMD_UNIT_PATH"; then
[ -f "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] &&
[ ! -L "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] &&
grep -Eq '^ExecStart=/usr/local/bin/wdtt-server([[:space:]]|$)' "$WDTT_SYSTEMD_UNIT_PATH" &&
grep -Eq '(^|[[:space:]])-config-dir[[:space:]]+/etc/wdtt([[:space:]]|$)' "$WDTT_SYSTEMD_UNIT_PATH" &&
grep -Fq 'wdtt0' "$WDTT_SYSTEMD_UNIT_PATH" ||
die "Обновление остановлено: не удалось подтвердить старую Android-установку"
fi
;;
reset)
[ "$WDTT_PRESERVE_DATA" = "0" ] ||
die "Полный сброс несовместим с режимом сохранения"
;;
*)
die "Приложение не указало безопасный режим установки"
;;
esac
if [ -e "$database" ] && [ "$WDTT_PRESERVE_DATA" != "1" ]; then
die "Найдена существующая база WDTT. Обновление разрешено только в режиме сохранения; явный сброс должен заранее удалить старую базу после подтверждения в приложении."
fi
@@ -164,7 +164,10 @@ private sealed interface WdttConnectFlow {
val access: RemoteAccessCapability,
val message: String
) : WdttConnectFlow
data class Complete(val message: String) : WdttConnectFlow
data class Complete(
val message: String,
val title: String = "Подключение WDTT Plus",
) : WdttConnectFlow
data class Failed(
val message: String,
val action: RemoteDocumentFailureAction? = null,
@@ -839,7 +842,18 @@ class MainActivity : ComponentActivity() {
}
}
if (shouldRestoreUiAfterBoundUpdate(isBoundUpdate)) {
wdttConnectFlow = null
val profileLabel = vpnProfileDisplayName(
profile,
store.profileNames.first(),
)
val confirmation = boundProfileUpdateConfirmation(
profileLabel = profileLabel,
alreadyApplied = result?.alreadyApplied == true,
)
wdttConnectFlow = WdttConnectFlow.Complete(
message = confirmation.message,
title = confirmation.title,
)
} else if (
existingRemoteProfile &&
store.tunnelProfileSnapshot(profile).vkHashes.isNotBlank()
@@ -2290,7 +2304,15 @@ private fun WdttConnectActivationDialog(
}
},
modifier = Modifier.televisionDialogWidth(television),
title = { Text("Подключение WDTT Plus") },
title = {
Text(
if (flow is WdttConnectFlow.Complete) {
flow.title
} else {
"Подключение WDTT Plus"
}
)
},
text = {
AnimatedContent(
targetState = flow,
@@ -0,0 +1,22 @@
package com.wdtt.plus
internal data class BoundProfileUpdateConfirmation(
val title: String,
val message: String,
)
internal fun boundProfileUpdateConfirmation(
profileLabel: String,
alreadyApplied: Boolean,
): BoundProfileUpdateConfirmation =
if (alreadyApplied) {
BoundProfileUpdateConfirmation(
title = "Профиль уже обновлён",
message = "Актуальные настройки профиля $profileLabel уже сохранены на этом устройстве.",
)
} else {
BoundProfileUpdateConfirmation(
title = "Профиль обновлён",
message = "Новые настройки профиля $profileLabel сохранены. Можно подключаться.",
)
}
@@ -1,7 +1,7 @@
package com.wdtt.plus
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15, 16)
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15, 16, 17)
data class ServerMigrationState(
val pendingLevel: Int,
@@ -2855,6 +2855,44 @@ class SettingsStore(context: Context) {
}
}
/**
* Flushes editable launch options for one exact profile before an access refresh.
* A remotely managed profile keeps its connection endpoint and secret exclusively
* under the atomic remote-document transaction; stale UI state must never write
* those fields back after a server move.
*/
suspend fun saveTunnelOptionsBeforeStart(
profileIndex: Int,
peer: String,
preserveManagedConnection: Boolean,
vkHashes: String,
secondaryVkHash: String,
workersPerHash: Int,
protocol: String,
listenPort: Int,
sni: String = "",
noDns: Boolean = false,
captchaMode: String,
captchaSolveMethod: String,
) {
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
dataStore.edit { prefs ->
val managedNow = prefs[getProfileKey(REMOTE_MANAGED_PROFILE, profile)] == true
if (!(preserveManagedConnection || managedNow)) {
prefs[getProfileKey(PEER, profile)] = peer
}
prefs[getProfileKey(VK_HASHES, profile)] = vkHashes
prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = secondaryVkHash
prefs[getProfileKey(WORKERS_PER_HASH, profile)] = workersPerHash
prefs[getProfileKey(PROTOCOL, profile)] = protocol
prefs[getProfileKey(LISTEN_PORT, profile)] = listenPort
prefs[getProfileKey(SNI, profile)] = sni
prefs[getProfileKey(NO_DNS, profile)] = noDns
prefs[getProfileKey(CAPTCHA_MODE, profile)] = captchaMode
prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] = captchaSolveMethod
}
}
suspend fun applyImportedServerConnection(
profileIndex: Int,
host: String,
@@ -416,6 +416,14 @@ internal fun isExpiredAccessAuthFailure(line: String): Boolean =
internal const val WRAP_HANDSHAKE_RETRY_MESSAGE =
"[WRAP] Отдельные каналы не ответили, выполняется повтор"
internal fun wrapHandshakeTerminalMessage(rtNetwork: Boolean): String =
if (rtNetwork) {
"\uD83C\uDF10 Через сеть РТ не получен ответ WRAP. Обычно сеть не пропустила выбранный TURN/SNI; реже причина в пароле или совместимости WRAP. Воркеры остановлены."
} else {
"\uD83D\uDD0C Сервер не ответил на WRAP. Возможны проблемы с сервером или маршрутом, блокировка UDP/TURN, неверный пароль либо несовместимость WRAP. Воркеры остановлены."
}
internal const val RT_MASQUE_CONFIG_FILE_NAME = "rt-masque-v1.json"
internal fun shouldUseRtMasque(rtNetwork: Boolean, rtMasque: Boolean): Boolean =
@@ -1552,7 +1560,7 @@ object TunnelManager {
if (params.configFirstStart) {
cmd.add("-config-first-start=true")
if (totalWorkers == TUNNEL_WORKERS_PER_GROUP) {
if (shouldUseManagedHashFallback(params.profileMaxWorkers, hashCount)) {
cmd.add("-hash-fallback=true")
}
}
@@ -2517,11 +2525,8 @@ object TunnelManager {
lastActiveAtMs == 0L &&
!isCaptchaInProgress()
) {
val wrapStopMessage = if (currentParams?.rtNetwork == true) {
"\uD83C\uDF10 Через сеть РТ не получен ответ WRAP. Обычно сеть не пропустила выбранный TURN/SNI; реже причина в пароле или совместимости WRAP. Воркеры остановлены."
} else {
"\uD83D\uDD12 Неверный пароль подключения или несовместимый WRAP. Воркеры остановлены."
}
val wrapStopMessage =
wrapHandshakeTerminalMessage(currentParams?.rtNetwork == true)
handleCriticalError(wrapStopMessage)
return@launch
} else if (
@@ -87,6 +87,11 @@ internal fun displayedTunnelProfile(
*/
internal fun shouldUseConfigFirstStart(): Boolean = true
internal fun shouldUseManagedHashFallback(
profileMaxWorkers: Int,
hashCount: Int,
): Boolean = profileMaxWorkers >= TUNNEL_WORKERS_PER_GROUP && hashCount > 1
suspend fun buildTunnelParamsFromSettings(
context: Context,
profileIndex: Int? = null,
@@ -173,8 +178,11 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
}
}
suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? {
val params = buildTunnelParamsFromSettings(context) ?: return null
suspend fun buildTunnelStartIntentFromSettings(
context: Context,
profileIndex: Int? = null,
): Intent? {
val params = buildTunnelParamsFromSettings(context, profileIndex) ?: return null
return Intent(context, TunnelService::class.java).apply {
action = "START"
putExtra("peer", params.peer)
+117 -28
View File
@@ -159,7 +159,8 @@ private const val THREEPROXY_SOURCE_SHA256 =
private const val THREEPROXY_SOURCE_URL =
"https://github.com/3proxy/3proxy/archive/refs/tags/$THREEPROXY_VERSION.tar.gz"
private enum class DeployMode {
internal enum class DeployMode {
FreshInstall,
PreserveData,
ResetAll
}
@@ -479,6 +480,7 @@ private data class ExistingInstallInfo(
val standaloneManaged: Boolean = false,
val androidDeployManaged: Boolean = false,
val legacyAndroidDeployCandidate: Boolean = false,
val incompleteAndroidDeployCandidate: Boolean = false,
val checkError: String? = null,
val comparison: DeployServerComparison? = null
) {
@@ -491,17 +493,20 @@ internal enum class DeploymentOwnership {
StandaloneInstaller,
AndroidDeploy,
LegacyAndroidDeploy,
IncompleteAndroidDeploy,
UnknownExisting
}
internal fun existingInstallOwnershipFromFlags(
standaloneManaged: Boolean,
androidDeployManaged: Boolean,
legacyAndroidDeployCandidate: Boolean
legacyAndroidDeployCandidate: Boolean,
incompleteAndroidDeployCandidate: Boolean = false,
): DeploymentOwnership = when {
standaloneManaged -> DeploymentOwnership.StandaloneInstaller
androidDeployManaged -> DeploymentOwnership.AndroidDeploy
legacyAndroidDeployCandidate -> DeploymentOwnership.LegacyAndroidDeploy
incompleteAndroidDeployCandidate -> DeploymentOwnership.IncompleteAndroidDeploy
else -> DeploymentOwnership.UnknownExisting
}
@@ -516,7 +521,10 @@ internal fun existingInstallAllowsPreservingUpdate(
internal fun existingInstallAllowsReset(
ownership: DeploymentOwnership,
checkSucceeded: Boolean
): Boolean = checkSucceeded && ownership == DeploymentOwnership.AndroidDeploy
): Boolean = checkSucceeded && ownership in setOf(
DeploymentOwnership.AndroidDeploy,
DeploymentOwnership.IncompleteAndroidDeploy,
)
internal data class OutboundProfileForms(
val localProxyPort: String,
@@ -1951,7 +1959,7 @@ fun DeployTab(
pendingDeployRequest = request
existingInstallInfo = info
} else {
launchDeploy(request, DeployMode.PreserveData)
launchDeploy(request, DeployMode.FreshInstall)
}
} catch (e: Exception) {
val friendly = friendlyDeployError(e, "проверка сервера")
@@ -6733,9 +6741,9 @@ private fun serverDiagnosticsErrorReport(
private fun serverProfileDiagnosticItem(profileName: String, profileIndex: Int?): DeviceCheckItem {
val number = profileIndex?.let { (it + 1).coerceAtLeast(1).toString() } ?: "?"
return DeviceCheckItem(
title = "Активный VPN-профиль",
title = "Выбранный профиль",
status = "профиль $number — $profileName",
details = "Диагностика собрана строго из текущего активного профиля приложения: его адреса сервера, логина, SSH-порта и выбранного способа входа.",
details = "Диагностика собрана строго из профиля, выбранного в приложении на момент запуска: его адреса сервера, логина, SSH-порта и способа входа.",
recommendation = "Если нужно проверить другой сервер, сначала переключите VPN-профиль в приложении и запустите диагностику заново.",
severity = DeviceCheckSeverity.Info
)
@@ -10737,7 +10745,11 @@ private suspend fun checkExistingInstall(
active = Regex("^ACTIVE=active$", RegexOption.MULTILINE).containsMatchIn(output),
standaloneManaged = markerValue(output, "WDTT_STANDALONE_MANAGED") == "1",
androidDeployManaged = markerValue(output, "WDTT_ANDROID_DEPLOY_MANAGED") == "1",
legacyAndroidDeployCandidate = markerValue(output, "WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE") == "1"
legacyAndroidDeployCandidate = markerValue(output, "WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE") == "1",
incompleteAndroidDeployCandidate = markerValue(
output,
"WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE"
) == "1"
)
} finally {
try { session?.disconnect() } catch (_: Exception) {}
@@ -10784,6 +10796,20 @@ internal fun standaloneInstallerOwnershipProbeScript(pathPrefix: String = ""): S
else
printf 'WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=0\n'
fi
incomplete_extra=''
if [ -d "${'$'}config" ] && [ ! -L "${'$'}config" ]; then
incomplete_extra="${'$'}(find "${'$'}config" -mindepth 1 -maxdepth 1 ! -path "${'$'}passwords" -print -quit 2>/dev/null || true)"
fi
if [ ! -e "${'$'}ownership" ] && [ ! -e "${'$'}unit" ] && [ ! -e "${'$'}binary" ] &&
[ -d "${'$'}config" ] && [ ! -L "${'$'}config" ] &&
[ -f "${'$'}passwords" ] && [ ! -L "${'$'}passwords" ] && [ -s "${'$'}passwords" ] &&
[ ! -e "${'$'}wg_keys" ] && [ -z "${'$'}incomplete_extra" ] &&
[ "${'$'}(stat -c '%a' "${'$'}config" 2>/dev/null || true)" = "700" ] &&
[ "${'$'}(stat -c '%a' "${'$'}passwords" 2>/dev/null || true)" = "600" ]; then
printf 'WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=1\n'
else
printf 'WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=0\n'
fi
if [ -f "${'$'}unit" ] || [ -f "${'$'}binary" ] || [ -d "${'$'}config" ] ||
[ -f "${'$'}passwords" ] || [ -f "${'$'}wg_keys" ]; then
printf 'WDTT_INSTALL_TRACE=1\n'
@@ -10794,13 +10820,22 @@ internal fun standaloneInstallerOwnershipProbeScript(pathPrefix: String = ""): S
}
internal fun deploymentOwnershipFromProbe(output: String): DeploymentOwnership {
val requiredMarkers = listOf(
"WDTT_STANDALONE_MANAGED",
"WDTT_ANDROID_DEPLOY_MANAGED",
"WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE",
"WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE",
"WDTT_INSTALL_TRACE",
)
if (requiredMarkers.any { markerValue(output, it) !in setOf("0", "1") }) {
throw IllegalStateException("не удалось безопасно проверить владельца установки. Изменяющая операция остановлена.")
}
return when {
markerValue(output, "WDTT_STANDALONE_MANAGED") != "0" &&
markerValue(output, "WDTT_STANDALONE_MANAGED") != "1" ->
throw IllegalStateException("не удалось безопасно проверить владельца установки. Изменяющая операция остановлена.")
markerValue(output, "WDTT_STANDALONE_MANAGED") == "1" -> DeploymentOwnership.StandaloneInstaller
markerValue(output, "WDTT_ANDROID_DEPLOY_MANAGED") == "1" -> DeploymentOwnership.AndroidDeploy
markerValue(output, "WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE") == "1" -> DeploymentOwnership.LegacyAndroidDeploy
markerValue(output, "WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE") == "1" ->
DeploymentOwnership.IncompleteAndroidDeploy
markerValue(output, "WDTT_INSTALL_TRACE") == "0" -> DeploymentOwnership.NoInstall
markerValue(output, "WDTT_INSTALL_TRACE") == "1" -> DeploymentOwnership.UnknownExisting
else -> throw IllegalStateException("не удалось безопасно проверить владельца установки. Изменяющая операция остановлена.")
@@ -10812,23 +10847,44 @@ private fun deploymentOwnership(ssh: SSHClient): DeploymentOwnership {
return deploymentOwnershipFromProbe(output)
}
private fun assertDeploymentMayBeUpdated(ownership: DeploymentOwnership, mode: DeployMode) {
when (ownership) {
DeploymentOwnership.StandaloneInstaller -> throw IllegalStateException(
internal fun assertDeploymentMayBeUpdated(
ownership: DeploymentOwnership,
mode: DeployMode,
) {
when {
ownership == DeploymentOwnership.StandaloneInstaller -> throw IllegalStateException(
"сервер управляется отдельным standalone-инсталлером. Android-приложение не обновляет " +
"и не перезаписывает такую установку; используйте server-installer/install.sh на VPS."
)
DeploymentOwnership.AndroidDeploy, DeploymentOwnership.NoInstall -> Unit
DeploymentOwnership.LegacyAndroidDeploy -> if (mode == DeployMode.ResetAll) {
ownership == DeploymentOwnership.UnknownExisting -> throw IllegalStateException(
"на сервере есть неизвестная установка WDTT без безопасных признаков Android-деплоя. " +
"Изменяющая операция остановлена."
)
mode == DeployMode.FreshInstall && ownership != DeploymentOwnership.NoInstall ->
throw IllegalStateException(
"первичная установка остановлена: на сервере появились следы WDTT. " +
"Повторите проверку и выберите безопасное действие для найденной установки."
)
mode == DeployMode.PreserveData && ownership !in setOf(
DeploymentOwnership.AndroidDeploy,
DeploymentOwnership.LegacyAndroidDeploy,
) -> throw IllegalStateException(
"обновление с сохранением разрешено только для подтверждённой Android-установки."
)
ownership == DeploymentOwnership.LegacyAndroidDeploy && mode == DeployMode.ResetAll -> {
throw IllegalStateException(
"старая Android-установка без метки допускает только обновление с сохранением. " +
"После успешного обновления появится метка, а сброс по-прежнему потребует отдельного подтверждения."
)
}
DeploymentOwnership.UnknownExisting -> throw IllegalStateException(
"на сервере есть неизвестная установка WDTT без безопасных признаков Android-деплоя. " +
"Изменяющая операция остановлена."
)
mode == DeployMode.ResetAll && ownership !in setOf(
DeploymentOwnership.AndroidDeploy,
DeploymentOwnership.IncompleteAndroidDeploy,
) ->
throw IllegalStateException(
"полный сброс разрешён только для установки с подтверждённой меткой Android-деплоя."
)
else -> Unit
}
}
@@ -10841,7 +10897,9 @@ private fun assertAndroidDeployMayManageServer(ssh: SSHClient, operation: String
DeploymentOwnership.LegacyAndroidDeploy -> throw IllegalStateException(
"старая Android-установка без метки не допускает $operation. Сначала выполните обновление с сохранением."
)
DeploymentOwnership.NoInstall, DeploymentOwnership.UnknownExisting -> throw IllegalStateException(
DeploymentOwnership.NoInstall,
DeploymentOwnership.IncompleteAndroidDeploy,
DeploymentOwnership.UnknownExisting -> throw IllegalStateException(
"не удалось безопасно подтвердить, что установка принадлежит Android-деплою. $operation остановлено."
)
}
@@ -13387,12 +13445,19 @@ private suspend fun performDeploy(
if (
mode == DeployMode.PreserveData ||
importPlan != null ||
(mode == DeployMode.ResetAll && ownership == DeploymentOwnership.AndroidDeploy)
(mode == DeployMode.ResetAll && ownership in setOf(
DeploymentOwnership.AndroidDeploy,
DeploymentOwnership.IncompleteAndroidDeploy,
))
) {
onProgress(0.055f, "Проверка сохранённых данных...")
val currentDbJson = readRemotePasswordsJson(ssh)?.also {
validatePasswordsDbForPreserving(JSONObject(it), mainPass)
}
onProgress(0.055f, "Проверка сохранённых данных...")
val currentDbJson = readRemotePasswordsJson(ssh)?.also {
if (ownership == DeploymentOwnership.IncompleteAndroidDeploy) {
validatePasswordsDbStructure(JSONObject(it))
} else {
validatePasswordsDbForPreserving(JSONObject(it), mainPass)
}
}
if (mode == DeployMode.PreserveData && currentDbJson == null) {
throw IllegalStateException(
"обновление с сохранением остановлено: на сервере нет passwords.json; " +
@@ -13437,6 +13502,11 @@ private suspend fun performDeploy(
onProgress(0.08f, "Установка...")
if (mode == DeployMode.ResetAll) {
onProgress(0.075f, "Сброс старых данных...")
val resetOwnership = deploymentOwnership(ssh)
require(resetOwnership == ownership) {
"состояние установки изменилось после проверки; сброс остановлен"
}
assertDeploymentMayBeUpdated(resetOwnership, DeployMode.ResetAll)
ssh.exec(
rootCommand(
"systemctl stop wdtt 2>/dev/null || true; " +
@@ -13478,6 +13548,11 @@ private suspend fun performDeploy(
val output = ssh.exec(
rootCommand(
"env WDTT_DTLS_PORT=$dtlsPort WDTT_WG_PORT=$wgPort WDTT_SSH_PORT=$port " +
"WDTT_INSTALL_MODE=${when (mode) {
DeployMode.FreshInstall -> "fresh"
DeployMode.PreserveData -> "preserve"
DeployMode.ResetAll -> "reset"
}} " +
"WDTT_PRESERVE_DATA=${if (mode == DeployMode.PreserveData) 1 else 0} " +
"${if (stagedDatabaseFile != null) "WDTT_STAGED_DB=/tmp/wdtt-passwords.json.new " else ""}" +
"bash /tmp/deploy.sh"
@@ -15701,7 +15776,8 @@ private fun ExistingInstallDialog(
val ownership = existingInstallOwnershipFromFlags(
standaloneManaged = info.standaloneManaged,
androidDeployManaged = info.androidDeployManaged,
legacyAndroidDeployCandidate = info.legacyAndroidDeployCandidate
legacyAndroidDeployCandidate = info.legacyAndroidDeployCandidate,
incompleteAndroidDeployCandidate = info.incompleteAndroidDeployCandidate,
)
val preservingUpdateAllowed = existingInstallAllowsPreservingUpdate(
ownership = ownership,
@@ -15795,6 +15871,12 @@ private fun ExistingInstallDialog(
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary
)
} else if (ownership == DeploymentOwnership.IncompleteAndroidDeploy) {
Text(
"Найден точный остаток незавершённой Android-установки: защищённая база есть, но служба, бинарник и WireGuard-ключи не были созданы. Обновление с сохранением недоступно; можно только явно начать установку с нуля.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary
)
} else if (info.hasAnyTrace) {
Text(
"Установка без подтверждённых признаков Android-деплоя. Чтобы не изменить чужой сервер, обновление, импорт, удаление и сброс заблокированы.",
@@ -15864,6 +15946,8 @@ private fun ExistingInstallDialog(
"С сохранением данных: обновится бинарник, серверные настройки будут взяты из приложения, а клиентские пароли, привязки устройств, история и ключи сохранятся. Перед изменением создаётся страховочная копия.\n\nЭто одноразовый путь миграции старого Android-деплоя. Сброс, удаление и импорт будут доступны только после успешного обновления и появления метки."
} else if (ownership == DeploymentOwnership.AndroidDeploy) {
"С сохранением данных: обновится бинарник, серверные настройки будут взяты из приложения, а клиентские пароли, привязки устройств, история и ключи сохранятся. Перед изменением создаётся страховочная копия.\n\nС нуля: данные WDTT Plus на сервере будут удалены, все выданные ссылки и привязки пропадут; затем сервер получит текущие поля приложения."
} else if (ownership == DeploymentOwnership.IncompleteAndroidDeploy) {
"Незавершённая установка не содержит работающего сервера. «Начать с нуля» сначала проверит базу и подготовит транзакционный откат, а затем заново установит сервер. Любые другие неизвестные следы по-прежнему блокируются."
} else {
"Владелец установки не подтверждён. Обновление, импорт, сброс и удаление заблокированы до успешной безопасной проверки."
},
@@ -15923,6 +16007,7 @@ private fun ExistingInstallDialog(
}
if (showResetConfirmation) {
ServerResetConfirmDialog(
incompleteInstall = ownership == DeploymentOwnership.IncompleteAndroidDeploy,
onDismiss = { showResetConfirmation = false },
onConfirm = {
showResetConfirmation = false
@@ -15935,6 +16020,7 @@ private fun ExistingInstallDialog(
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ServerResetConfirmDialog(
incompleteInstall: Boolean = false,
onDismiss: () -> Unit,
onConfirm: () -> Unit
) {
@@ -15953,8 +16039,11 @@ private fun ServerResetConfirmDialog(
"Затем сервер будет заново установлен из текущих полей приложения."
)
Text(
"Перед удалением приложение создаст проверенную страховочную копию. " +
"Для запуска непрерывно удерживайте кнопку 3 секунды.",
(if (incompleteInstall) {
"База будет проверена и сохранена для отката, если новая установка не запустится. "
} else {
"Перед удалением приложение создаст проверенную страховочную копию. "
}) + "Для запуска непрерывно удерживайте кнопку 3 секунды.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
+20 -11
View File
@@ -127,6 +127,7 @@ import com.wdtt.plus.SleepBatteryRuntimeState
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.TrustedWifiManager
import com.wdtt.plus.decodeStoredVpnPackages
import com.wdtt.plus.displayedTunnelProfile
import com.wdtt.plus.trustedWifiAccessProblem
import com.wdtt.plus.sleepBatteryModeItem
import com.wdtt.plus.trustedWifiModeItem
@@ -369,9 +370,15 @@ fun InfoTab(
)
val selectedProfile = runCatching { settingsStore.activeProfile.first() }.getOrDefault(0)
val savedTunnelProfile = runCatching { settingsStore.activeTunnelProfile.first() }.getOrNull()
val diagnosticProfile = TunnelManager.activeTunnelProfile.value
?: savedTunnelProfile
?: selectedProfile
val trustedWifiRuntime = TrustedWifiManager.state.value
val trustedWifiWaiting = trustedWifiRuntime.waiting ||
runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false)
val diagnosticProfile = displayedTunnelProfile(
selectedProfile = selectedProfile,
activeTunnelProfile = TunnelManager.activeTunnelProfile.value ?: savedTunnelProfile,
running = TunnelManager.running.value,
trustedWifiWaiting = trustedWifiWaiting,
)
val profileNames = runCatching { settingsStore.profileNames.first() }.getOrDefault(emptyList())
val diagnosticProfileName = vpnProfileDisplayName(diagnosticProfile, profileNames)
val tunnelProfile = runCatching {
@@ -394,9 +401,6 @@ fun InfoTab(
}
val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrDefault(false)
val trustedWifiSsids = runCatching { settingsStore.trustedWifiSsids.first() }.getOrDefault(emptyList())
val trustedWifiRuntime = TrustedWifiManager.state.value
val trustedWifiWaiting = trustedWifiRuntime.waiting ||
runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false)
val trustedWifiWaitingSsid = trustedWifiRuntime.ssid.ifBlank {
runCatching { settingsStore.trustedWifiWaitingSsid.first() }.getOrDefault("")
}
@@ -2175,9 +2179,16 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
val selectedProfileIndex = runCatching { settingsStore.activeProfile.first() }.getOrNull()
val savedTunnelProfileIndex = runCatching { settingsStore.activeTunnelProfile.first() }.getOrNull()
val diagnosticProfileIndex = TunnelManager.activeTunnelProfile.value
?: savedTunnelProfileIndex
?: selectedProfileIndex
val trustedWifiWaiting = TrustedWifiManager.state.value.waiting ||
runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false)
val diagnosticProfileIndex = selectedProfileIndex?.let { selected ->
displayedTunnelProfile(
selectedProfile = selected,
activeTunnelProfile = TunnelManager.activeTunnelProfile.value ?: savedTunnelProfileIndex,
running = TunnelManager.running.value,
trustedWifiWaiting = trustedWifiWaiting,
)
}
val activeProfile = diagnosticProfileIndex?.plus(1)
val routingSettings = diagnosticProfileIndex?.let { profile ->
runCatching { settingsStore.vpnRoutingSettingsForProfile(profile) }.getOrNull()
@@ -2221,8 +2232,6 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
val loggingEnabled = runCatching { settingsStore.loggingEnabled.first() }.getOrNull()
val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrNull()
val trustedWifiCount = runCatching { settingsStore.trustedWifiSsids.first().size }.getOrNull()
val trustedWifiWaiting = TrustedWifiManager.state.value.waiting ||
runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false)
val sleepBatteryEnabled = runCatching { settingsStore.pauseVpnDuringSleep.first() }.getOrNull()
val sleepBatteryPauseDelay = runCatching { settingsStore.pauseVpnDuringSleepDelayMinutes.first() }.getOrNull()
val sleepBatteryMode = runCatching { settingsStore.sleepBatteryMode.first() }.getOrNull()
@@ -112,7 +112,6 @@ import com.wdtt.plus.DEFAULT_VK_CLIENT_IDS
import com.wdtt.plus.DEFAULT_RT_TURN_SNI
import com.wdtt.plus.ManlCaptchaWebViewManager
import com.wdtt.plus.MainActivity
import com.wdtt.plus.CONFIG_FIRST_START_EXTRA
import com.wdtt.plus.NativeClientStartupSecrets
import com.wdtt.plus.RemoteContinuation
import com.wdtt.plus.RemoteContinuationLauncher
@@ -128,12 +127,11 @@ import com.wdtt.plus.TunnelService
import com.wdtt.plus.TunnelStopCoordinator
import com.wdtt.plus.TunnelStopResult
import com.wdtt.plus.TunnelTransition
import com.wdtt.plus.TUNNEL_PROFILE_INDEX_EXTRA
import com.wdtt.plus.VpnDnsSettingsSnapshot
import com.wdtt.plus.buildTunnelStartIntentFromSettings
import com.wdtt.plus.normalizeTunnelWorkerCount
import com.wdtt.plus.normalizeRtTurnSni
import com.wdtt.plus.nativeClientStartupConfigLine
import com.wdtt.plus.shouldUseConfigFirstStart
import com.wdtt.plus.TrustedWifiManager
import com.wdtt.plus.VkJoinLink
import com.wdtt.plus.WDTTColors
@@ -621,76 +619,33 @@ fun SettingsTabContent(
val showManualConnectionFields = false
val effectiveServerDtlsPort = if (manualPortsEnabled) serverDtlsPortInput.toIntOrNull()?.coerceIn(1, 65535) ?: 56000 else 56000
val effectiveLocalPort = if (manualPortsEnabled) portInput.toIntOrNull()?.coerceIn(1, 65535) ?: 9000 else 9000
var pendingStartAfterVpnPermission by remember { mutableStateOf(false) }
var pendingStartProfileAfterVpnPermission by remember { mutableStateOf<Int?>(null) }
fun startTunnelService() {
val effectiveCaptchaMode = if (autoCaptchaEnabled) "auto" else "wv"
val effectiveCaptchaSolveMethod = if (autoCaptchaEnabled) "auto" else "manual"
val normalizedWorkers = normalizeTunnelWorkerCount(workersInput.toInt(), profileMaxWorkers)
saveJob?.cancel()
fun startTunnelService(profileIndex: Int) {
scope.launch {
settingsStore.save(
peerInput, hashSlotsForStorage, "",
normalizedWorkers, "udp", effectiveLocalPort, sniInput, false
)
settingsStore.saveCaptchaMode(effectiveCaptchaMode)
settingsStore.saveCaptchaSolveMethod(effectiveCaptchaSolveMethod)
}
var finalPeer = "$peerInput:$effectiveServerDtlsPort"
var finalHashes = combinedHashes
var finalLocalPort = effectiveLocalPort
var finalPassword = savedConnectionPassword
if (wdttLinkMode) {
if (parsedWdttLink != null) {
finalPeer = "${parsedWdttLink.host}:${parsedWdttLink.dtlsPort}"
finalLocalPort = parsedWdttLink.localPort
finalPassword = parsedWdttLink.password
finalHashes = parsedWdttLink.hashes
val intent = buildTunnelStartIntentFromSettings(context, profileIndex)
if (intent == null) {
TunnelManager.reportConnectionIssue(
"Профиль заполнен не полностью",
"Проверьте адрес, пароль подключения и VK-хеши."
)
TunnelManager.clearTransition()
Toast.makeText(context, "Проверьте настройки профиля", Toast.LENGTH_LONG).show()
return@launch
}
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent)
else context.startService(intent)
}
val intent = Intent(context, TunnelService::class.java).apply {
action = "START"
putExtra("peer", finalPeer)
putExtra("vk_hashes", finalHashes)
putExtra("secondary_vk_hash", "")
putExtra("workers_per_hash", normalizedWorkers)
putExtra("port", finalLocalPort)
putExtra("sni", sniInput)
putExtra("connection_password", finalPassword)
putExtra("vkcalls_preflight", vkCallsPreflight)
putExtra("rt_network", rtNetwork)
putExtra("rt_masque", rtMasque)
putExtra("rt_masque_server_bootstrap", effectiveRtMasqueServerBootstrap)
putExtra("rt_turn_sni", rtTurnSniInput)
putExtra("captcha_mode", effectiveCaptchaMode)
putExtra("captcha_solve_method", effectiveCaptchaSolveMethod)
putExtra("fingerprint", activeFingerprint)
putExtra("client_ids", activeClientIds)
putExtra("custom_vk_credentials_enabled", customVkCredentialsEnabled)
putExtra("custom_vk_client_id", customVkClientId)
putExtra("custom_vk_client_secret", customVkClientSecret)
putExtra("profile_max_workers", profileMaxWorkers)
putExtra(
CONFIG_FIRST_START_EXTRA,
shouldUseConfigFirstStart(),
)
putExtra(TUNNEL_PROFILE_INDEX_EXTRA, activeProfile)
}
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent)
else context.startService(intent)
}
val vpnPermissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (pendingStartAfterVpnPermission) {
pendingStartAfterVpnPermission = false
pendingStartProfileAfterVpnPermission?.let { profileIndex ->
pendingStartProfileAfterVpnPermission = null
if (VpnService.prepare(context) == null) {
TunnelManager.clearConnectionIssue()
startTunnelService()
startTunnelService(profileIndex)
} else {
TunnelManager.reportConnectionIssue(
"VPN-разрешение не выдано",
@@ -702,14 +657,14 @@ fun SettingsTabContent(
}
}
fun requestVpnAndStart() {
fun requestVpnAndStart(profileIndex: Int) {
val vpnIntent = VpnService.prepare(context)
if (vpnIntent != null) {
pendingStartAfterVpnPermission = true
pendingStartProfileAfterVpnPermission = profileIndex
vpnPermissionLauncher.launch(vpnIntent)
} else {
TunnelManager.clearConnectionIssue()
startTunnelService()
startTunnelService(profileIndex)
}
}
@@ -717,13 +672,35 @@ fun SettingsTabContent(
TunnelManager.noteStartRequested()
scope.launch {
try {
val requestedProfile = activeProfile
val effectiveCaptchaMode = if (autoCaptchaEnabled) "auto" else "wv"
val effectiveCaptchaSolveMethod = if (autoCaptchaEnabled) "auto" else "manual"
val normalizedWorkers = normalizeTunnelWorkerCount(
workersInput.toInt(),
profileMaxWorkers,
)
saveJob?.cancel()
settingsStore.saveTunnelOptionsBeforeStart(
profileIndex = requestedProfile,
peer = peerInput,
preserveManagedConnection = remoteManagedProfile,
vkHashes = hashSlotsForStorage,
secondaryVkHash = "",
workersPerHash = normalizedWorkers,
protocol = "udp",
listenPort = effectiveLocalPort,
sni = sniInput,
noDns = false,
captchaMode = effectiveCaptchaMode,
captchaSolveMethod = effectiveCaptchaSolveMethod,
)
when (
val decision = AccessLifecycleCoordinator.prepareStart(
context,
activeProfile,
requestedProfile,
)
) {
AccessStartDecision.Allowed -> requestVpnAndStart()
AccessStartDecision.Allowed -> requestVpnAndStart(requestedProfile)
is AccessStartDecision.Denied -> {
TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS)
TunnelManager.clearTransition()