diff --git a/app/src/main/java/com/freeturn/app/ProxyService.kt b/app/src/main/java/com/freeturn/app/ProxyService.kt index b2588ec..e006621 100644 --- a/app/src/main/java/com/freeturn/app/ProxyService.kt +++ b/app/src/main/java/com/freeturn/app/ProxyService.kt @@ -226,7 +226,7 @@ class ProxyService : Service() { // расходится с реально запускаемой. DNS оператора резолвим здесь (зависит от // активной сети) и передаём в билдер. val carrierDns = if (cfg.useCarrierDns) activeNetworkDnsServers() else null - cmdArgs.addAll(CoreArgs.client(cfg, srv, carrierDns)) + cmdArgs.addAll(CoreArgs.client(cfg, srv, carrierDns, prefs.ownClientId())) } var exitCode = -1 diff --git a/app/src/main/java/com/freeturn/app/data/AppPreferences.kt b/app/src/main/java/com/freeturn/app/data/AppPreferences.kt index 215ad96..03835fc 100644 --- a/app/src/main/java/com/freeturn/app/data/AppPreferences.kt +++ b/app/src/main/java/com/freeturn/app/data/AppPreferences.kt @@ -4,16 +4,23 @@ package com.freeturn.app.data import android.content.Context import androidx.datastore.core.DataStore +import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler import androidx.datastore.preferences.core.* import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import java.io.IOException import java.security.SecureRandom -private val Context.dataStore: DataStore by preferencesDataStore(name = "app_prefs") +// Битый файл переживаем с дефолтами: чтение/запись на пути старта туннеля +// (ownClientId, оркестратор) не должны ронять процесс. +private val Context.dataStore: DataStore by preferencesDataStore( + name = "app_prefs", + corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() } +) data class SshConfig( val ip: String = "", @@ -60,6 +67,17 @@ object ObfProfile { ByteArray(32).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) } } +/** Client ID (флаг -client-id ядра): авторизация по allowlist clients.json на сервере. */ +object ClientId { + private val ID_REGEX = Regex("^[0-9a-f]{32}$") + + /** Формат, который генерирует и валидирует приложение (16 байт → 32-hex, как автоген ядра). */ + fun isValid(id: String): Boolean = id.matches(ID_REGEX) + + fun generate(): String = + ByteArray(16).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) } +} + /** * Транспорт «туннельного приложения» поверх локального прокси. Пока единственный — * WireGuard (GoBackend): поднимает VPN-туннель, чей Endpoint указывает на localPort @@ -90,7 +108,7 @@ data class ClientConfig( val provider: String = Provider.VK, val threads: Int = 12, /** Соответствует флагу `-streams-per-cred` ядра. Дефолт ядра = 10, наш = 6. */ - val streamsPerCred: Int = 6, + val streamsPerCred: Int = DEFAULT_STREAMS_PER_CRED, /** TURN-транспорт UDP (-transport udp). false = TCP/TLS (дефолт ядра и наш). */ val useUdp: Boolean = false, val manualCaptcha: Boolean = false, @@ -133,7 +151,12 @@ data class ClientConfig( /** Список package-имён для include/exclude (разделители: запятая/пробел/перенос строки). */ val splitTunnelApps: String = "", /** Сбор логов ядра в UI. false = ProxyServiceState.addLog глотает строки. */ - val logsEnabled: Boolean = true + val logsEnabled: Boolean = true, + /** + * -client-id для этого сервера: у импортированного доступа — cid из share-ссылки + * (он в allowlist владельца). Пусто = общий ID устройства (свои серверы). + */ + val clientId: String = "" ) { /** WG реально активен только если выбран WG-транспорт и задан непустой конфиг. */ val wireGuardActive: Boolean @@ -141,6 +164,7 @@ data class ClientConfig( companion object { const val DEFAULT_LOCAL_PORT = "127.0.0.1:9000" + const val DEFAULT_STREAMS_PER_CRED = 6 } } @@ -153,6 +177,7 @@ class AppPreferences(context: Context) { val TG_SUBSCRIBE_SHOWN = booleanPreferencesKey("tg_subscribe_shown") val SERVERS_JSON = stringPreferencesKey("servers_json") val ACTIVE_SERVER_ID = stringPreferencesKey("active_server_id") + val OWN_CLIENT_ID = stringPreferencesKey("own_client_id") } /** DataStore-флоу: IOException (битый файл) → дефолты, остальное пробрасываем. */ @@ -313,6 +338,24 @@ class AppPreferences(context: Context) { context.dataStore.edit { prefs -> prefs[TG_SUBSCRIBE_SHOWN] = true } } + /** + * Постоянный Client ID устройства (-client-id владельца). Генерируется один раз; + * start-команда сервера сажает его в allowlist и включает -clients-file. + */ + suspend fun ownClientId(): String { + // Read-first: write-транзакция на пути старта туннеля нужна один раз за + // жизнь установки — когда ключа ещё нет. + val cur = prefFlow { it[OWN_CLIENT_ID] }.first() + if (cur != null && ClientId.isValid(cur)) return cur + var id = "" + context.dataStore.edit { prefs -> + val existing = prefs[OWN_CLIENT_ID] + id = if (existing != null && ClientId.isValid(existing)) existing + else ClientId.generate().also { prefs[OWN_CLIENT_ID] = it } + } + return id + } + /** Полный сброс настроек. */ suspend fun resetAll() { context.dataStore.edit { it.clear() } diff --git a/app/src/main/java/com/freeturn/app/data/CoreArgs.kt b/app/src/main/java/com/freeturn/app/data/CoreArgs.kt index 7e5bc75..61f1a82 100644 --- a/app/src/main/java/com/freeturn/app/data/CoreArgs.kt +++ b/app/src/main/java/com/freeturn/app/data/CoreArgs.kt @@ -7,7 +7,8 @@ package com.freeturn.app.data * * Возвращает аргументы БЕЗ имени бинарника. DNS оператора ([carrierDns]) резолвится * только в движке (зависит от активной сети); в UI передаём null — флаг -dns-servers - * (оператор) тогда опускается, он добавится лишь при реальном запуске. + * (оператор) тогда опускается, он добавится лишь при реальном запуске. [ownClientId] + * аналогично: ID устройства знает движок, UI передаёт null. */ object CoreArgs { @@ -15,6 +16,7 @@ object CoreArgs { cfg: ClientConfig, srv: ServerOpts, carrierDns: String? = null, + ownClientId: String? = null, ): List = buildList { add("-peer"); add(cfg.serverAddress) add("-provider"); add(cfg.provider) @@ -55,5 +57,9 @@ object CoreArgs { if (cfg.magicSwitch) { cfg.magicTurn.trim().takeIf { it.isNotEmpty() }?.let { add("-turn"); add(it) } } + // -client-id: cid из share-ссылки (импортированный доступ) либо общий ID + // устройства — сервер с -clients-file пускает только ID из allowlist. + val clientId = cfg.clientId.ifBlank { ownClientId.orEmpty() } + if (clientId.isNotBlank()) { add("-client-id"); add(clientId) } } } diff --git a/app/src/main/java/com/freeturn/app/data/Server.kt b/app/src/main/java/com/freeturn/app/data/Server.kt index e8467ac..a956adf 100644 --- a/app/src/main/java/com/freeturn/app/data/Server.kt +++ b/app/src/main/java/com/freeturn/app/data/Server.kt @@ -92,6 +92,7 @@ internal object ServerJson { put("splitTunnelMode", p.client.splitTunnelMode) put("splitTunnelApps", p.client.splitTunnelApps) put("logsEnabled", p.client.logsEnabled) + put("clientId", p.client.clientId) }) put("proxyListen", p.proxyListen) put("proxyConnect", p.proxyConnect) @@ -156,7 +157,8 @@ internal object ServerJson { if (it in SplitTunnelMode.VALUES) it else SplitTunnelMode.ALL }, splitTunnelApps = cliO.optString("splitTunnelApps"), - logsEnabled = cliO.optBoolean("logsEnabled", true) + logsEnabled = cliO.optBoolean("logsEnabled", true), + clientId = cliO.optString("clientId") ), proxyListen = o.optString("proxyListen").ifBlank { "0.0.0.0:56000" }, proxyConnect = o.optString("proxyConnect").ifBlank { "127.0.0.1:40537" }, diff --git a/app/src/main/java/com/freeturn/app/domain/ProxyOrchestrator.kt b/app/src/main/java/com/freeturn/app/domain/ProxyOrchestrator.kt index 3a9fdb9..583da98 100644 --- a/app/src/main/java/com/freeturn/app/domain/ProxyOrchestrator.kt +++ b/app/src/main/java/com/freeturn/app/domain/ProxyOrchestrator.kt @@ -25,7 +25,8 @@ class ProxyOrchestrator( listen = l, connect = c, tcpMode = tcpMode, obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", - obfKey = if (opts.obfEnabled) opts.obfKey else "" + obfKey = if (opts.obfEnabled) opts.obfKey else "", + clientId = prefs.ownClientId() ) } @@ -47,7 +48,8 @@ class ProxyOrchestrator( listen = l, connect = c, tcpMode = tcpMode, obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", - obfKey = if (opts.obfEnabled) opts.obfKey else "" + obfKey = if (opts.obfEnabled) opts.obfKey else "", + clientId = prefs.ownClientId() ) } } diff --git a/app/src/main/java/com/freeturn/app/domain/SshRepository.kt b/app/src/main/java/com/freeturn/app/domain/SshRepository.kt index 749fd3b..b398e8d 100644 --- a/app/src/main/java/com/freeturn/app/domain/SshRepository.kt +++ b/app/src/main/java/com/freeturn/app/domain/SshRepository.kt @@ -183,7 +183,8 @@ class SshRepository( connect: String, tcpMode: Boolean = false, obfProfile: String = "none", - obfKey: String = "" + obfKey: String = "", + clientId: String = "" ): Boolean { val cfg = activeSshConfig ?: return false if (cfg.ip.isEmpty()) return false @@ -197,7 +198,8 @@ class SshRepository( connect = connect, tcpMode = tcpMode, obfProfile = obfProfile, - obfKey = obfKey + obfKey = obfKey, + clientId = clientId ) ) ) diff --git a/app/src/main/java/com/freeturn/app/ui/screens/SettingsScreens.kt b/app/src/main/java/com/freeturn/app/ui/screens/SettingsScreens.kt index 416dad6..cfb17ce 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/SettingsScreens.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/SettingsScreens.kt @@ -1099,7 +1099,7 @@ private fun LaunchParamBlock(label: String, commandLine: String) { } /** Флаги клиента (-flag value), значение которых прячем под privacyMode. */ -private val CLIENT_SECRET_FLAGS = setOf("-peer", "-link", "-obf-key", "-turn") +private val CLIENT_SECRET_FLAGS = setOf("-peer", "-link", "-obf-key", "-turn", "-client-id") /** Командная строка клиентского ядра (как в движке) с маской секретов. */ private fun clientCommandLine(server: Server, privacy: Boolean): String { diff --git a/app/src/main/java/com/freeturn/app/viewmodel/ErrorText.kt b/app/src/main/java/com/freeturn/app/viewmodel/ErrorText.kt new file mode 100644 index 0000000..61fd93b --- /dev/null +++ b/app/src/main/java/com/freeturn/app/viewmodel/ErrorText.kt @@ -0,0 +1,8 @@ +package com.freeturn.app.viewmodel + +import android.content.Context +import com.freeturn.app.R + +/** Текст ошибки для UI: message исключения либо общий фоллбэк из ресурсов. */ +fun Throwable.uiMessage(context: Context): String = + message?.takeIf { it.isNotBlank() } ?: context.getString(R.string.error_ssh_generic) diff --git a/app/src/main/java/com/freeturn/app/viewmodel/ServerSetupViewModel.kt b/app/src/main/java/com/freeturn/app/viewmodel/ServerSetupViewModel.kt index f19694b..d85ce2b 100644 --- a/app/src/main/java/com/freeturn/app/viewmodel/ServerSetupViewModel.kt +++ b/app/src/main/java/com/freeturn/app/viewmodel/ServerSetupViewModel.kt @@ -231,7 +231,7 @@ class ServerSetupViewModel( .onFailure { e -> HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR) _uiState.update { - it.copy(checkingSsh = false, sshError = e.message ?: "SSH error") + it.copy(checkingSsh = false, sshError = e.uiMessage(appContext)) } } } @@ -323,7 +323,10 @@ class ServerSetupViewModel( connect = "127.0.0.1:$backendPort", tcpMode = !c.vpnMode && c.backendTcp, obfProfile = c.obfProfile, - obfKey = if (obfOn) obfKey else "" + obfKey = if (obfOn) obfKey else "", + // Авторизация по allowlist с первого запуска: владелец сидится + // в clients.json, сервер стартует с -clients-file. + clientId = prefs.ownClientId() ) ).onFailure { fail(it.message); return@launch } advance() diff --git a/app/src/main/java/com/freeturn/app/viewmodel/ServerViewModel.kt b/app/src/main/java/com/freeturn/app/viewmodel/ServerViewModel.kt index 21a468a..4782a06 100644 --- a/app/src/main/java/com/freeturn/app/viewmodel/ServerViewModel.kt +++ b/app/src/main/java/com/freeturn/app/viewmodel/ServerViewModel.kt @@ -118,7 +118,8 @@ class ServerViewModel( listen = l, connect = c, tcpMode = tcpMode, obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", - obfKey = if (opts.obfEnabled) opts.obfKey else "" + obfKey = if (opts.obfEnabled) opts.obfKey else "", + clientId = prefs.ownClientId() ) } }