Release WDTT Plus v9

This commit is contained in:
Ivan4537 committed 2026-07-07 00:34:24 +03:00
1 parent 24d4157e99
commit 3efd691ae2
15 files changed
+2952 -330

No files matched your search

+9
View File
@@ -2,6 +2,15 @@
Здесь фиксируются заметные пользовательские изменения WDTT Plus. Здесь фиксируются заметные пользовательские изменения WDTT Plus.
## v9 — 06.07.2026
### Сервер и SSH
- Деплой и серверные действия поддерживают два явных способа SSH-входа: пароль или приватный ключ, отдельно для основного и дополнительного VPS.
- Приватный ключ можно вставить, загрузить из файла или буфера обмена, проверить до сохранения и хранить зашифрованно только на устройстве; в перенос настроек и на сервер он не включается.
- Установка, подключение без установки, клиенты, перенос сервера и выходной IP используют выбранный способ SSH-входа единообразно.
- Добавлена безопасная диагностика сервера из вкладки «Деплой»: отчёт собирается для активного VPN-профиля, учитывает разные Linux-системы и не включает пароли, ключи, токены или WireGuard-секреты.
## v8 — 06.07.2026 ## v8 — 06.07.2026
### Обновления ### Обновления
+1
View File
@@ -68,6 +68,7 @@
- **WRAP без захардкоженного ключа:** внешний RTP AEAD/ChaCha20-Poly1305 слой выводится из пароля подключения через HKDF. Один пароль — один WRAP-ключ, ключ не хранится в APK. - **WRAP без захардкоженного ключа:** внешний RTP AEAD/ChaCha20-Poly1305 слой выводится из пароля подключения через HKDF. Один пароль — один WRAP-ключ, ключ не хранится в APK.
- **RTP AEAD обфускация:** транспорт маскируется под RTP/WebRTC аудиотрафик с OPUS payload type, а полезная нагрузка шифруется AEAD-слоем поверх DTLS/WireGuard. - **RTP AEAD обфускация:** транспорт маскируется под RTP/WebRTC аудиотрафик с OPUS payload type, а полезная нагрузка шифруется AEAD-слоем поверх DTLS/WireGuard.
- **Деплой с телефона:** вкладка **«Деплой»** подключается к серверу по SSH, загружает `wdtt-server`, создаёт `systemd`-сервис, включает NAT/firewall и открывает рабочие UDP-порты. - **Деплой с телефона:** вкладка **«Деплой»** подключается к серверу по SSH, загружает `wdtt-server`, создаёт `systemd`-сервис, включает NAT/firewall и открывает рабочие UDP-порты.
- **SSH по паролю или ключу:** установка, подключение без установки, управление клиентами, перенос сервера и инструменты выходного IP работают как с SSH-паролем, так и с приватным ключом OpenSSH/PEM. Способ входа выбирается явно; в режиме ключа пароль можно оставить для `sudo`, если он требуется сервером. Ключ можно вставить, прочитать из файла или буфера обмена и проверить перед сохранением. Основной и дополнительный VPS хранят свои ключи отдельно в защищённом хранилище Android; ключи не отправляются на сервер и не входят в перенос настроек администратора.
- **Подключение к готовому серверу:** если сервер уже установлен, приложение проверяет SSH-доступ и главный пароль, показывает отличия и после подтверждения восстанавливает локальные поля. Если серверный профиль владельца был сохранён из переименованного VPN-профиля, это название также вернётся в приложение; стандартные VPN 1/2/3 локальное имя не затирают. Этот режим работает только от сервера к приложению и ничего не записывает на сервер. - **Подключение к готовому серверу:** если сервер уже установлен, приложение проверяет SSH-доступ и главный пароль, показывает отличия и после подтверждения восстанавливает локальные поля. Если серверный профиль владельца был сохранён из переименованного VPN-профиля, это название также вернётся в приложение; стандартные VPN 1/2/3 локальное имя не затирают. Этот режим работает только от сервера к приложению и ничего не записывает на сервер.
- **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит пользовательских паролей, 16-символьную генерацию, ручное задание пароля с проверками, привязку к устройству и срок действия. Клиентов можно создавать, импортировать, экспортировать, отключать, продлевать, отвязывать, удалять и менять им пароль из приложения или Telegram-бота. - **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит пользовательских паролей, 16-символьную генерацию, ручное задание пароля с проверками, привязку к устройству и срок действия. Клиентов можно создавать, импортировать, экспортировать, отключать, продлевать, отвязывать, удалять и менять им пароль из приложения или Telegram-бота.
- **Горячее обновление WRAP-ключей:** создание, удаление и истечение паролей обновляют набор WRAP-ключей на сервере без перезапуска ядра. - **Горячее обновление WRAP-ключей:** создание, удаление и истечение паролей обновляют набор WRAP-ключей на сервере без перезапуска ядра.
+2 -2
View File
@@ -5,7 +5,7 @@ plugins {
id("org.jetbrains.kotlin.plugin.compose") id("org.jetbrains.kotlin.plugin.compose")
} }
val appVersionName = "8" val appVersionName = "9"
val releaseApkBaseName = "WDTT-Plus" val releaseApkBaseName = "WDTT-Plus"
val localProperties = Properties() val localProperties = Properties()
@@ -22,7 +22,7 @@ android {
applicationId = "com.wdtt.plus" applicationId = "com.wdtt.plus"
minSdk = 28 minSdk = 28
targetSdk = 35 targetSdk = 35
versionCode = 8 versionCode = 9
versionName = appVersionName versionName = appVersionName
buildConfigField("String", "MOD_RELEASE_DATE", "\"06.07.2026\"") buildConfigField("String", "MOD_RELEASE_DATE", "\"06.07.2026\"")
+83 -79
View File
@@ -50,9 +50,11 @@ import androidx.compose.material.icons.outlined.VpnKey
import androidx.compose.material3.* import androidx.compose.material3.*
import androidx.compose.runtime.* import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.Shape
@@ -69,6 +71,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogProperties
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle
@@ -656,14 +659,24 @@ fun MainScreen(
val lifecycleOwner = LocalLifecycleOwner.current val lifecycleOwner = LocalLifecycleOwner.current
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val updateCheckMutex = remember { Mutex() } val updateCheckMutex = remember { Mutex() }
val settingsReady by settingsStore.settingsReady.collectAsStateWithLifecycle(initialValue = false)
if (!settingsReady) {
Box(modifier = Modifier.fillMaxSize()) {
AppBackdrop(modifier = Modifier.matchParentSize())
}
return
}
val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0) val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0)
val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList())
val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false) val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false)
val migrationDeployHost by settingsStore.deployIp.collectAsStateWithLifecycle(initialValue = "")
val migrationSshPassword by settingsStore.deployPassword.collectAsStateWithLifecycle(initialValue = "")
val migrationSshPrivateKey by settingsStore.deploySshPrivateKey.collectAsStateWithLifecycle(initialValue = "")
val migrationSshAuthMode by settingsStore.deploySshAuthMode.collectAsStateWithLifecycle(initialValue = "password")
val migrationMainPassword by settingsStore.deployMainPassword.collectAsStateWithLifecycle(initialValue = "")
val interfaceRole by settingsStore.interfaceRole.collectAsStateWithLifecycle(initialValue = "") val interfaceRole by settingsStore.interfaceRole.collectAsStateWithLifecycle(initialValue = "")
val permissionOnboardingComplete by settingsStore.permissionOnboardingComplete.collectAsStateWithLifecycle(initialValue = false) val permissionOnboardingComplete by settingsStore.permissionOnboardingComplete.collectAsStateWithLifecycle(initialValue = false)
val migrationNoticeV2Shown by settingsStore.migrationNoticeV2Shown.collectAsStateWithLifecycle(initialValue = true) val serverMigrationState by settingsStore.serverMigrationState.collectAsStateWithLifecycle(initialValue = null)
val migrationNoticeV3Shown by settingsStore.migrationNoticeV3Shown.collectAsStateWithLifecycle(initialValue = true)
val migrationNoticeV5Shown by settingsStore.migrationNoticeV5Shown.collectAsStateWithLifecycle(initialValue = true)
val deviceCompatibilityCheckComplete by settingsStore.deviceCompatibilityCheckComplete.collectAsStateWithLifecycle( val deviceCompatibilityCheckComplete by settingsStore.deviceCompatibilityCheckComplete.collectAsStateWithLifecycle(
initialValue = true initialValue = true
) )
@@ -675,6 +688,12 @@ fun MainScreen(
} }
}.getOrDefault(false) }.getOrDefault(false)
} }
LaunchedEffect(settingsStore, isUpdatedInstall) {
settingsStore.initializeServerMigrationState(
currentVersionCode = BuildConfig.VERSION_CODE,
isUpdatedInstall = isUpdatedInstall
)
}
var selectedTab by rememberSaveable { mutableIntStateOf(0) } var selectedTab by rememberSaveable { mutableIntStateOf(0) }
val tunnelScrollPosition = rememberSaveable { mutableIntStateOf(0) } val tunnelScrollPosition = rememberSaveable { mutableIntStateOf(0) }
val deployScrollPosition = rememberSaveable { mutableIntStateOf(0) } val deployScrollPosition = rememberSaveable { mutableIntStateOf(0) }
@@ -815,6 +834,7 @@ fun MainScreen(
} }
val actionsExpanded = rememberSaveable { mutableStateOf(false) } val actionsExpanded = rememberSaveable { mutableStateOf(false) }
val projectExpanded = rememberSaveable { mutableStateOf(false) } val projectExpanded = rememberSaveable { mutableStateOf(false) }
val tabStateHolder = rememberSaveableStateHolder()
@@ -1010,8 +1030,24 @@ fun MainScreen(
} }
} }
) { ) {
val deployVisible = selectedTab == 1 && !wdttLinkMode
val deployAvailable = activeNavItems.any { it.id == 1 } && !wdttLinkMode
if (deployAvailable) {
tabStateHolder.SaveableStateProvider("deploy_persistent") {
DeployTab(
scrollPosition = deployScrollPosition,
visible = deployVisible,
modifier = Modifier
.fillMaxSize()
.padding(bottom = navOverlayReserve)
.graphicsLayer { alpha = if (deployVisible) 1f else 0f }
.zIndex(if (deployVisible) 1f else -1f)
)
}
}
AnimatedContent( AnimatedContent(
targetState = selectedTab, targetState = if (deployVisible) -1 else selectedTab,
transitionSpec = { transitionSpec = {
fadeIn(tween(300)) togetherWith fadeOut(tween(225)) fadeIn(tween(300)) togetherWith fadeOut(tween(225))
}, },
@@ -1020,9 +1056,11 @@ fun MainScreen(
.padding(bottom = navOverlayReserve), .padding(bottom = navOverlayReserve),
label = "tab_content" label = "tab_content"
) { tab -> ) { tab ->
tabStateHolder.SaveableStateProvider(tab) {
when (tab) { when (tab) {
-1 -> Spacer(modifier = Modifier.fillMaxSize())
0 -> SettingsTab(scrollPosition = tunnelScrollPosition) 0 -> SettingsTab(scrollPosition = tunnelScrollPosition)
1 -> if (!wdttLinkMode) DeployTab(scrollPosition = deployScrollPosition) else Spacer(modifier = Modifier.fillMaxSize()) 1 -> Spacer(modifier = Modifier.fillMaxSize())
2 -> ExceptionsTab( 2 -> ExceptionsTab(
firstVisibleItemIndex = exceptionsFirstVisibleItemIndex, firstVisibleItemIndex = exceptionsFirstVisibleItemIndex,
firstVisibleItemScrollOffset = exceptionsFirstVisibleItemScrollOffset firstVisibleItemScrollOffset = exceptionsFirstVisibleItemScrollOffset
@@ -1038,6 +1076,7 @@ fun MainScreen(
) )
} }
} }
}
ProxyNavigationBar( ProxyNavigationBar(
navItems = activeNavItems, navItems = activeNavItems,
@@ -1088,75 +1127,20 @@ fun MainScreen(
) )
} }
val migrationNotice = serverMigrationState
val activeProfileManagesServer = hasManagedServerCredentials(
host = migrationDeployHost,
sshAuthMode = migrationSshAuthMode,
sshPassword = migrationSshPassword,
mainPassword = migrationMainPassword,
sshPrivateKey = migrationSshPrivateKey
)
if ( if (
BuildConfig.VERSION_CODE == 2 &&
isAdminInterface && isAdminInterface &&
isUpdatedInstall && activeProfileManagesServer &&
!migrationNoticeV2Shown migrationNotice?.noticeRequired == true &&
) { pendingUpdateCandidate == null &&
AlertDialog( startupDeviceReport == null
onDismissRequest = {},
properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false
),
title = { Text("Требуется обновление сервера") },
text = {
Text(
"Это крупное обновление WDTT Plus. Для корректной работы новых функций необходимо выполнить установку сервера во вкладке «Деплой».\n\n" +
"Выберите установку с сохранением данных. Настройки, клиенты и выданные доступы сохранятся — будет обновлена только серверная часть.\n\n" +
"Установку с нуля выполнять не нужно."
)
},
confirmButton = {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Button(
onClick = { scope.launch { settingsStore.saveMigrationNoticeV2Shown() } }
) {
Text("Хорошо")
}
}
}
)
}
if (
BuildConfig.VERSION_CODE == 3 &&
isAdminInterface &&
isUpdatedInstall &&
!migrationNoticeV3Shown
) {
AlertDialog(
onDismissRequest = {},
properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false
),
title = { Text("Требуется обновление сервера") },
text = {
Text(
"Для корректной работы новых функций необходимо обновить установку серверной части во вкладке «Деплой».\n\n" +
"Выберите установку с сохранением данных. Настройки, клиенты и выданные доступы сохранятся — будет обновлена только серверная часть.\n\n" +
"Установку с нуля выполнять не нужно."
)
},
confirmButton = {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Button(
onClick = { scope.launch { settingsStore.saveMigrationNoticeV3Shown() } }
) {
Text("Хорошо")
}
}
}
)
}
if (
BuildConfig.VERSION_CODE == 5 &&
isAdminInterface &&
isUpdatedInstall &&
!migrationNoticeV5Shown
) { ) {
AlertDialog( AlertDialog(
onDismissRequest = {}, onDismissRequest = {},
@@ -1166,20 +1150,40 @@ fun MainScreen(
), ),
title = { Text("Обновите серверную часть") }, title = { Text("Обновите серверную часть") },
text = { text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text( Text(
"Чтобы управление выходным IP, бесплатным WARP и новыми проверками корректно работало в приложении и Telegram-боте, выполните установку сервера во вкладке «Деплой».\n\n" + "В новых версиях WDTT Plus была изменена серверная часть. Для корректной работы приложения с сервером выполните установку сервера с сохранением данных во вкладке «Деплой».\n\n" +
"Выберите установку с сохранением данных. Клиенты, доступы и настройки сохранятся.\n\n" + "Клиенты, выданные доступы и настройки сохранятся. Установку с нуля выполнять не нужно."
"Установку с нуля выполнять не нужно."
) )
Text(
"После успешной установки приложение отметит обновление для выбранного VPN-профиля.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}, },
confirmButton = { confirmButton = {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Button( Button(
onClick = { scope.launch { settingsStore.saveMigrationNoticeV5Shown() } } onClick = {
) { scope.launch {
Text("Хорошо") settingsStore.acknowledgeServerMigrationNotice(migrationNotice.pendingLevel)
selectedTab = 1
} }
} }
) {
Text("Перейти в Деплой")
}
},
dismissButton = {
TextButton(
onClick = {
scope.launch {
settingsStore.acknowledgeServerMigrationNotice(migrationNotice.pendingLevel)
}
}
) {
Text("Позже")
}
} }
) )
} }
@@ -1,19 +1,20 @@
package com.wdtt.plus package com.wdtt.plus
import com.jcraft.jsch.ChannelExec import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session import com.jcraft.jsch.Session
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.json.JSONObject import org.json.JSONObject
import java.util.Properties
data class ServerAdminTarget( data class ServerAdminTarget(
val host: String, val host: String,
val user: String, val user: String,
val sshPassword: String, val sshPassword: String,
val sshPort: Int, val sshPort: Int,
val mainPassword: String val mainPassword: String,
val sshPrivateKey: String = "",
val sshKeyPassphrase: String = "",
val allowPasswordAuthentication: Boolean
) )
data class ServerAdminProfileInfo( data class ServerAdminProfileInfo(
@@ -486,17 +487,17 @@ object ServerAdminClient {
) )
private fun createSession(target: ServerAdminTarget): Session { private fun createSession(target: ServerAdminTarget): Session {
val session = JSch().getSession(target.user.ifBlank { "root" }, target.host, target.sshPort) return createSshSession(
session.setPassword(target.sshPassword) host = target.host,
session.setConfig(Properties().apply { user = target.user,
put("StrictHostKeyChecking", "no") credentials = SshCredentials(
put("ServerAliveInterval", "10") password = target.sshPassword,
put("ServerAliveCountMax", "6") privateKey = target.sshPrivateKey,
put("ConnectTimeout", "15000") privateKeyPassphrase = target.sshKeyPassphrase,
put("PreferredAuthentications", "password,keyboard-interactive") allowPasswordAuthentication = target.allowPasswordAuthentication
}) ),
session.connect(20_000) port = target.sshPort
return session )
} }
private fun shellQuote(value: String): String = private fun shellQuote(value: String): String =
@@ -534,7 +535,7 @@ object ServerAdminClient {
"no such file" in lower || "not found" in lower && "wdtt-server" in lower -> "no such file" in lower || "not found" in lower && "wdtt-server" in lower ->
"на сервере старый wdtt-server без admin-команд. Переустановите сервер из этой версии WDTT Plus." "на сервере старый wdtt-server без admin-команд. Переустановите сервер из этой версии WDTT Plus."
"permission denied" in lower || "authentication failed" in lower || "auth fail" in lower -> "permission denied" in lower || "authentication failed" in lower || "auth fail" in lower ->
"не удалось войти по SSH. Проверьте логин, пароль и порт." "не удалось войти по SSH. Проверьте логин, SSH-пароль или приватный ключ, пароль ключа и порт."
"root privileges required" in lower || "sudo not found" in lower -> "root privileges required" in lower || "sudo not found" in lower ->
"для управления нужны root-права или sudo на сервере." "для управления нужны root-права или sudo на сервере."
"connection refused" in lower -> "connection refused" in lower ->
@@ -0,0 +1,74 @@
package com.wdtt.plus
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7)
data class ServerMigrationState(
val pendingLevel: Int,
val acknowledgedLevel: Int,
val completedLevel: Int
) {
val noticeRequired: Boolean
get() = pendingLevel > acknowledgedLevel
val profileUpdateRequired: Boolean
get() = pendingLevel > completedLevel
}
internal data class ServerMigrationInitialization(
val lastSeenAppVersionCode: Int,
val pendingLevel: Int,
val acknowledgedLevel: Int
)
internal fun latestServerMigrationLevel(appVersionCode: Int): Int =
SERVER_MIGRATION_LEVELS.lastOrNull { it <= appVersionCode } ?: 0
internal fun crossedServerMigrationLevel(previousVersionCode: Int, currentVersionCode: Int): Int =
SERVER_MIGRATION_LEVELS.lastOrNull {
it > previousVersionCode && it <= currentVersionCode
} ?: 0
internal fun hasManagedServerCredentials(
host: String,
sshAuthMode: String,
sshPassword: String,
mainPassword: String,
sshPrivateKey: String = ""
): Boolean = host.isNotBlank() &&
sshCredentialsForMode(sshAuthMode, sshPassword, sshPrivateKey, "").hasAuthentication &&
mainPassword.isNotBlank()
/**
* Обновляет накопительное состояние предупреждений. При первом запуске новой схемы старые
* отметки v2/v3/v5 используются как исходный уровень, поэтому прочитанные окна не повторяются.
*/
internal fun resolveServerMigrationInitialization(
currentVersionCode: Int,
isUpdatedInstall: Boolean,
storedLastSeenAppVersionCode: Int?,
storedPendingLevel: Int,
storedAcknowledgedLevel: Int?,
legacyAcknowledgedLevel: Int
): ServerMigrationInitialization {
val acknowledgedLevel = maxOf(storedAcknowledgedLevel ?: 0, legacyAcknowledgedLevel)
var pendingLevel = storedPendingLevel
if (storedLastSeenAppVersionCode != null) {
pendingLevel = maxOf(
pendingLevel,
crossedServerMigrationLevel(storedLastSeenAppVersionCode, currentVersionCode)
)
} else if (isUpdatedInstall) {
val currentRequiredLevel = latestServerMigrationLevel(currentVersionCode)
if (currentRequiredLevel > acknowledgedLevel) {
pendingLevel = maxOf(pendingLevel, currentRequiredLevel)
}
}
return ServerMigrationInitialization(
lastSeenAppVersionCode = maxOf(storedLastSeenAppVersionCode ?: 0, currentVersionCode),
pendingLevel = pendingLevel,
acknowledgedLevel = acknowledgedLevel
)
}
+250 -74
View File
@@ -13,7 +13,13 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.json.JSONArray import org.json.JSONArray
@@ -229,6 +235,23 @@ object WdttDeepLink {
class SettingsStore(context: Context) { class SettingsStore(context: Context) {
private val appContext = context.applicationContext private val appContext = context.applicationContext
private val storeScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val preferencesState: StateFlow<Preferences?> = appContext.dataStore.data.stateIn(
storeScope,
SharingStarted.Eagerly,
null
)
private val preferencesFlow: Flow<Preferences> = preferencesState.filterNotNull()
private val _settingsReady = MutableStateFlow(false)
val settingsReady: StateFlow<Boolean> = _settingsReady.asStateFlow()
init {
storeScope.launch {
preferencesFlow.first()
_settingsReady.value = true
}
}
companion object { companion object {
private val Context.dataStore by preferencesDataStore("settings") private val Context.dataStore by preferencesDataStore("settings")
private val ACTIVE_PROFILE = intPreferencesKey("active_profile") private val ACTIVE_PROFILE = intPreferencesKey("active_profile")
@@ -258,6 +281,16 @@ class SettingsStore(context: Context) {
private val DEPLOY_LOGIN = stringPreferencesKey("deploy_login") private val DEPLOY_LOGIN = stringPreferencesKey("deploy_login")
private val DEPLOY_PASSWORD = stringPreferencesKey("deploy_password") private val DEPLOY_PASSWORD = stringPreferencesKey("deploy_password")
private val DEPLOY_PASSWORD_ENCRYPTED = stringPreferencesKey("deploy_password_encrypted") private val DEPLOY_PASSWORD_ENCRYPTED = stringPreferencesKey("deploy_password_encrypted")
private val DEPLOY_SSH_PRIVATE_KEY = stringPreferencesKey("deploy_ssh_private_key")
private val DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED = stringPreferencesKey("deploy_ssh_private_key_encrypted")
private val DEPLOY_SSH_KEY_PASSPHRASE = stringPreferencesKey("deploy_ssh_key_passphrase")
private val DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED = stringPreferencesKey("deploy_ssh_key_passphrase_encrypted")
private val DEPLOY_SSH_AUTH_MODE = stringPreferencesKey("deploy_ssh_auth_mode")
private val WG_EXIT_SSH_PRIVATE_KEY = stringPreferencesKey("wg_exit_ssh_private_key")
private val WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED = stringPreferencesKey("wg_exit_ssh_private_key_encrypted")
private val WG_EXIT_SSH_KEY_PASSPHRASE = stringPreferencesKey("wg_exit_ssh_key_passphrase")
private val WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED = stringPreferencesKey("wg_exit_ssh_key_passphrase_encrypted")
private val WG_EXIT_SSH_AUTH_MODE = stringPreferencesKey("wg_exit_ssh_auth_mode")
private val DEPLOY_SSH_PORT = stringPreferencesKey("deploy_ssh_port") private val DEPLOY_SSH_PORT = stringPreferencesKey("deploy_ssh_port")
private val DEPLOY_DNS1 = stringPreferencesKey("deploy_dns1") private val DEPLOY_DNS1 = stringPreferencesKey("deploy_dns1")
private val DEPLOY_DNS2 = stringPreferencesKey("deploy_dns2") private val DEPLOY_DNS2 = stringPreferencesKey("deploy_dns2")
@@ -314,6 +347,11 @@ class SettingsStore(context: Context) {
private val MIGRATION_NOTICE_V2_SHOWN = booleanPreferencesKey("migration_notice_v2_shown") private val MIGRATION_NOTICE_V2_SHOWN = booleanPreferencesKey("migration_notice_v2_shown")
private val MIGRATION_NOTICE_V3_SHOWN = booleanPreferencesKey("migration_notice_v3_shown") private val MIGRATION_NOTICE_V3_SHOWN = booleanPreferencesKey("migration_notice_v3_shown")
private val MIGRATION_NOTICE_V5_SHOWN = booleanPreferencesKey("migration_notice_v5_shown") private val MIGRATION_NOTICE_V5_SHOWN = booleanPreferencesKey("migration_notice_v5_shown")
private val SERVER_MIGRATION_STATE_INITIALIZED = booleanPreferencesKey("server_migration_state_initialized")
private val LAST_SEEN_APP_VERSION_CODE = intPreferencesKey("last_seen_app_version_code")
private val SERVER_MIGRATION_PENDING_LEVEL = intPreferencesKey("server_migration_pending_level")
private val SERVER_MIGRATION_NOTICE_ACK_LEVEL = intPreferencesKey("server_migration_notice_ack_level")
private val SERVER_MIGRATION_COMPLETED_LEVEL = intPreferencesKey("server_migration_completed_level")
private val DEVICE_COMPATIBILITY_CHECK_COMPLETE = booleanPreferencesKey("device_compatibility_check_complete") private val DEVICE_COMPATIBILITY_CHECK_COMPLETE = booleanPreferencesKey("device_compatibility_check_complete")
private val DEPLOY_CLIENTS_SECTION_EXPANDED = booleanPreferencesKey("deploy_clients_section_expanded") private val DEPLOY_CLIENTS_SECTION_EXPANDED = booleanPreferencesKey("deploy_clients_section_expanded")
private val DEPLOY_OUTBOUND_SECTION_EXPANDED = booleanPreferencesKey("deploy_outbound_section_expanded") private val DEPLOY_OUTBOUND_SECTION_EXPANDED = booleanPreferencesKey("deploy_outbound_section_expanded")
@@ -329,7 +367,7 @@ class SettingsStore(context: Context) {
val newName = "${baseKey.name}_$profile" val newName = "${baseKey.name}_$profile"
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
return when (baseKey) { return when (baseKey) {
PROFILE_NAME, PEER, VK_HASHES, SECONDARY_VK_HASH, PROTOCOL, SNI, USER_AGENT, DEPLOY_IP, DEPLOY_LOGIN, DEPLOY_PASSWORD, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_SSH_PORT, DEPLOY_DNS1, DEPLOY_DNS2, EXCLUDED_APPS, BLACKLIST_APPS, WHITELIST_APPS, CONNECTION_PASSWORD, CONNECTION_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_ADMIN_ID, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_BOT_TOKEN, DEPLOY_BOT_TOKEN_ENCRYPTED, PROXY_MODE, PROXY_HOST, CAPTCHA_MODE, CAPTCHA_SOLVE_METHOD, CAPTCHA_WBV_SOLVE_METHOD, WDTT_LINK, SELECTED_FINGERPRINT, ACTIVE_CLIENT_IDS -> stringPreferencesKey(newName) as Preferences.Key<T> PROFILE_NAME, PEER, VK_HASHES, SECONDARY_VK_HASH, PROTOCOL, SNI, USER_AGENT, DEPLOY_IP, DEPLOY_LOGIN, DEPLOY_PASSWORD, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_KEY_PASSPHRASE, DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, DEPLOY_SSH_AUTH_MODE, WG_EXIT_SSH_PRIVATE_KEY, WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, WG_EXIT_SSH_KEY_PASSPHRASE, WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED, WG_EXIT_SSH_AUTH_MODE, DEPLOY_SSH_PORT, DEPLOY_DNS1, DEPLOY_DNS2, EXCLUDED_APPS, BLACKLIST_APPS, WHITELIST_APPS, CONNECTION_PASSWORD, CONNECTION_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_ADMIN_ID, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_BOT_TOKEN, DEPLOY_BOT_TOKEN_ENCRYPTED, PROXY_MODE, PROXY_HOST, CAPTCHA_MODE, CAPTCHA_SOLVE_METHOD, CAPTCHA_WBV_SOLVE_METHOD, WDTT_LINK, SELECTED_FINGERPRINT, ACTIVE_CLIENT_IDS -> stringPreferencesKey(newName) as Preferences.Key<T>
WORKERS_PER_HASH, VK_HASH_NEXT_SLOT, LISTEN_PORT, SERVER_DTLS_PORT, SERVER_WG_PORT, PROXY_PORT -> intPreferencesKey(newName) as Preferences.Key<T> WORKERS_PER_HASH, VK_HASH_NEXT_SLOT, LISTEN_PORT, SERVER_DTLS_PORT, SERVER_WG_PORT, PROXY_PORT -> intPreferencesKey(newName) as Preferences.Key<T>
MANUAL_PORTS_ENABLED, NO_DTLS, NO_DNS, IS_WHITELIST, WDTT_LINK_MODE, VKCALLS_PREFLIGHT, DETAILED_LOGS -> booleanPreferencesKey(newName) as Preferences.Key<T> MANUAL_PORTS_ENABLED, NO_DTLS, NO_DNS, IS_WHITELIST, WDTT_LINK_MODE, VKCALLS_PREFLIGHT, DETAILED_LOGS -> booleanPreferencesKey(newName) as Preferences.Key<T>
else -> throw IllegalArgumentException("Unsupported key type: ${baseKey.name}") else -> throw IllegalArgumentException("Unsupported key type: ${baseKey.name}")
@@ -343,101 +381,130 @@ class SettingsStore(context: Context) {
init { init {
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
migrateSecretsToKeystore() migrateSecretsToKeystore()
migrateWireGuardExitSshAuthMode()
migrateVpnAppLists() migrateVpnAppLists()
} }
} }
val activeProfile: Flow<Int> = dataStore.data.map { it[ACTIVE_PROFILE] ?: 0 } val activeProfile: Flow<Int> = preferencesFlow.map { it[ACTIVE_PROFILE] ?: 0 }
val profileNames: Flow<List<String>> = dataStore.data.map { prefs -> val profileNames: Flow<List<String>> = preferencesFlow.map { prefs ->
(0 until VPN_PROFILE_COUNT).map { profile -> (0 until VPN_PROFILE_COUNT).map { profile ->
prefs[getProfileKey(PROFILE_NAME, profile)].orEmpty() prefs[getProfileKey(PROFILE_NAME, profile)].orEmpty()
} }
} }
val showSystemApps: Flow<Boolean> = dataStore.data.map { it[SHOW_SYSTEM_APPS] ?: false } val showSystemApps: Flow<Boolean> = preferencesFlow.map { it[SHOW_SYSTEM_APPS] ?: false }
val loggingEnabled: Flow<Boolean> = dataStore.data.map { it[LOGGING_ENABLED] ?: true } val loggingEnabled: Flow<Boolean> = preferencesFlow.map { it[LOGGING_ENABLED] ?: true }
val wdttLink: Flow<String> = dataStore.data.map { prefs -> val wdttLink: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(WDTT_LINK, profile)] ?: "" prefs[getProfileKey(WDTT_LINK, profile)] ?: ""
} }
val wdttLinkMode: Flow<Boolean> = dataStore.data.map { prefs -> val wdttLinkMode: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(WDTT_LINK_MODE, profile)] ?: false prefs[getProfileKey(WDTT_LINK_MODE, profile)] ?: false
} }
val peer: Flow<String> = dataStore.data.map { prefs -> val peer: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PEER, profile)] ?: "" prefs[getProfileKey(PEER, profile)] ?: ""
} }
val vkHashes: Flow<String> = dataStore.data.map { prefs -> val vkHashes: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(VK_HASHES, profile)] ?: "" prefs[getProfileKey(VK_HASHES, profile)] ?: ""
} }
val secondaryVkHash: Flow<String> = dataStore.data.map { prefs -> val secondaryVkHash: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(SECONDARY_VK_HASH, profile)] ?: "" prefs[getProfileKey(SECONDARY_VK_HASH, profile)] ?: ""
} }
val workersPerHash: Flow<Int> = dataStore.data.map { prefs -> val workersPerHash: Flow<Int> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(WORKERS_PER_HASH, profile)] ?: 16 prefs[getProfileKey(WORKERS_PER_HASH, profile)] ?: 16
} }
val protocol: Flow<String> = dataStore.data.map { prefs -> val protocol: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROTOCOL, profile)] ?: "udp" prefs[getProfileKey(PROTOCOL, profile)] ?: "udp"
} }
val listenPort: Flow<Int> = dataStore.data.map { prefs -> val listenPort: Flow<Int> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000 prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000
} }
val manualPortsEnabled: Flow<Boolean> = dataStore.data.map { prefs -> val manualPortsEnabled: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] ?: false prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] ?: false
} }
val serverDtlsPort: Flow<Int> = dataStore.data.map { prefs -> val serverDtlsPort: Flow<Int> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000 prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000
} }
val serverWgPort: Flow<Int> = dataStore.data.map { prefs -> val serverWgPort: Flow<Int> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001 prefs[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001
} }
val sni: Flow<String> = dataStore.data.map { prefs -> val sni: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(SNI, profile)] ?: "" prefs[getProfileKey(SNI, profile)] ?: ""
} }
val noDns: Flow<Boolean> = dataStore.data.map { prefs -> val noDns: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(NO_DNS, profile)] ?: false prefs[getProfileKey(NO_DNS, profile)] ?: false
} }
val userAgent: Flow<String> = dataStore.data.map { prefs -> val userAgent: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(USER_AGENT, profile)] ?: "" prefs[getProfileKey(USER_AGENT, profile)] ?: ""
} }
val deployIp: Flow<String> = dataStore.data.map { prefs -> val deployIp: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DEPLOY_IP, profile)] ?: "" prefs[getProfileKey(DEPLOY_IP, profile)] ?: ""
} }
val deployLogin: Flow<String> = dataStore.data.map { prefs -> val deployLogin: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DEPLOY_LOGIN, profile)] ?: "" prefs[getProfileKey(DEPLOY_LOGIN, profile)] ?: ""
} }
val deployPassword: Flow<String> = dataStore.data.map { prefs -> val deployPassword: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile) readSecret(prefs, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile)
} }
val deploySshPort: Flow<String> = dataStore.data.map { prefs -> val deploySshPrivateKey: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, profile)
}
val deploySshKeyPassphrase: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, DEPLOY_SSH_KEY_PASSPHRASE, profile)
}
val deploySshAuthMode: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)]
?.takeIf { it == "password" || it == "key" }
?: if (readSecret(prefs, DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, profile).isNotBlank()) "key" else "password"
}
val wireGuardExitSshPrivateKey: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, WG_EXIT_SSH_PRIVATE_KEY, profile)
}
val wireGuardExitSshKeyPassphrase: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED, WG_EXIT_SSH_KEY_PASSPHRASE, profile)
}
val wireGuardExitSshAuthMode: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(WG_EXIT_SSH_AUTH_MODE, profile)]
?.takeIf { it == "password" || it == "key" }
?: if (readSecret(prefs, WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, WG_EXIT_SSH_PRIVATE_KEY, profile).isNotBlank()) "key" else "password"
}
val deploySshPort: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] ?: "" prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] ?: ""
} }
val deployDns1: Flow<String> = dataStore.data.map { prefs -> val deployDns1: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DEPLOY_DNS1, profile)] ?: "1.1.1.1" prefs[getProfileKey(DEPLOY_DNS1, profile)] ?: "1.1.1.1"
} }
val deployDns2: Flow<String> = dataStore.data.map { prefs -> val deployDns2: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1" prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1"
} }
val vpnAppPackages: Flow<String> = dataStore.data.map { prefs -> val vpnAppPackages: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
val baseKey = if (prefs[getProfileKey(IS_WHITELIST, profile)] == true) { val baseKey = if (prefs[getProfileKey(IS_WHITELIST, profile)] == true) {
WHITELIST_APPS WHITELIST_APPS
@@ -447,109 +514,118 @@ class SettingsStore(context: Context) {
prefs[getProfileKey(baseKey, profile)] ?: "" prefs[getProfileKey(baseKey, profile)] ?: ""
} }
val detailedLogs: Flow<Boolean> = dataStore.data.map { prefs -> val detailedLogs: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DETAILED_LOGS, profile)] ?: false prefs[getProfileKey(DETAILED_LOGS, profile)] ?: false
} }
// ═══ Пароли и Управление ═══ // ═══ Пароли и Управление ═══
val connectionPassword: Flow<String> = dataStore.data.map { prefs -> val connectionPassword: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile) readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile)
} }
val deployMainPassword: Flow<String> = dataStore.data.map { prefs -> val deployMainPassword: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile) readSecret(prefs, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile)
} }
val deployAdminId: Flow<String> = dataStore.data.map { prefs -> val deployAdminId: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile) readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile)
} }
val deployBotToken: Flow<String> = dataStore.data.map { prefs -> val deployBotToken: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
readSecret(prefs, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile) readSecret(prefs, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile)
} }
// ═══ Proxy Mode ═══ // ═══ Proxy Mode ═══
val proxyMode: Flow<String> = dataStore.data.map { prefs -> val proxyMode: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROXY_MODE, profile)] ?: "tun" prefs[getProfileKey(PROXY_MODE, profile)] ?: "tun"
} }
val proxyHost: Flow<String> = dataStore.data.map { prefs -> val proxyHost: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROXY_HOST, profile)] ?: "127.0.0.1" prefs[getProfileKey(PROXY_HOST, profile)] ?: "127.0.0.1"
} }
val proxyPort: Flow<Int> = dataStore.data.map { prefs -> val proxyPort: Flow<Int> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROXY_PORT, profile)] ?: 1080 prefs[getProfileKey(PROXY_PORT, profile)] ?: 1080
} }
// ═══ Captcha Solve Mode ═══ // ═══ Captcha Solve Mode ═══
val vkCallsPreflight: Flow<Boolean> = dataStore.data.map { prefs -> val vkCallsPreflight: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true
} }
val captchaMode: Flow<String> = dataStore.data.map { prefs -> val captchaMode: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto" prefs[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto"
} }
val captchaSolveMethod: Flow<String> = dataStore.data.map { prefs -> val captchaSolveMethod: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto" prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto"
} }
val captchaWbvSolveMethod: Flow<String> = dataStore.data.map { prefs -> val captchaWbvSolveMethod: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] ?: "auto" prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] ?: "auto"
} }
// ═══ VPN Exclusions Mode ═══ // ═══ VPN Exclusions Mode ═══
val isWhitelist: Flow<Boolean> = dataStore.data.map { prefs -> val isWhitelist: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(IS_WHITELIST, profile)] ?: false prefs[getProfileKey(IS_WHITELIST, profile)] ?: false
} }
// ═══ Theme Mode ═══ // ═══ Theme Mode ═══
val themeMode: Flow<String> = dataStore.data.map { it[THEME_MODE] ?: "system" } val themeMode: Flow<String> = preferencesFlow.map { it[THEME_MODE] ?: "system" }
val isDynamicColor: Flow<Boolean> = dataStore.data.map { it[IS_DYNAMIC_COLOR] ?: (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) } val isDynamicColor: Flow<Boolean> = preferencesFlow.map { it[IS_DYNAMIC_COLOR] ?: (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) }
val themePalette: Flow<String> = dataStore.data.map { it[THEME_PALETTE] ?: "indigo" } val themePalette: Flow<String> = preferencesFlow.map { it[THEME_PALETTE] ?: "indigo" }
// ═══ Fingerprint & Client IDs ═══ // ═══ Fingerprint & Client IDs ═══
val selectedFingerprint: Flow<String> = dataStore.data.map { prefs -> val selectedFingerprint: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox" prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox"
} }
val activeClientIds: Flow<String> = dataStore.data.map { prefs -> val activeClientIds: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: "6287487,8202606" prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: "6287487,8202606"
} }
val clientIdCheckResults: Flow<String> = dataStore.data.map { prefs -> val clientIdCheckResults: Flow<String> = preferencesFlow.map { prefs ->
prefs[CLIENT_ID_CHECK_RESULTS] ?: "{}" prefs[CLIENT_ID_CHECK_RESULTS] ?: "{}"
} }
val updateLastCheckAt: Flow<Long> = dataStore.data.map { it[UPDATE_LAST_CHECK_AT] ?: 0L } val updateLastCheckAt: Flow<Long> = preferencesFlow.map { it[UPDATE_LAST_CHECK_AT] ?: 0L }
val updateLatestVersion: Flow<String> = dataStore.data.map { it[UPDATE_LATEST_VERSION] ?: "" } val updateLatestVersion: Flow<String> = preferencesFlow.map { it[UPDATE_LATEST_VERSION] ?: "" }
val updateLastError: Flow<String> = dataStore.data.map { it[UPDATE_LAST_ERROR] ?: "" } val updateLastError: Flow<String> = preferencesFlow.map { it[UPDATE_LAST_ERROR] ?: "" }
val updateCheckIntervalMinutes: Flow<Int> = dataStore.data.map { val updateCheckIntervalMinutes: Flow<Int> = preferencesFlow.map {
normalizeUpdateCheckIntervalMinutes(it[UPDATE_CHECK_INTERVAL_MINUTES] ?: DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES) normalizeUpdateCheckIntervalMinutes(it[UPDATE_CHECK_INTERVAL_MINUTES] ?: DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES)
} }
val updatePostponeUntil: Flow<Long> = dataStore.data.map { it[UPDATE_POSTPONE_UNTIL] ?: 0L } val updatePostponeUntil: Flow<Long> = preferencesFlow.map { it[UPDATE_POSTPONE_UNTIL] ?: 0L }
val updatePostponeVersion: Flow<String> = dataStore.data.map { it[UPDATE_POSTPONE_VERSION] ?: "" } val updatePostponeVersion: Flow<String> = preferencesFlow.map { it[UPDATE_POSTPONE_VERSION] ?: "" }
val updateDialogLastShownVersion: Flow<String> = dataStore.data.map { it[UPDATE_DIALOG_LAST_SHOWN_VERSION] ?: "" } val updateDialogLastShownVersion: Flow<String> = preferencesFlow.map { it[UPDATE_DIALOG_LAST_SHOWN_VERSION] ?: "" }
val updateDialogLastShownAt: Flow<Long> = dataStore.data.map { it[UPDATE_DIALOG_LAST_SHOWN_AT] ?: 0L } val updateDialogLastShownAt: Flow<Long> = preferencesFlow.map { it[UPDATE_DIALOG_LAST_SHOWN_AT] ?: 0L }
val updateDialogLastActionVersion: Flow<String> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_VERSION] ?: "" } val updateDialogLastActionVersion: Flow<String> = preferencesFlow.map { it[UPDATE_DIALOG_LAST_ACTION_VERSION] ?: "" }
val updateDialogLastAction: Flow<String> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION] ?: "" } val updateDialogLastAction: Flow<String> = preferencesFlow.map { it[UPDATE_DIALOG_LAST_ACTION] ?: "" }
val updateDialogLastActionAt: Flow<Long> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_AT] ?: 0L } val updateDialogLastActionAt: Flow<Long> = preferencesFlow.map { it[UPDATE_DIALOG_LAST_ACTION_AT] ?: 0L }
val migrationNoticeV2Shown: Flow<Boolean> = dataStore.data.map { it[MIGRATION_NOTICE_V2_SHOWN] ?: false } val serverMigrationState: Flow<ServerMigrationState?> = preferencesFlow.map { prefs ->
val migrationNoticeV3Shown: Flow<Boolean> = dataStore.data.map { it[MIGRATION_NOTICE_V3_SHOWN] ?: false } if (prefs[SERVER_MIGRATION_STATE_INITIALIZED] != true) {
val migrationNoticeV5Shown: Flow<Boolean> = dataStore.data.map { it[MIGRATION_NOTICE_V5_SHOWN] ?: false } null
val deviceCompatibilityCheckComplete: Flow<Boolean> = dataStore.data.map { } else {
val profile = prefs[ACTIVE_PROFILE] ?: 0
ServerMigrationState(
pendingLevel = prefs[SERVER_MIGRATION_PENDING_LEVEL] ?: 0,
acknowledgedLevel = prefs[SERVER_MIGRATION_NOTICE_ACK_LEVEL] ?: 0,
completedLevel = prefs[serverMigrationCompletedKey(profile)] ?: 0
)
}
}
val deviceCompatibilityCheckComplete: Flow<Boolean> = preferencesFlow.map {
it[DEVICE_COMPATIBILITY_CHECK_COMPLETE] ?: false it[DEVICE_COMPATIBILITY_CHECK_COMPLETE] ?: false
} }
val deployClientsSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: false } val deployClientsSectionExpanded: Flow<Boolean> = preferencesFlow.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: false }
val deployOutboundSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_OUTBOUND_SECTION_EXPANDED] ?: false } val deployOutboundSectionExpanded: Flow<Boolean> = preferencesFlow.map { it[DEPLOY_OUTBOUND_SECTION_EXPANDED] ?: false }
val deployMigrationSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_MIGRATION_SECTION_EXPANDED] ?: false } val deployMigrationSectionExpanded: Flow<Boolean> = preferencesFlow.map { it[DEPLOY_MIGRATION_SECTION_EXPANDED] ?: false }
val interfaceRole: Flow<String> = dataStore.data.map { it[INTERFACE_ROLE] ?: "" } val interfaceRole: Flow<String> = preferencesFlow.map { it[INTERFACE_ROLE] ?: "" }
val permissionOnboardingComplete: Flow<Boolean> = dataStore.data.map { prefs -> val permissionOnboardingComplete: Flow<Boolean> = preferencesFlow.map { prefs ->
prefs[PERMISSION_ONBOARDING_COMPLETE] ?: !prefs[INTERFACE_ROLE].isNullOrBlank() prefs[PERMISSION_ONBOARDING_COMPLETE] ?: !prefs[INTERFACE_ROLE].isNullOrBlank()
} }
@@ -645,21 +721,44 @@ class SettingsStore(context: Context) {
} }
} }
suspend fun saveMigrationNoticeV2Shown() { suspend fun initializeServerMigrationState(currentVersionCode: Int, isUpdatedInstall: Boolean) {
dataStore.edit { prefs -> dataStore.edit { prefs ->
prefs[MIGRATION_NOTICE_V2_SHOWN] = true val legacyAcknowledgedLevel = when {
prefs[MIGRATION_NOTICE_V5_SHOWN] == true -> 5
prefs[MIGRATION_NOTICE_V3_SHOWN] == true -> 3
prefs[MIGRATION_NOTICE_V2_SHOWN] == true -> 2
else -> 0
}
val result = resolveServerMigrationInitialization(
currentVersionCode = currentVersionCode,
isUpdatedInstall = isUpdatedInstall,
storedLastSeenAppVersionCode = prefs[LAST_SEEN_APP_VERSION_CODE],
storedPendingLevel = prefs[SERVER_MIGRATION_PENDING_LEVEL] ?: 0,
storedAcknowledgedLevel = prefs[SERVER_MIGRATION_NOTICE_ACK_LEVEL],
legacyAcknowledgedLevel = legacyAcknowledgedLevel
)
prefs[LAST_SEEN_APP_VERSION_CODE] = result.lastSeenAppVersionCode
prefs[SERVER_MIGRATION_PENDING_LEVEL] = result.pendingLevel
prefs[SERVER_MIGRATION_NOTICE_ACK_LEVEL] = result.acknowledgedLevel
prefs[SERVER_MIGRATION_STATE_INITIALIZED] = true
} }
} }
suspend fun saveMigrationNoticeV3Shown() { suspend fun acknowledgeServerMigrationNotice(level: Int) {
if (level <= 0) return
dataStore.edit { prefs -> dataStore.edit { prefs ->
prefs[MIGRATION_NOTICE_V3_SHOWN] = true prefs[SERVER_MIGRATION_NOTICE_ACK_LEVEL] = maxOf(
prefs[SERVER_MIGRATION_NOTICE_ACK_LEVEL] ?: 0,
level
)
} }
} }
suspend fun saveMigrationNoticeV5Shown() { suspend fun markProfileServerMigrationComplete(profile: Int, level: Int) {
if (level <= 0) return
dataStore.edit { prefs -> dataStore.edit { prefs ->
prefs[MIGRATION_NOTICE_V5_SHOWN] = true val key = serverMigrationCompletedKey(profile.coerceIn(0, VPN_PROFILE_COUNT - 1))
prefs[key] = maxOf(prefs[key] ?: 0, level)
} }
} }
@@ -669,6 +768,10 @@ class SettingsStore(context: Context) {
} }
} }
private fun serverMigrationCompletedKey(profile: Int): Preferences.Key<Int> =
if (profile == 0) SERVER_MIGRATION_COMPLETED_LEVEL
else intPreferencesKey("${SERVER_MIGRATION_COMPLETED_LEVEL.name}_$profile")
suspend fun saveDeployClientsSectionExpanded(expanded: Boolean) { suspend fun saveDeployClientsSectionExpanded(expanded: Boolean) {
dataStore.edit { prefs -> dataStore.edit { prefs ->
prefs[DEPLOY_CLIENTS_SECTION_EXPANDED] = expanded prefs[DEPLOY_CLIENTS_SECTION_EXPANDED] = expanded
@@ -733,7 +836,7 @@ class SettingsStore(context: Context) {
suspend fun createWdttDeepLinkApplyPlan(link: String): WdttDeepLinkApplyPlan? { suspend fun createWdttDeepLinkApplyPlan(link: String): WdttDeepLinkApplyPlan? {
WdttDeepLink.parse(link) ?: return null WdttDeepLink.parse(link) ?: return null
val cleanLink = link.trim() val cleanLink = link.trim()
return dataStore.data.map { prefs -> return appContext.dataStore.data.map { prefs ->
val activeProfile = (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1) val activeProfile = (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
val freeProfile = (0 until VPN_PROFILE_COUNT).firstOrNull { profile -> val freeProfile = (0 until VPN_PROFILE_COUNT).firstOrNull { profile ->
prefs.isTunnelProfileEmpty(profile) prefs.isTunnelProfileEmpty(profile)
@@ -749,7 +852,7 @@ class SettingsStore(context: Context) {
suspend fun connectionLinkForProfile(profileIndex: Int): String { suspend fun connectionLinkForProfile(profileIndex: Int): String {
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1) val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
return dataStore.data.map { prefs -> return appContext.dataStore.data.map { prefs ->
val storedLink = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty() val storedLink = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty()
val storedParts = WdttDeepLink.parse(storedLink) val storedParts = WdttDeepLink.parse(storedLink)
val parts = storedParts ?: WdttLinkParts( val parts = storedParts ?: WdttLinkParts(
@@ -775,7 +878,7 @@ class SettingsStore(context: Context) {
}.first() }.first()
} }
suspend fun exportAdminSettings(): String = dataStore.data.map { prefs -> suspend fun exportAdminSettings(): String = appContext.dataStore.data.map { prefs ->
val profiles = JSONArray() val profiles = JSONArray()
repeat(VPN_PROFILE_COUNT) { profile -> repeat(VPN_PROFILE_COUNT) { profile ->
profiles.put(JSONObject().apply { profiles.put(JSONObject().apply {
@@ -874,6 +977,12 @@ class SettingsStore(context: Context) {
prefs[getProfileKey(DEPLOY_IP, profile)] = item.optString("deployIp") prefs[getProfileKey(DEPLOY_IP, profile)] = item.optString("deployIp")
prefs[getProfileKey(DEPLOY_LOGIN, profile)] = item.optString("deployLogin") prefs[getProfileKey(DEPLOY_LOGIN, profile)] = item.optString("deployLogin")
prefs.putSecret(DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, item.optString("deployPassword"), profile) prefs.putSecret(DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, item.optString("deployPassword"), profile)
prefs.putSecret(DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, DEPLOY_SSH_PRIVATE_KEY, "", profile)
prefs.putSecret(DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, DEPLOY_SSH_KEY_PASSPHRASE, "", profile)
prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] = "password"
prefs.putSecret(WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, WG_EXIT_SSH_PRIVATE_KEY, "", profile)
prefs.putSecret(WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED, WG_EXIT_SSH_KEY_PASSPHRASE, "", profile)
prefs[getProfileKey(WG_EXIT_SSH_AUTH_MODE, profile)] = "password"
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] = item.optString("deploySshPort") prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] = item.optString("deploySshPort")
prefs[getProfileKey(DEPLOY_DNS1, profile)] = item.optString("deployDns1", "1.1.1.1") prefs[getProfileKey(DEPLOY_DNS1, profile)] = item.optString("deployDns1", "1.1.1.1")
prefs[getProfileKey(DEPLOY_DNS2, profile)] = item.optString("deployDns2", "1.0.0.1") prefs[getProfileKey(DEPLOY_DNS2, profile)] = item.optString("deployDns2", "1.0.0.1")
@@ -1060,6 +1169,55 @@ class SettingsStore(context: Context) {
} }
} }
suspend fun saveDeploySshKey(privateKey: String, passphrase: String) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
val normalizedKey = normalizeSshPrivateKey(privateKey)
prefs.putSecret(
DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED,
DEPLOY_SSH_PRIVATE_KEY,
normalizedKey,
profile
)
prefs.putSecret(
DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED,
DEPLOY_SSH_KEY_PASSPHRASE,
passphrase.takeIf { normalizedKey.isNotBlank() }.orEmpty(),
profile
)
}
}
suspend fun saveDeploySshAuthMode(mode: String) {
require(mode == "password" || mode == "key")
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DEPLOY_SSH_AUTH_MODE, profile)] = mode
}
}
suspend fun saveWireGuardExitSshKey(privateKey: String, passphrase: String) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
val normalizedKey = normalizeSshPrivateKey(privateKey)
prefs.putSecret(WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, WG_EXIT_SSH_PRIVATE_KEY, normalizedKey, profile)
prefs.putSecret(
WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED,
WG_EXIT_SSH_KEY_PASSPHRASE,
passphrase.takeIf { normalizedKey.isNotBlank() }.orEmpty(),
profile
)
}
}
suspend fun saveWireGuardExitSshAuthMode(mode: String) {
require(mode == "password" || mode == "key")
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(WG_EXIT_SSH_AUTH_MODE, profile)] = mode
}
}
suspend fun toggleVpnAppSelected(packageName: String, whitelist: Boolean) { suspend fun toggleVpnAppSelected(packageName: String, whitelist: Boolean) {
dataStore.edit { prefs -> dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0 val profile = prefs[ACTIVE_PROFILE] ?: 0
@@ -1174,6 +1332,10 @@ class SettingsStore(context: Context) {
dataStore.edit { prefs -> dataStore.edit { prefs ->
for (profile in 0..2) { for (profile in 0..2) {
prefs.migrateSecret(getProfileKey(DEPLOY_PASSWORD_ENCRYPTED, profile), getProfileKey(DEPLOY_PASSWORD, profile)) prefs.migrateSecret(getProfileKey(DEPLOY_PASSWORD_ENCRYPTED, profile), getProfileKey(DEPLOY_PASSWORD, profile))
prefs.migrateSecret(getProfileKey(DEPLOY_SSH_PRIVATE_KEY_ENCRYPTED, profile), getProfileKey(DEPLOY_SSH_PRIVATE_KEY, profile))
prefs.migrateSecret(getProfileKey(DEPLOY_SSH_KEY_PASSPHRASE_ENCRYPTED, profile), getProfileKey(DEPLOY_SSH_KEY_PASSPHRASE, profile))
prefs.migrateSecret(getProfileKey(WG_EXIT_SSH_PRIVATE_KEY_ENCRYPTED, profile), getProfileKey(WG_EXIT_SSH_PRIVATE_KEY, profile))
prefs.migrateSecret(getProfileKey(WG_EXIT_SSH_KEY_PASSPHRASE_ENCRYPTED, profile), getProfileKey(WG_EXIT_SSH_KEY_PASSPHRASE, profile))
prefs.migrateSecret(getProfileKey(CONNECTION_PASSWORD_ENCRYPTED, profile), getProfileKey(CONNECTION_PASSWORD, profile)) prefs.migrateSecret(getProfileKey(CONNECTION_PASSWORD_ENCRYPTED, profile), getProfileKey(CONNECTION_PASSWORD, profile))
prefs.migrateSecret(getProfileKey(DEPLOY_MAIN_PASSWORD_ENCRYPTED, profile), getProfileKey(DEPLOY_MAIN_PASSWORD, profile)) prefs.migrateSecret(getProfileKey(DEPLOY_MAIN_PASSWORD_ENCRYPTED, profile), getProfileKey(DEPLOY_MAIN_PASSWORD, profile))
prefs.migrateSecret(getProfileKey(DEPLOY_ADMIN_ID_ENCRYPTED, profile), getProfileKey(DEPLOY_ADMIN_ID, profile)) prefs.migrateSecret(getProfileKey(DEPLOY_ADMIN_ID_ENCRYPTED, profile), getProfileKey(DEPLOY_ADMIN_ID, profile))
@@ -1182,6 +1344,20 @@ class SettingsStore(context: Context) {
} }
} }
private suspend fun migrateWireGuardExitSshAuthMode() {
val legacyPrefs = appContext.getSharedPreferences("wdtt_outbound_forms", Context.MODE_PRIVATE)
val legacyMode = legacyPrefs.getString("wg_exit_auth_mode", null)
?.takeIf { it == "password" || it == "key" }
?: return
dataStore.edit { prefs ->
for (profile in 0 until VPN_PROFILE_COUNT) {
val key = getProfileKey(WG_EXIT_SSH_AUTH_MODE, profile)
if (prefs[key] == null) prefs[key] = legacyMode
}
}
legacyPrefs.edit().remove("wg_exit_auth_mode").apply()
}
private suspend fun migrateVpnAppLists() { private suspend fun migrateVpnAppLists() {
dataStore.edit { prefs -> dataStore.edit { prefs ->
for (profile in 0 until VPN_PROFILE_COUNT) { for (profile in 0 until VPN_PROFILE_COUNT) {
@@ -0,0 +1,141 @@
package com.wdtt.plus
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session
import java.util.Properties
const val MAX_SSH_PRIVATE_KEY_CHARS = 128 * 1024
data class SshCredentials(
val password: String = "",
val privateKey: String = "",
val privateKeyPassphrase: String = "",
val allowPasswordAuthentication: Boolean = true
) {
val hasAuthentication: Boolean
get() = (privateKey.isNotBlank() && sshPrivateKeyIssue(privateKey) == null) ||
(allowPasswordAuthentication && password.isNotBlank())
val usesPrivateKey: Boolean
get() = privateKey.isNotBlank()
val usesPasswordAuthentication: Boolean
get() = allowPasswordAuthentication && password.isNotBlank()
}
fun sshCredentialsForMode(
mode: String,
password: String,
privateKey: String,
privateKeyPassphrase: String
): SshCredentials = if (mode == "key") {
SshCredentials(
password = password,
privateKey = privateKey,
privateKeyPassphrase = privateKeyPassphrase,
allowPasswordAuthentication = false
)
} else {
SshCredentials(password = password, allowPasswordAuthentication = true)
}
fun normalizeSshPrivateKey(value: String): String =
value.removePrefix("\uFEFF").replace("\r\n", "\n").trim()
fun sshPrivateKeyIssue(value: String): String? {
val key = normalizeSshPrivateKey(value)
if (key.isBlank()) return "Приватный ключ не указан."
if (key.length > MAX_SSH_PRIVATE_KEY_CHARS) return "Файл ключа слишком большой. Максимум — 128 КБ."
if (" PUBLIC KEY-----" in key.lineSequence().firstOrNull().orEmpty()) {
return "Выбран публичный ключ. Нужен приватный ключ."
}
val supportedHeaders = listOf(
"-----BEGIN OPENSSH PRIVATE KEY-----",
"-----BEGIN RSA PRIVATE KEY-----",
"-----BEGIN EC PRIVATE KEY-----",
"-----BEGIN DSA PRIVATE KEY-----",
"-----BEGIN PRIVATE KEY-----",
"-----BEGIN ENCRYPTED PRIVATE KEY-----"
)
val header = supportedHeaders.firstOrNull(key::startsWith)
?: return "Формат ключа не распознан. Поддерживаются OpenSSH и PEM-приватные ключи."
val footer = header.replace("BEGIN", "END")
if (!key.endsWith(footer)) return "Приватный ключ обрезан или повреждён: не найден конец ключа."
return null
}
internal fun friendlySshConnectionError(message: String, credentials: SshCredentials): String = when {
message.contains("invalid privatekey", ignoreCase = true) ->
"Приватный SSH-ключ повреждён или имеет неподдерживаемый формат."
message.contains("decrypt", ignoreCase = true) || message.contains("passphrase", ignoreCase = true) ->
"Не удалось расшифровать приватный SSH-ключ. Проверьте пароль ключа."
message.contains("Auth fail", ignoreCase = true) && credentials.usesPrivateKey &&
!credentials.usesPasswordAuthentication ->
"SSH-сервер отклонил приватный ключ. Проверьте логин SSH, наличие соответствующего публичного ключа на сервере и пароль ключа."
message.contains("Auth fail", ignoreCase = true) && credentials.usesPasswordAuthentication &&
!credentials.usesPrivateKey ->
"SSH-сервер отклонил пароль. Проверьте логин SSH и пароль."
message.contains("Auth fail", ignoreCase = true) ->
"SSH-сервер отклонил пароль и приватный ключ. Проверьте логин SSH, ключ и пароль ключа."
message.contains("connection refused", ignoreCase = true) ->
"SSH-сервер доступен, но порт отклонил подключение. Проверьте SSH-порт и настройки SSH-сервера."
message.contains("unknownhost", ignoreCase = true) ||
message.contains("unknown host", ignoreCase = true) ->
"Не удалось найти SSH-сервер. Проверьте IP-адрес или домен."
message.contains("timeout", ignoreCase = true) ->
"SSH-сервер не ответил за 20 секунд. Проверьте адрес, порт, сеть и межсетевой экран."
else -> "Не удалось подключиться по SSH: ${message.ifBlank { "неизвестная ошибка" }}"
}
fun createSshSession(
host: String,
user: String,
credentials: SshCredentials,
port: Int = 22
): Session {
require(host.isNotBlank()) { "Не указан адрес SSH-сервера." }
require(port in 1..65535) { "SSH-порт должен быть от 1 до 65535." }
require(credentials.hasAuthentication) { "Укажите SSH-пароль или приватный SSH-ключ." }
try {
val jsch = JSch()
val privateKey = normalizeSshPrivateKey(credentials.privateKey)
if (privateKey.isNotBlank()) {
sshPrivateKeyIssue(privateKey)?.let { throw IllegalArgumentException(it) }
jsch.addIdentity(
"wdtt-plus-memory-key",
privateKey.toByteArray(Charsets.UTF_8),
null,
credentials.privateKeyPassphrase.takeIf { it.isNotEmpty() }?.toByteArray(Charsets.UTF_8)
)
}
val session = jsch.getSession(user.ifBlank { "root" }, host.trim(), port)
if (credentials.allowPasswordAuthentication && credentials.password.isNotBlank()) {
session.setPassword(credentials.password)
}
session.setConfig(Properties().apply {
put("StrictHostKeyChecking", "no")
put("ServerAliveInterval", "10")
put("ServerAliveCountMax", "6")
put("ConnectTimeout", "15000")
put(
"PreferredAuthentications",
when {
privateKey.isNotBlank() && credentials.allowPasswordAuthentication -> "publickey,password,keyboard-interactive"
privateKey.isNotBlank() -> "publickey"
credentials.allowPasswordAuthentication -> "password,keyboard-interactive"
else -> "publickey"
}
)
})
session.connect(20_000)
return session
} catch (error: IllegalArgumentException) {
throw error
} catch (error: JSchException) {
val message = error.message.orEmpty()
throw IllegalStateException(friendlySshConnectionError(message, credentials), error)
}
}
@@ -42,13 +42,14 @@ private fun appSectionCardBorderColor(): Color {
@Composable @Composable
fun AppSectionCard( fun AppSectionCard(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
containerColor: Color? = null,
contentPadding: PaddingValues = PaddingValues(horizontal = 18.dp, vertical = 18.dp), contentPadding: PaddingValues = PaddingValues(horizontal = 18.dp, vertical = 18.dp),
verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(16.dp), verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(16.dp),
content: @Composable ColumnScope.() -> Unit content: @Composable ColumnScope.() -> Unit
) { ) {
Surface( Surface(
shape = RoundedCornerShape(28.dp), shape = RoundedCornerShape(28.dp),
color = appSectionCardColor(), color = containerColor ?: appSectionCardColor(),
contentColor = MaterialTheme.colorScheme.onSurface, contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(1.dp, appSectionCardBorderColor()), border = BorderStroke(1.dp, appSectionCardBorderColor()),
shadowElevation = 0.dp, shadowElevation = 0.dp,
File diff suppressed because it is too large. Load diff
@@ -123,6 +123,7 @@ import com.wdtt.plus.ServerAdminClient
import com.wdtt.plus.ServerAdminProfileInfo import com.wdtt.plus.ServerAdminProfileInfo
import com.wdtt.plus.ServerAdminState import com.wdtt.plus.ServerAdminState
import com.wdtt.plus.ServerAdminTarget import com.wdtt.plus.ServerAdminTarget
import com.wdtt.plus.SshCredentials
import com.wdtt.plus.ServerClientCreateRequest import com.wdtt.plus.ServerClientCreateRequest
import com.wdtt.plus.ServerClientInfo import com.wdtt.plus.ServerClientInfo
import com.wdtt.plus.ServerTrafficPeriod import com.wdtt.plus.ServerTrafficPeriod
@@ -167,14 +168,29 @@ internal fun serverClientsAccessIssue(
hostValid: Boolean, hostValid: Boolean,
sshPassword: String, sshPassword: String,
sshPort: Int, sshPort: Int,
mainPassword: String mainPassword: String,
): String? = when { sshPrivateKey: String = "",
host.isBlank() -> "Укажите IP-адрес или домен сервера в верхнем блоке «Деплой»." allowPasswordAuthentication: Boolean = true
!hostValid -> "Проверьте IP-адрес или домен сервера в верхнем блоке «Деплой»." ): String? {
sshPassword.isBlank() -> "Укажите SSH-пароль сервера в верхнем блоке «Деплой»." if (host.isBlank()) return "Укажите IP-адрес или домен сервера в верхнем блоке «Деплой»."
sshPort !in 1..65535 -> "Укажите корректный SSH-порт от 1 до 65535." if (!hostValid) return "Проверьте IP-адрес или домен сервера в верхнем блоке «Деплой»."
mainPassword.isBlank() -> "Откройте «Секреты» и укажите главный пароль администратора." val credentials = SshCredentials(
else -> null password = sshPassword,
privateKey = sshPrivateKey,
allowPasswordAuthentication = allowPasswordAuthentication
)
if (!credentials.hasAuthentication) {
return sshAuthenticationIssueForMode(
mode = if (allowPasswordAuthentication) "password" else "key",
password = sshPassword,
privateKey = sshPrivateKey,
passwordLabel = "SSH-пароль",
privateKeyLabel = "приватный SSH-ключ"
) ?: "Укажите SSH-пароль или приватный SSH-ключ в верхнем блоке «Деплой»."
}
if (sshPort !in 1..65535) return "Укажите корректный SSH-порт от 1 до 65535."
if (mainPassword.isBlank()) return "Откройте «Секреты» и укажите главный пароль администратора."
return null
} }
internal fun shouldAutoRefreshServerClients( internal fun shouldAutoRefreshServerClients(
@@ -308,6 +324,9 @@ fun ServerClientsSection(
host: String, host: String,
user: String, user: String,
sshPassword: String, sshPassword: String,
sshPrivateKey: String,
sshKeyPassphrase: String,
allowPasswordAuthentication: Boolean,
sshPort: Int, sshPort: Int,
mainPassword: String, mainPassword: String,
defaultPorts: String, defaultPorts: String,
@@ -362,16 +381,21 @@ fun ServerClientsSection(
host = host, host = host,
hostValid = hostValid, hostValid = hostValid,
sshPassword = sshPassword, sshPassword = sshPassword,
sshPrivateKey = sshPrivateKey,
allowPasswordAuthentication = allowPasswordAuthentication,
sshPort = sshPort, sshPort = sshPort,
mainPassword = mainPassword mainPassword = mainPassword
) )
val targetReady = accessIssue == null val targetReady = accessIssue == null
val targetKey = remember(host, user, sshPassword, sshPort, mainPassword) { val targetKey = remember(host, user, sshPassword, sshPrivateKey, sshKeyPassphrase, allowPasswordAuthentication, sshPort, mainPassword) {
listOf( listOf(
host.trim(), host.trim(),
user.ifBlank { "root" }, user.ifBlank { "root" },
sshPort.toString(), sshPort.toString(),
sshPassword.hashCode().toString(), sshPassword.hashCode().toString(),
sshPrivateKey.hashCode().toString(),
sshKeyPassphrase.hashCode().toString(),
allowPasswordAuthentication.toString(),
mainPassword.hashCode().toString() mainPassword.hashCode().toString()
).joinToString("\u0000") ).joinToString("\u0000")
} }
@@ -404,6 +428,9 @@ fun ServerClientsSection(
host = host.trim(), host = host.trim(),
user = effectiveUser, user = effectiveUser,
sshPassword = sshPassword, sshPassword = sshPassword,
sshPrivateKey = sshPrivateKey,
sshKeyPassphrase = sshKeyPassphrase,
allowPasswordAuthentication = allowPasswordAuthentication,
sshPort = sshPort, sshPort = sshPort,
mainPassword = mainPassword mainPassword = mainPassword
) )
@@ -0,0 +1,92 @@
package com.wdtt.plus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ServerMigrationTest {
@Test
fun skippedVersionsAccumulateLatestServerMigration() {
val result = resolveServerMigrationInitialization(
currentVersionCode = 8,
isUpdatedInstall = true,
storedLastSeenAppVersionCode = 3,
storedPendingLevel = 0,
storedAcknowledgedLevel = 3,
legacyAcknowledgedLevel = 3
)
assertEquals(7, result.pendingLevel)
assertEquals(3, result.acknowledgedLevel)
}
@Test
fun legacyFlagsPreventAlreadySeenNoticesButNotLaterMigrations() {
val result = resolveServerMigrationInitialization(
currentVersionCode = 8,
isUpdatedInstall = true,
storedLastSeenAppVersionCode = null,
storedPendingLevel = 0,
storedAcknowledgedLevel = null,
legacyAcknowledgedLevel = 5
)
assertEquals(7, result.pendingLevel)
assertEquals(5, result.acknowledgedLevel)
}
@Test
fun freshInstallDoesNotRequireServerMigration() {
val result = resolveServerMigrationInitialization(
currentVersionCode = 8,
isUpdatedInstall = false,
storedLastSeenAppVersionCode = null,
storedPendingLevel = 0,
storedAcknowledgedLevel = null,
legacyAcknowledgedLevel = 0
)
assertEquals(0, result.pendingLevel)
assertEquals(8, result.lastSeenAppVersionCode)
}
@Test
fun appVersionWithoutServerChangesDoesNotCreateNewNotice() {
val result = resolveServerMigrationInitialization(
currentVersionCode = 8,
isUpdatedInstall = true,
storedLastSeenAppVersionCode = 7,
storedPendingLevel = 7,
storedAcknowledgedLevel = 7,
legacyAcknowledgedLevel = 5
)
assertEquals(7, result.pendingLevel)
assertEquals(7, result.acknowledgedLevel)
}
@Test
fun stateSeparatesReadNoticeFromCompletedDeployment() {
val state = ServerMigrationState(
pendingLevel = 7,
acknowledgedLevel = 7,
completedLevel = 5
)
assertFalse(state.noticeRequired)
assertTrue(state.profileUpdateRequired)
}
@Test
fun serverNoticeRequiresBothSshAndOwnerCredentials() {
assertTrue(hasManagedServerCredentials("example.org", "password", "ssh-password", "owner-password"))
assertFalse(hasManagedServerCredentials("example.org", "password", "", "owner-password"))
assertFalse(hasManagedServerCredentials("example.org", "password", "ssh-password", ""))
assertFalse(hasManagedServerCredentials("", "password", "ssh-password", "owner-password"))
val key = "-----BEGIN OPENSSH PRIVATE KEY-----\ndGVzdA==\n-----END OPENSSH PRIVATE KEY-----"
assertTrue(hasManagedServerCredentials("example.org", "key", "", "owner-password", key))
assertFalse(hasManagedServerCredentials("example.org", "key", "sudo-password", "owner-password", ""))
assertFalse(hasManagedServerCredentials("example.org", "password", "", "owner-password", key))
}
}
@@ -0,0 +1,121 @@
package com.wdtt.plus
import com.jcraft.jsch.JSch
import com.jcraft.jsch.KeyPair
import java.io.ByteArrayOutputStream
import java.io.File
import org.junit.Assume.assumeTrue
import org.junit.Assert.assertFalse
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class SshAuthenticationTest {
private val openSshKey = """
-----BEGIN OPENSSH PRIVATE KEY-----
dGVzdA==
-----END OPENSSH PRIVATE KEY-----
""".trimIndent()
@Test
fun acceptsStructurallyCompleteOpenSshKey() {
assertNull(sshPrivateKeyIssue(openSshKey))
assertTrue(SshCredentials(privateKey = openSshKey).hasAuthentication)
}
@Test
fun rejectsPublicAndTruncatedKeys() {
assertTrue(sshPrivateKeyIssue("ssh-ed25519 AAAA test") != null)
assertTrue(sshPrivateKeyIssue("-----BEGIN OPENSSH PRIVATE KEY-----\nabc") != null)
}
@Test
fun passwordRemainsAValidFallback() {
assertTrue(SshCredentials(password = "secret").hasAuthentication)
assertFalse(SshCredentials().hasAuthentication)
}
@Test
fun selectedModePreventsSavedKeyFromHijackingPasswordLogin() {
val passwordMode = sshCredentialsForMode("password", "secret", openSshKey, "key-pass")
assertTrue(passwordMode.hasAuthentication)
assertFalse(passwordMode.usesPrivateKey)
assertTrue(passwordMode.usesPasswordAuthentication)
val keyMode = sshCredentialsForMode("key", "sudo-pass", openSshKey, "key-pass")
assertTrue(keyMode.usesPrivateKey)
assertTrue(keyMode.hasAuthentication)
assertFalse(keyMode.usesPasswordAuthentication)
assertFalse(keyMode.allowPasswordAuthentication)
}
@Test
fun privateKeyPresenceDoesNotDisablePasswordModeByItself() {
val credentials = SshCredentials(
password = "secret",
privateKey = openSshKey,
privateKeyPassphrase = "key-pass",
allowPasswordAuthentication = true
)
assertTrue(credentials.hasAuthentication)
assertTrue(credentials.usesPasswordAuthentication)
assertTrue(credentials.usesPrivateKey)
}
@Test
fun authenticationFailureExplainsTheSelectedMethod() {
assertEquals(
"SSH-сервер отклонил пароль. Проверьте логин SSH и пароль.",
friendlySshConnectionError("Auth fail", SshCredentials(password = "secret"))
)
assertEquals(
"SSH-сервер отклонил приватный ключ. Проверьте логин SSH, наличие соответствующего публичного ключа на сервере и пароль ключа.",
friendlySshConnectionError("Auth fail", SshCredentials(privateKey = openSshKey))
)
}
@Test
fun generatedPemKeyCanBeLoadedByBundledJsch() {
val jsch = JSch()
val pair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048)
val output = ByteArrayOutputStream()
pair.writePrivateKey(output, "key-passphrase".toByteArray())
pair.dispose()
val privateKey = output.toString(Charsets.UTF_8.name())
assertNull(sshPrivateKeyIssue(privateKey))
JSch().addIdentity(
"test-key",
privateKey.toByteArray(),
null,
"key-passphrase".toByteArray()
)
}
@Test
fun optionalLocalSshIntegration() {
val port = System.getenv("WDTT_TEST_SSH_PORT")?.toIntOrNull()
val host = System.getenv("WDTT_TEST_SSH_HOST").orEmpty().ifBlank { "127.0.0.1" }
val user = System.getenv("WDTT_TEST_SSH_USER").orEmpty()
val keyFile = System.getenv("WDTT_TEST_SSH_KEY")?.let(::File)
val keyPassphrase = System.getenv("WDTT_TEST_SSH_KEY_PASSPHRASE").orEmpty()
assumeTrue(port != null && host.isNotBlank() && user.isNotBlank() && keyFile?.isFile == true)
val session = createSshSession(
host = host,
user = user,
credentials = SshCredentials(
privateKey = keyFile!!.readText(),
privateKeyPassphrase = keyPassphrase
),
port = port!!
)
try {
assertTrue(session.isConnected)
} finally {
session.disconnect()
}
}
}
@@ -56,25 +56,58 @@ class OutboundWireGuardTest {
assertTrue("sha256sum" in script) assertTrue("sha256sum" in script)
assertTrue("--accept-tos" in script) assertTrue("--accept-tos" in script)
assertTrue("wdtt-warp-watchdog.timer" in script) assertTrue("wdtt-warp-watchdog.timer" in script)
assertTrue("for attempt in 1 2 3" in script) assertTrue("wdtt_warp_autotune" in script)
assertTrue("WARP_ENDPOINT_CANDIDATES" in script)
assertTrue("engage.cloudflareclient.com:2408" in script)
assertTrue("rollback after WARP check error" in script)
assertShellSyntax(script) assertShellSyntax(script)
} }
@Test
fun serverDiagnosticsScript_hasPortableChecksAndValidShellSyntax() {
val script = serverDiagnosticsScript()
assertTrue("WDTT_SERVER_DIAG" in script)
assertTrue("apt-get dnf yum zypper apk pacman" in script)
assertTrue("wdtt_diag_install_dependencies" in script)
assertTrue("DEBIAN_FRONTEND=noninteractive apt-get install" in script)
assertTrue("dnf install -y" in script)
assertTrue("yum install -y" in script)
assertTrue("zypper --non-interactive install" in script)
assertTrue("apk add --no-cache" in script)
assertTrue("pacman -Sy --noconfirm --needed" in script)
assertTrue("systemctl" in script)
assertTrue("iptables" in script)
assertTrue("nft" in script)
assertTrue("VK / TURN-зависимости" in script)
assertTrue("api.vk.me" in script)
assertTrue("calls.okcdn.ru" in script)
assertTrue("api.telegram.org" in script)
assertTrue("Бесплатный WARP" in script)
assertTrue("engage.cloudflareclient.com" in script)
assertTrue("WDTT_EXPECTED_DTLS_PORT" in script)
assertTrue("wdtt_diag_udp_probe" in script)
assertTrue("/dev/net/tun" in script)
assertTrue("admin.sock" in script)
assertFalse("PrivateKey =" in script)
assertShellSyntax(script, shell = "sh")
}
@Test(expected = IllegalArgumentException::class) @Test(expected = IllegalArgumentException::class)
fun freeWarpScript_rejectsUnsafeMtu() { fun freeWarpScript_rejectsUnsafeMtu() {
buildFreeWarpInstallScript(1600) buildFreeWarpInstallScript(1600)
} }
private fun assertShellSyntax(script: String) { private fun assertShellSyntax(script: String, shell: String = "bash") {
val file = File.createTempFile("wdtt-warp-", ".sh") val file = File.createTempFile("wdtt-warp-", ".sh")
try { try {
file.writeText(script) file.writeText(script)
val process = ProcessBuilder("bash", "-n", file.absolutePath) val process = ProcessBuilder(shell, "-n", file.absolutePath)
.redirectErrorStream(true) .redirectErrorStream(true)
.start() .start()
val output = process.inputStream.bufferedReader().readText() val output = process.inputStream.bufferedReader().readText()
val code = process.waitFor() val code = process.waitFor()
assertTrue("bash -n завершился с кодом $code: $output", code == 0) assertTrue("$shell -n завершился с кодом $code: $output", code == 0)
} finally { } finally {
file.delete() file.delete()
} }
@@ -7,6 +7,28 @@ import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
class ServerClientsAccessTest { class ServerClientsAccessTest {
@Test
fun primaryServerAccessExplainsEveryLocalBlocker() {
val key = "-----BEGIN OPENSSH PRIVATE KEY-----\ndGVzdA==\n-----END OPENSSH PRIVATE KEY-----"
assertEquals(
"Укажите IP-адрес или домен сервера в верхнем блоке «Деплой».",
primaryServerSshAccessIssue("", false, "password", "", "", 22)
)
assertEquals(
"Укажите SSH-пароль.",
primaryServerSshAccessIssue("vpn.example.org", true, "password", "", "", 22)
)
assertEquals(
"Выбран вход по SSH-ключу — добавьте приватный SSH-ключ.",
primaryServerSshAccessIssue("vpn.example.org", true, "key", "sudo", "", 22)
)
assertEquals(
"Откройте «Секреты» и укажите корректный SSH-порт от 1 до 65535.",
primaryServerSshAccessIssue("vpn.example.org", true, "key", "", key, 0)
)
assertNull(primaryServerSshAccessIssue("vpn.example.org", true, "key", "", key, 22))
}
@Test @Test
fun accessRequiresDeployHostSshAndAdminPassword() { fun accessRequiresDeployHostSshAndAdminPassword() {
assertEquals( assertEquals(
@@ -18,9 +40,21 @@ class ServerClientsAccessTest {
serverClientsAccessIssue("https://bad host", false, "ssh", 22, "owner") serverClientsAccessIssue("https://bad host", false, "ssh", 22, "owner")
) )
assertEquals( assertEquals(
"Укажите SSH-пароль сервера в верхнем блоке «Деплой».", "Укажите SSH-пароль.",
serverClientsAccessIssue("vpn.example.org", true, "", 22, "owner") serverClientsAccessIssue("vpn.example.org", true, "", 22, "owner")
) )
assertEquals(
"Выбран вход по SSH-ключу — добавьте приватный SSH-ключ.",
serverClientsAccessIssue(
host = "vpn.example.org",
hostValid = true,
sshPassword = "sudo-password",
sshPort = 22,
mainPassword = "owner",
sshPrivateKey = "",
allowPasswordAuthentication = false
)
)
assertEquals( assertEquals(
"Укажите корректный SSH-порт от 1 до 65535.", "Укажите корректный SSH-порт от 1 до 65535.",
serverClientsAccessIssue("vpn.example.org", true, "ssh", 0, "owner") serverClientsAccessIssue("vpn.example.org", true, "ssh", 0, "owner")
@@ -30,6 +64,8 @@ class ServerClientsAccessTest {
serverClientsAccessIssue("vpn.example.org", true, "ssh", 22, "") serverClientsAccessIssue("vpn.example.org", true, "ssh", 22, "")
) )
assertNull(serverClientsAccessIssue("vpn.example.org", true, "ssh", 22, "owner")) assertNull(serverClientsAccessIssue("vpn.example.org", true, "ssh", 22, "owner"))
val key = "-----BEGIN OPENSSH PRIVATE KEY-----\ndGVzdA==\n-----END OPENSSH PRIVATE KEY-----"
assertNull(serverClientsAccessIssue("vpn.example.org", true, "", 22, "owner", key))
} }
@Test @Test