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