fix: ed25519 (BouncyCastle), безопасность WebView, гонки, хардненинг

- ed25519: замена net.i2p.eddsa на Bouncy Castle (mwiede/jsch 2.x), удаление мёртвой регистрации EdDSA-провайдера в App.kt
- SSHManager: единый addIdentity с нормализацией ключа и passphrase для executeWithStdin
- AppUpdater: проброс CancellationException, проверка HTTP-кода, disconnect и таймауты при скачивании
- SshRepository: устойчивый healthcheck (построчный поиск OK)
- SettingsViewModel: устранение lost-update в сеттерах (read-modify-write под mutex), applicationContext
- ServerViewModel/DI: applicationContext, явный androidContext() для ViewModels
- ProxyService: guard wakelock, типизированный startForeground в try/catch
- CaptchaWebViewDialog: cleanup WebView, COMPATIBILITY mixed-content, запрет file-access, whitelist схем, валидация URL
- MainActivity: запрос POST_NOTIFICATIONS на Android 13+
- Manifest: англоязычное описание specialUse FGS
This commit is contained in:
samosvalishe committed 2026-06-01 18:12:43 +03:00
1 parent c242647588
commit 0c22ef0a0b
17 files changed
+332 -157

No files matched your search

+1 -1
View File
@@ -54,7 +54,7 @@ kotlin {
dependencies {
implementation(libs.androidx.core.splashscreen)
implementation(libs.jsch)
implementation(libs.eddsa)
implementation(libs.bouncycastle)
implementation(libs.kotlinx.coroutines.android)
implementation(libs.androidx.security.crypto)
+6 -5
View File
@@ -9,11 +9,12 @@
-keep class com.jcraft.jsch.** { *; }
-dontwarn com.jcraft.jsch.**
# ── EdDSA (Ed25519) ───────────────────────────────────────────────────────────
# JSch обращается к net.i2p.crypto.eddsa через Security Provider (reflection).
# R8 стрипает эти классы в release → Ed25519-ключи не работают.
-keep class net.i2p.crypto.eddsa.** { *; }
-dontwarn net.i2p.crypto.eddsa.**
# ── Bouncy Castle (Ed25519 / curve25519 / chacha20) ───────────────────────────
# mwiede/jsch 2.x подгружает алгоритмы BC через reflection. R8 стрипает эти
# классы в release → Ed25519-ключи и современный KEX не работают.
-keep class org.bouncycastle.** { *; }
-dontwarn org.bouncycastle.**
-dontwarn javax.naming.**
# ── Kotlin Coroutines ─────────────────────────────────────────────────────────
-keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {}
+1 -1
View File
@@ -51,7 +51,7 @@
-->
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Поддержание активного сетевого прокси-соединения через TURN-серверы для обхода ограничений сети." />
android:value="Maintains an active local network proxy connection over TURN servers so the user can keep using a working tunnel while the app is in the background." />
</service>
<provider
+3 -6
View File
@@ -1,8 +1,6 @@
package com.freeturn.app
import android.app.Application
import net.i2p.crypto.eddsa.EdDSASecurityProvider
import java.security.Security
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
@@ -11,10 +9,9 @@ import com.freeturn.app.di.appModule
class App : Application() {
override fun onCreate() {
super.onCreate()
if (Security.getProvider("EdDSA") == null) {
Security.addProvider(EdDSASecurityProvider())
}
// ed25519/curve25519 обеспечивает Bouncy Castle на classpath — mwiede/jsch 2.x
// подхватывает его сам, регистрация Security-провайдера не нужна (старый
// net.i2p EdDSASecurityProvider jsch 2.x игнорировал, потому ed25519 не работал).
startKoin {
androidLogger()
androidContext(this@App)
@@ -1,10 +1,14 @@
package com.freeturn.app
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
@@ -22,12 +26,24 @@ class MainActivity : ComponentActivity() {
private val settingsViewModel: SettingsViewModel by viewModel()
private val requestNotificationPermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { }
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
super.onCreate(savedInstanceState)
splashScreen.setKeepOnScreenCondition { !settingsViewModel.isInitialized.value }
// На Android 13+ без POST_NOTIFICATIONS нотификация foreground-сервиса
// (статус прокси + кнопка Stop) не показывается. Запрашиваем при старте.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED
) {
requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
}
HapticUtil.perform(this, HapticUtil.Pattern.LAUNCH)
enableEdgeToEdge()
setContent {
@@ -13,10 +13,12 @@ import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.content.pm.ServiceInfo
import android.os.PowerManager
import android.os.SystemClock
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.ServiceCompat
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.DnsMode
import com.freeturn.app.data.Provider
@@ -131,7 +133,21 @@ class ProxyService : Service() {
}
}
currentBaseStatus = getString(R.string.notif_proxy_connecting)
startForeground(NOTIF_ID_FG, createNotification())
// Явно передаём FGS-тип (specialUse доступен с API 34; ниже — без типа).
// Оборачиваем в try/catch: ForegroundServiceStartNotAllowedException (API 31+
// при старте из фона) и InvalidForegroundServiceTypeException не должны
// ронять процесс.
val fgsType = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0
try {
ServiceCompat.startForeground(this, NOTIF_ID_FG, createNotification(), fgsType)
} catch (e: Exception) {
ProxyServiceState.addLog("Не удалось запустить foreground-сервис: ${e.message}")
ProxyServiceState.setStartupResult(StartupResult.Failed(e.message ?: "FGS start failed"))
ProxyServiceState.setRunning(false)
stopSelf()
return START_NOT_STICKY
}
// Если процесс ядра ещё жив — это повторный onStartCommand (например,
// sticky-рестарт). Не запускаем второй процесс, но требование о
@@ -146,6 +162,10 @@ class ProxyService : Service() {
restartCount.set(0)
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
// Освобождаем предыдущий wakelock перед созданием нового — иначе при
// повторном onStartCommand с уже мёртвым process старый объект остаётся
// held до GC (утечка wakelock).
if (wakeLock?.isHeld == true) wakeLock?.release()
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VkTurn::BgLock")
wakeLock?.acquire(TimeUnit.HOURS.toMillis(24))
@@ -42,15 +42,7 @@ class SSHManager {
var tempSession: Session? = null
try {
val jsch = JSch()
if (sshKey.isNotBlank()) {
// OpenSSH ed25519/RSA-ключи требуют LF и финального перевода строки —
// при вставке через Android-textfield/Windows может прилететь CRLF, и парсер
// OPENSSH PRIVATE KEY роняет ключ. Нормализуем перед addIdentity.
// Парольная фраза (если задана пользователем) приходит в pass-поле.
val keyBytes = normalizePrivateKey(sshKey)
val passphrase = pass.takeIf { it.isNotEmpty() }?.toByteArray(Charsets.UTF_8)
jsch.addIdentity("identity", keyBytes, null, passphrase)
}
if (sshKey.isNotBlank()) addKeyIdentity(jsch, sshKey, pass)
tempSession = jsch.getSession(user, ip, port)
if (sshKey.isBlank()) {
tempSession.setPassword(pass)
@@ -128,9 +120,7 @@ class SSHManager {
var tempSession: Session? = null
try {
val jsch = JSch()
if (sshKey.isNotBlank()) {
jsch.addIdentity("identity", sshKey.toByteArray(Charsets.UTF_8), null, null)
}
if (sshKey.isNotBlank()) addKeyIdentity(jsch, sshKey, pass)
tempSession = jsch.getSession(user, ip, port)
if (sshKey.isBlank()) tempSession.setPassword(pass)
tempSession.hostKeyRepository = tofu
@@ -179,6 +169,21 @@ class SSHManager {
}
}
/**
* Загружает приватный ключ в JSch для key-аутентификации.
*
* OpenSSH ed25519/RSA-ключи требуют LF и финального перевода строки — при вставке
* через Android-textfield/Windows может прилететь CRLF, и парсер OPENSSH PRIVATE KEY
* роняет ключ. Нормализуем перед addIdentity. Парольная фраза ключа (если он
* зашифрован) приходит в [pass]. Ed25519 требует Bouncy Castle на classpath
* (на Android нет Java 15 EdDSA) — см. libs.versions.toml.
*/
private fun addKeyIdentity(jsch: JSch, sshKey: String, pass: String) {
val keyBytes = normalizePrivateKey(sshKey)
val passphrase = pass.takeIf { it.isNotEmpty() }?.toByteArray(Charsets.UTF_8)
jsch.addIdentity("identity", keyBytes, null, passphrase)
}
private fun normalizePrivateKey(raw: String): ByteArray {
val lf = raw.replace("\r\n", "\n").replace("\r", "\n").trim()
val withTrailingNl = if (lf.endsWith("\n")) lf else "$lf\n"
@@ -9,6 +9,7 @@ import com.freeturn.app.viewmodel.ProxyViewModel
import com.freeturn.app.viewmodel.ServerViewModel
import com.freeturn.app.viewmodel.SettingsViewModel
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.androidx.viewmodel.dsl.viewModelOf
import org.koin.dsl.module
@@ -20,6 +21,8 @@ val appModule = module {
single { ProxyOrchestrator(get(), get(), get()) }
viewModelOf(::ProxyViewModel)
viewModelOf(::ServerViewModel)
viewModelOf(::SettingsViewModel)
// Context резолвим явно через androidContext() (Application), а не неявно из
// графа — VM сами сводят его к applicationContext.
viewModel { ServerViewModel(get(), get(), get(), androidContext()) }
viewModel { SettingsViewModel(get(), get(), get(), get(), get(), androidContext()) }
}
@@ -5,6 +5,7 @@ import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.content.FileProvider
import com.freeturn.app.viewmodel.UpdateState
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -59,6 +60,9 @@ class AppUpdater(private val context: Context) {
} else {
_state.value = UpdateState.NoUpdate
}
} catch (e: CancellationException) {
// Отмена корутины — штатный путь (structured concurrency), не ошибка сети.
throw e
} catch (_: Exception) {
_state.value = if (silent) UpdateState.Idle
else UpdateState.Error("Нет соединения с сервером")
@@ -76,28 +80,42 @@ class AppUpdater(private val context: Context) {
withContext(Dispatchers.IO) {
val connection = URL(url).openConnection() as HttpURLConnection
connection.instanceFollowRedirects = true
connection.connect()
connection.connectTimeout = 15_000
connection.readTimeout = 30_000
try {
connection.connect()
// Без проверки кода 404/HTML-страница редиректа запишется в update.apk
// и FileProvider отдаст мусор установщику.
if (connection.responseCode !in 200..299) {
throw java.io.IOException("HTTP ${connection.responseCode}")
}
val totalSize = connection.contentLength.toLong()
var downloaded = 0L
val totalSize = connection.contentLength.toLong()
var downloaded = 0L
connection.inputStream.use { input ->
apkFile.outputStream().use { output ->
val buffer = ByteArray(8192)
var bytesRead: Int
while (input.read(buffer).also { bytesRead = it } != -1) {
output.write(buffer, 0, bytesRead)
downloaded += bytesRead
if (totalSize > 0) {
_state.value = UpdateState.Downloading(
(downloaded * 100 / totalSize).toInt()
)
connection.inputStream.use { input ->
apkFile.outputStream().use { output ->
val buffer = ByteArray(8192)
var bytesRead: Int
while (input.read(buffer).also { bytesRead = it } != -1) {
output.write(buffer, 0, bytesRead)
downloaded += bytesRead
if (totalSize > 0) {
_state.value = UpdateState.Downloading(
(downloaded * 100 / totalSize).toInt()
)
}
}
}
}
} finally {
connection.disconnect()
}
}
_state.value = UpdateState.ReadyToInstall
} catch (e: CancellationException) {
apkFile.delete()
throw e
} catch (e: Exception) {
apkFile.delete()
_state.value = UpdateState.Error("Ошибка загрузки: ${e.message}")
@@ -85,7 +85,9 @@ class SshRepository(
suspend fun connectSsh(config: SshConfig): Pair<Boolean, String?> {
_sshState.value = SshConnectionState.Connecting
val result = runEcho(config)
return if (result.trim() == "OK") {
// Сравниваем построчно, а не весь вывод: серверный MOTD/banner или строки
// из .bashrc могут попасть в stdout перед "OK" и сломать строгое равенство.
return if (result.lines().any { it.trim() == "OK" }) {
val fp = sshManager.lastSeenFingerprint ?: config.hostFingerprint
activeSshConfig = config.copy(hostFingerprint = fp)
_sshState.value = SshConnectionState.Connected(config.ip)
@@ -8,6 +8,7 @@ package com.freeturn.app.ui.screens
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
@@ -22,6 +23,7 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -32,8 +34,12 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.core.net.toUri
import com.freeturn.app.R
/** Разрешённые схемы для топ-навигации внутри капча-WebView. */
private val ALLOWED_SCHEMES = setOf("http", "https")
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun CaptchaWebViewDialog(
@@ -74,53 +80,99 @@ fun CaptchaWebViewDialog(
)
}
) { padding ->
// URL приходит из лога ядра — грузим только http(s). javascript:/file:/
// data: в WebView с включённым JS исполнились бы в его контексте.
val isValidUrl = remember(captchaUrl) {
captchaUrl.toUri().scheme?.lowercase() in ALLOWED_SCHEMES
}
Box(
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
AndroidView(
factory = { ctx ->
WebView(ctx).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
if (!isValidUrl) {
LaunchedEffect(captchaUrl) { onDismiss() }
} else {
AndroidView(
factory = { ctx ->
WebView(ctx).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
useWideViewPort = true
loadWithOverviewMode = true
setSupportZoom(true)
builtInZoomControls = true
displayZoomControls = false
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
userAgentString = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36"
}
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
isLoading = true
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
useWideViewPort = true
loadWithOverviewMode = true
setSupportZoom(true)
builtInZoomControls = true
displayZoomControls = false
// Капча отдаётся ядром по http://localhost — COMPATIBILITY
// блокирует active mixed content, но не ломает поток.
// ALWAYS_ALLOW (было) открывал MITM.
mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
allowFileAccess = false
allowContentAccess = false
@Suppress("DEPRECATION")
allowFileAccessFromFileURLs = false
@Suppress("DEPRECATION")
allowUniversalAccessFromFileURLs = false
userAgentString = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36"
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
isLoading = false
webViewClient = object : WebViewClient() {
// Блокируем навигацию вне http(s): intent://, market://,
// tel:, javascript: и пр. — частые векторы редиректа.
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
val scheme = request?.url?.scheme?.lowercase()
return scheme !in ALLOWED_SCHEMES
}
@Deprecated("API < 24")
@Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
val scheme = url?.toUri()?.scheme?.lowercase()
return scheme !in ALLOWED_SCHEMES
}
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
isLoading = true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
isLoading = false
}
}
loadUrl(captchaUrl)
}
loadUrl(captchaUrl)
}
},
modifier = Modifier.fillMaxSize()
)
if (isLoading) {
CircularWavyProgressIndicator(
modifier = Modifier.align(Alignment.Center)
},
onRelease = { webView ->
// Без явной очистки WebView держит Activity-context и
// продолжает крутить JS/таймеры в фоне до GC.
webView.stopLoading()
webView.loadUrl("about:blank")
webView.clearHistory()
(webView.parent as? ViewGroup)?.removeView(webView)
webView.removeAllViews()
webView.destroy()
},
modifier = Modifier.fillMaxSize()
)
if (isLoading) {
CircularWavyProgressIndicator(
modifier = Modifier.align(Alignment.Center)
)
}
}
}
}
@@ -388,6 +388,20 @@ fun ClientSetupScreen(
)
}
// Bond — client-only флаг (сервер детектит сам). SSH не нужен;
// показываем только в TCP-форвард режиме.
if (effectiveTcpForward) {
SwitchRow(
label = stringResource(R.string.client_bond),
description = stringResource(R.string.client_bond_desc),
checked = saved.bond,
onCheckedChange = {
HapticUtil.perform(context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF)
settingsViewModel.setBond(it)
}
)
}
HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)
Text(
@@ -411,30 +425,38 @@ fun ClientSetupScreen(
val lockedHint = if (syncOn)
stringResource(R.string.locked_disconnect_hint) else null
SwitchRow(
label = stringResource(R.string.tcp_forward_mode),
description = lockedHint?.takeIf { !isSshConnected }
?: stringResource(R.string.tcp_forward_mode_desc),
checked = effectiveTcpForward,
enabled = controlsEnabled,
onCheckedChange = {
HapticUtil.perform(context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF)
settingsViewModel.setTcpForward(it)
// TCP-форвард — табы (UDP по умолчанию / TCP для проброса). Синхр. с сервером.
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Column {
Text(stringResource(R.string.tcp_forward_mode), style = MaterialTheme.typography.bodyMedium)
Text(
lockedHint?.takeIf { !isSshConnected }
?: stringResource(R.string.tcp_forward_mode_desc),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
)
// Bond — client-only флаг (сервер детектит сам). SSH не нужен;
// активен только в TCP-форвард режиме.
SwitchRow(
label = stringResource(R.string.client_bond),
description = stringResource(R.string.client_bond_desc),
checked = saved.bond,
enabled = effectiveTcpForward,
onCheckedChange = {
HapticUtil.perform(context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF)
settingsViewModel.setBond(it)
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
SegmentedButton(
selected = !effectiveTcpForward,
enabled = controlsEnabled,
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
settingsViewModel.setTcpForward(false)
},
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2)
) { Text(stringResource(R.string.udp)) }
SegmentedButton(
selected = effectiveTcpForward,
enabled = controlsEnabled,
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
settingsViewModel.setTcpForward(true)
},
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
) { Text(stringResource(R.string.tcp)) }
}
)
}
// Профиль обфускации — табы (как транспорт). Должен совпадать с сервером.
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -22,9 +22,12 @@ class ServerViewModel(
private val sshRepository: SshRepository,
private val prefs: AppPreferences,
private val orchestrator: ProxyOrchestrator,
private val context: Context
context: Context
) : ViewModel() {
// applicationContext: ViewModel переживает Activity — иначе утечка.
private val appContext = context.applicationContext
val sshState: StateFlow<SshConnectionState> = sshRepository.sshState
val serverState: StateFlow<ServerState> = sshRepository.serverState
val sshLog: StateFlow<List<String>> = sshRepository.sshLog
@@ -50,9 +53,9 @@ class ServerViewModel(
if (config.hostFingerprint.isEmpty() && fp != null) {
prefs.saveSshFingerprint(fp)
}
HapticUtil.perform(context, HapticUtil.Pattern.SUCCESS)
HapticUtil.perform(appContext, HapticUtil.Pattern.SUCCESS)
} else {
HapticUtil.perform(context, HapticUtil.Pattern.ERROR)
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
}
}
}
@@ -34,9 +34,13 @@ class SettingsViewModel(
private val sshRepository: SshRepository,
private val appUpdater: AppUpdater,
private val orchestrator: ProxyOrchestrator,
private val context: Context
context: Context
) : ViewModel() {
// ViewModel переживает пересоздание Activity — храним applicationContext,
// чтобы не утекала Activity.
private val appContext = context.applicationContext
val clientConfig: StateFlow<ClientConfig> = prefs.clientConfigFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ClientConfig())
@@ -107,59 +111,76 @@ class SettingsViewModel(
}
}
// Во всех сеттерах read-modify-write выполняется ВНУТРИ profileMutex: чтение
// current вне лока давало lost update — два параллельных сеттера читали один
// снапшот, затем по очереди писали свой copy(), и второй затирал первого.
fun setProvider(value: String) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.provider == value) return@launch
profileMutex.withLock { prefs.saveClientConfig(current.copy(provider = value)) }
profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.provider == value) return@withLock
prefs.saveClientConfig(current.copy(provider = value))
}
}
}
fun setDnsMode(value: String) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.dnsMode == value) return@launch
profileMutex.withLock { prefs.saveClientConfig(current.copy(dnsMode = value)) }
profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.dnsMode == value) return@withLock
prefs.saveClientConfig(current.copy(dnsMode = value))
}
}
}
fun setUseUdp(enabled: Boolean) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.useUdp == enabled) return@launch
profileMutex.withLock { prefs.saveClientConfig(current.copy(useUdp = enabled)) }
profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.useUdp == enabled) return@withLock
prefs.saveClientConfig(current.copy(useUdp = enabled))
}
}
}
fun setManualCaptcha(enabled: Boolean) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.manualCaptcha == enabled) return@launch
profileMutex.withLock { prefs.saveClientConfig(current.copy(manualCaptcha = enabled)) }
profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.manualCaptcha == enabled) return@withLock
prefs.saveClientConfig(current.copy(manualCaptcha = enabled))
}
}
}
fun setUseCarrierDns(enabled: Boolean) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.useCarrierDns == enabled) return@launch
profileMutex.withLock { prefs.saveClientConfig(current.copy(useCarrierDns = enabled)) }
profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.useCarrierDns == enabled) return@withLock
prefs.saveClientConfig(current.copy(useCarrierDns = enabled))
}
}
}
fun setDebugMode(enabled: Boolean) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.debugMode == enabled) return@launch
profileMutex.withLock { prefs.saveClientConfig(current.copy(debugMode = enabled)) }
profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.debugMode == enabled) return@withLock
prefs.saveClientConfig(current.copy(debugMode = enabled))
}
}
}
fun setMagicSwitch(enabled: Boolean) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.magicSwitch == enabled) return@launch
profileMutex.withLock { prefs.saveClientConfig(current.copy(magicSwitch = enabled)) }
profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.magicSwitch == enabled) return@withLock
prefs.saveClientConfig(current.copy(magicSwitch = enabled))
}
}
}
@@ -286,7 +307,7 @@ class SettingsViewModel(
private fun serverAddrToProfileName(serverAddr: String): String =
serverAddr.substringBefore(':').takeIf { it.isNotBlank() }
?: context.getString(com.freeturn.app.R.string.profile_default_name)
?: appContext.getString(com.freeturn.app.R.string.profile_default_name)
private fun uniqueProfileName(base: String, existing: List<Profile>, excludingId: String?): String {
val taken = existing
@@ -303,11 +324,13 @@ class SettingsViewModel(
// --- Server & Proxy Switches (TcpForward, Bond, Obf, Sync) ---
fun setBond(enabled: Boolean) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.bond == enabled) return@launch
val next = current.copy(bond = enabled)
profileMutex.withLock { prefs.saveClientConfig(next) }
orchestrator.restartProxyIfRunning()
val changed = profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.bond == enabled) return@withLock false
prefs.saveClientConfig(current.copy(bond = enabled))
true
}
if (changed) orchestrator.restartProxyIfRunning()
}
}
@@ -319,13 +342,16 @@ class SettingsViewModel(
val effectiveMatches = known?.obfProfile?.let { it == profile } ?: true
if (storedMatches && effectiveMatches) return@launch
val sync = prefs.clientConfigFlow.first().syncServerSwitches
var next = current.copy(obfProfile = profile)
if (profile != ObfProfile.NONE && next.obfKey.isBlank() && sync) {
val key = sshRepository.generateObfKey()
if (!key.isNullOrBlank()) next = next.copy(obfKey = key)
}
if (!storedMatches || next.obfKey != current.obfKey) {
profileMutex.withLock { prefs.saveServerOpts(next) }
// generateObfKey — сетевой SSH-вызов, не держим под profileMutex.
val generatedKey: String? =
if (profile != ObfProfile.NONE && current.obfKey.isBlank() && sync)
sshRepository.generateObfKey()?.takeIf { it.isNotBlank() }
else null
profileMutex.withLock {
val latest = prefs.serverOptsFlow.first()
var next = latest.copy(obfProfile = profile)
if (generatedKey != null && next.obfKey.isBlank()) next = next.copy(obfKey = generatedKey)
if (next != latest) prefs.saveServerOpts(next)
}
if (sync) orchestrator.restartServerIfRunning()
orchestrator.restartProxyIfRunning()
@@ -334,11 +360,13 @@ class SettingsViewModel(
fun setSyncServerSwitches(enabled: Boolean) {
viewModelScope.launch {
val current = prefs.clientConfigFlow.first()
if (current.syncServerSwitches == enabled) return@launch
val next = current.copy(syncServerSwitches = enabled)
profileMutex.withLock { prefs.saveClientConfig(next) }
if (enabled) {
val changed = profileMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.syncServerSwitches == enabled) return@withLock false
prefs.saveClientConfig(current.copy(syncServerSwitches = enabled))
true
}
if (changed && enabled) {
orchestrator.restartServerIfRunning()
orchestrator.restartProxyIfRunning()
}
@@ -347,11 +375,14 @@ class SettingsViewModel(
fun setObfKey(key: String) {
viewModelScope.launch {
val current = prefs.serverOptsFlow.first()
val trimmed = key.trim()
if (current.obfKey == trimmed) return@launch
val next = current.copy(obfKey = trimmed)
profileMutex.withLock { prefs.saveServerOpts(next) }
val changed = profileMutex.withLock {
val current = prefs.serverOptsFlow.first()
if (current.obfKey == trimmed) return@withLock false
prefs.saveServerOpts(current.copy(obfKey = trimmed))
true
}
if (!changed) return@launch
if (prefs.clientConfigFlow.first().syncServerSwitches) orchestrator.restartServerIfRunning()
orchestrator.restartProxyIfRunning()
}
@@ -365,8 +396,10 @@ class SettingsViewModel(
val effectiveMatches = known?.tcpMode?.let { it == enabled } ?: true
if (storedMatches && effectiveMatches) return@launch
if (!storedMatches) {
val next = current.copy(tcpForward = enabled)
profileMutex.withLock { prefs.saveClientConfig(next) }
profileMutex.withLock {
val latest = prefs.clientConfigFlow.first()
if (latest.tcpForward != enabled) prefs.saveClientConfig(latest.copy(tcpForward = enabled))
}
}
if (current.syncServerSwitches) {
val serverRunning = (sshRepository.serverState.value as? ServerState.Known)?.running == true
@@ -399,17 +432,17 @@ class SettingsViewModel(
fun resetAllSettings() {
viewModelScope.launch {
if (ProxyServiceState.isRunning.value) {
context.stopService(Intent(context, ProxyService::class.java))
appContext.stopService(Intent(appContext, ProxyService::class.java))
}
prefs.resetAll()
sshRepository.resetAll()
proxyManager.clearState()
ProxyServiceState.clearLogs()
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
val intent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(intent)
appContext.startActivity(intent)
}
}
}
Binary file not shown.
+1 -1
View File
@@ -114,7 +114,7 @@
<string name="listen_ip_desc">IP-адрес, к которому биндится сервер. 0.0.0.0 - все интерфейсы. Укажите конкретный WAN IP, если на хосте несколько адресов.</string>
<string name="turn_client_address">Адрес TURN‑клиента</string>
<string name="turn_client_placeholder">127.0.0.1:40537</string>
<string name="turn_client_desc">Локальный WireGuard/Hysteria-клиент на стороне сервера</string>
<string name="turn_client_desc">Локальный WireGuard/Xray-клиент на стороне сервера</string>
<string name="install">Установить / обновить</string>
<string name="server_install_cached">Актуально</string>
<string name="server_install_downloaded">Обновлено</string>
+5 -2
View File
@@ -13,7 +13,7 @@ coreSplashscreen = "1.2.0"
jsch = "2.28.0"
coroutinesAndroid = "1.10.2"
securityCrypto = "1.1.0"
eddsa = "0.3.0"
bouncycastle = "1.83"
koin = "3.5.6"
[libraries]
@@ -34,7 +34,10 @@ androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lif
androidx-core-splashscreen = { group = "androidx.core", name = "core-splashscreen", version.ref = "coreSplashscreen" }
androidx-security-crypto = { group = "androidx.security", name = "security-crypto", version.ref = "securityCrypto" }
jsch = { group = "com.github.mwiede", name = "jsch", version.ref = "jsch" }
eddsa = { group = "net.i2p.crypto", name = "eddsa", version.ref = "eddsa" }
# mwiede/jsch 2.x использует Bouncy Castle (не net.i2p.eddsa) для ed25519/ed448,
# curve25519-sha256 и chacha20-poly1305. На Android (нет Java 15 EdDSA) без него
# ed25519-ключи и современный KEX не работают.
bouncycastle = { group = "org.bouncycastle", name = "bcprov-jdk18on", version.ref = "bouncycastle" }
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutinesAndroid" }
koin-androidx-compose = { group = "io.insert-koin", name = "koin-androidx-compose", version.ref = "koin" }