Proxy TLS trust UI and isolated connectivity checks

Show certificate issues in proxy checks, prompt to trust with persistent or
session-only pins, and add trusted-certificate management. Isolate health
checks from the active route and remove the App settings category label.

Co-authored-by: denis0001-dev <denis0001.dev@ya.ru>
This commit is contained in:
Cursor Agent
2026-11-11 18:35:17 +00:00
Unverified
parent 86203db53c
commit 56e576a58e
22 changed files with 754 additions and 15 deletions
@@ -18,7 +18,11 @@ actual fun createPlatformHttpClient(
connectTimeoutMillis = 5_000
socketTimeoutMillis = 30_000
}
val route = proxyRoute ?: ProxyRuntime.currentRoute
val route = when {
proxyRoute != null -> proxyRoute
ProxyRuntime.probeIsolation -> ProxyRoute.Direct
else -> ProxyRuntime.currentRoute
}
configureEngineProxy(this, route)
block()
}
@@ -7,6 +7,7 @@ import java.net.InetSocketAddress
import java.net.Proxy
actual fun configureEngineProxy(config: HttpClientConfig<*>, route: ProxyRoute) {
configureEngineTls(config)
val javaProxy = when (route) {
ProxyRoute.Direct, ProxyRoute.System -> return
is ProxyRoute.Custom -> when (route.endpointType) {
@@ -0,0 +1,62 @@
package ru.fromchat.network.proxy
import io.ktor.client.HttpClientConfig
import io.ktor.client.engine.okhttp.OkHttpConfig
import ru.fromchat.config.ServerConfig
import java.security.KeyStore
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.Base64
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
actual fun configureEngineTls(config: HttpClientConfig<*>) {
val trustManager = androidProxyPinningTrustManager()
val sslContext = SSLContext.getInstance("TLS").apply {
init(null, arrayOf(trustManager), null)
}
config.engine {
(this as? OkHttpConfig)?.config {
sslSocketFactory(sslContext.socketFactory, trustManager)
}
}
}
actual suspend fun fetchPeerCertificatePem(route: ProxyRoute): String? = null
private fun androidProxyPinningTrustManager(): X509TrustManager {
val delegate = defaultAndroidTrustManager()
val apiHost = tlsHostFromUrl(ServerConfig.apiBaseUrl)
return object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
delegate.checkClientTrusted(chain, authType)
}
override fun getAcceptedIssuers(): Array<X509Certificate> = delegate.acceptedIssuers
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
try {
delegate.checkServerTrusted(chain, authType)
} catch (e: CertificateException) {
val leaf = chain?.firstOrNull() ?: throw e
val pem = androidCertificateToPem(leaf)
if (ProxyTlsTrust.extraPemForHost(apiHost).any { it.trim() == pem.trim() }) {
return
}
throw e
}
}
}
}
private fun defaultAndroidTrustManager(): X509TrustManager {
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
factory.init(null as KeyStore?)
return factory.trustManagers.filterIsInstance<X509TrustManager>().first()
}
private fun androidCertificateToPem(certificate: X509Certificate): String {
val encoded = Base64.getMimeEncoder(64, "\n".toByteArray()).encodeToString(certificate.encoded)
return "-----BEGIN CERTIFICATE-----\n$encoded\n-----END CERTIFICATE-----"
}
@@ -357,6 +357,14 @@
<string name="proxy_delete">Удалить</string>
<string name="proxy_ping_ms">%1$d мс</string>
<string name="proxy_check_failed">Недоступно</string>
<string name="proxy_certificate_issue">Проблема с сертификатом</string>
<string name="proxy_trust_cert_title">Доверять этому сертификату?</string>
<string name="proxy_trust_cert_body">TLS-сертификат сервера не подписан доверенным центром. Продолжайте только если узнаёте этот сервер.</string>
<string name="proxy_trust_yes">Да</string>
<string name="proxy_trust_once">Только сейчас</string>
<string name="proxy_trusted_certs_title">Доверенные сертификаты</string>
<string name="proxy_trusted_certs_empty">Нет сохранённых доверенных сертификатов</string>
<string name="proxy_trusted_certs_manage">Доверенные сертификаты</string>
<string name="proxy_screen_subtitle">Как FromChat подключается к серверу по защищённому каналу.</string>
<string name="proxy_step_type_title">Тип прокси</string>
<string name="proxy_step_type_body">HTTP, SOCKS5 или SSH-туннель как SOCKS.</string>
@@ -388,6 +388,14 @@
<string name="proxy_delete">Delete</string>
<string name="proxy_ping_ms">%1$d ms</string>
<string name="proxy_check_failed">Unreachable</string>
<string name="proxy_certificate_issue">Certificate issue</string>
<string name="proxy_trust_cert_title">Trust this certificate?</string>
<string name="proxy_trust_cert_body">The server TLS certificate is not signed by a trusted authority. Only continue if you recognize this server.</string>
<string name="proxy_trust_yes">Yes</string>
<string name="proxy_trust_once">This time only</string>
<string name="proxy_trusted_certs_title">Trusted certificates</string>
<string name="proxy_trusted_certs_empty">No trusted certificates saved</string>
<string name="proxy_trusted_certs_manage">Trusted certificates</string>
<string name="proxy_screen_subtitle">Choose how FromChat reaches your server over an encrypted link.</string>
<string name="proxy_step_type_title">Proxy type</string>
<string name="proxy_step_type_body">HTTP, SOCKS5, or an SSH tunnel that acts like SOCKS.</string>
@@ -7,6 +7,7 @@ import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import ru.fromchat.api.ApiClient
import ru.fromchat.api.createProbeHttpClient
import ru.fromchat.api.schema.server.ServerInstanceIdResponse
import ru.fromchat.config.ServerConfig
@@ -76,11 +77,16 @@ object ProxyChecker {
}
}
private suspend fun checkWithRoute(route: ProxyRoute): ProxyCheckResult {
private suspend fun checkWithRoute(route: ProxyRoute): ProxyCheckResult =
ProxyRuntime.withProbeIsolation {
performCheckWithRoute(route)
}
private suspend fun performCheckWithRoute(route: ProxyRoute): ProxyCheckResult {
val mark = TimeSource.Monotonic.markNow()
val base = ServerConfig.apiBaseUrl.trimEnd('/')
val client = createProbeHttpClient(proxyRoute = route, bypassHttpProxyForCalls = false)
return try {
val base = ServerConfig.apiBaseUrl.trimEnd('/')
val instanceId = client.get("$base/instance_id").body<ServerInstanceIdResponse>().instanceId.trim()
if (instanceId.isEmpty()) {
ProxyCheckResult.Failed("Empty instance id")
@@ -91,9 +97,46 @@ object ProxyChecker {
)
}
} catch (e: Exception) {
ProxyCheckResult.Failed(e.message)
if (e.isCertificateError()) {
val host = tlsHostFromUrl(base)
val pem = fetchPeerCertificatePem(route).orEmpty()
if (pem.isNotEmpty() && ProxyTlsTrust.hasTrustForPem(host, pem)) {
client.close()
val retryClient = createProbeHttpClient(proxyRoute = route, bypassHttpProxyForCalls = false)
return try {
val instanceId = retryClient.get("$base/instance_id").body<ServerInstanceIdResponse>()
.instanceId.trim()
if (instanceId.isEmpty()) {
ProxyCheckResult.Failed("Empty instance id")
} else {
ProxyCheckResult.Success(
pingMs = mark.elapsedNow().inWholeMilliseconds.toInt(),
instanceId = instanceId,
)
}
} catch (retry: Exception) {
if (retry.isCertificateError()) {
ProxyCheckResult.CertificateIssue(
pem = pem,
detail = retry.message,
)
} else {
ProxyCheckResult.Failed(retry.message)
}
} finally {
retryClient.close()
}
}
ProxyCheckResult.CertificateIssue(pem = pem, detail = e.message)
} else {
ProxyCheckResult.Failed(e.message)
}
} finally {
client.close()
}
}
fun notifyTlsTrustChanged() {
ApiClient.rebuildHttpClients()
}
}
@@ -85,4 +85,5 @@ sealed class ProxyCheckResult {
data object Checking : ProxyCheckResult()
data class Success(val pingMs: Int, val instanceId: String) : ProxyCheckResult()
data class Failed(val reason: String? = null) : ProxyCheckResult()
data class CertificateIssue(val pem: String, val detail: String? = null) : ProxyCheckResult()
}
@@ -8,6 +8,18 @@ import kotlinx.coroutines.sync.withLock
import ru.fromchat.api.ApiClient
object ProxyRuntime {
@Volatile
var probeIsolation: Boolean = false
suspend fun <T> withProbeIsolation(block: suspend () -> T): T {
probeIsolation = true
try {
return block()
} finally {
probeIsolation = false
}
}
private val applyMutex = Mutex()
private val _selection = MutableStateFlow<ProxySelection>(ProxySelection.Direct)
@@ -43,6 +55,9 @@ object ProxyRuntime {
suspend fun applySelection(selection: ProxySelection) {
applyMutex.withLock {
stopSshTunnel()
if (_selection.value != selection) {
ProxyTlsTrust.clearSession()
}
_selection.value = selection
ProxyStore.setSelection(selection)
refreshEffectiveRoute(startTunnel = true)
@@ -169,7 +184,7 @@ object ProxyRuntime {
}
suspend fun routeForCheckTarget(target: ProxyCheckTarget): ProxyRoute? = when (target) {
ProxyCheckTarget.ActiveSelection -> currentRoute
ProxyCheckTarget.ActiveSelection -> ProxyRoute.Direct
is ProxyCheckTarget.SavedProxyById -> {
val proxy = ProxyStore.readProxies().firstOrNull { it.id == target.id } ?: return null
ephemeralRouteForProxy(proxy)
@@ -0,0 +1,7 @@
package ru.fromchat.network.proxy
import io.ktor.client.HttpClientConfig
expect fun configureEngineTls(config: HttpClientConfig<*>)
expect suspend fun fetchPeerCertificatePem(route: ProxyRoute): String?
@@ -0,0 +1,22 @@
package ru.fromchat.network.proxy
fun Throwable.isCertificateError(): Boolean {
var cur: Throwable? = this
while (cur != null) {
val name = cur::class.simpleName.orEmpty()
val msg = cur.message.orEmpty()
if (
name.contains("Cert", ignoreCase = true) ||
name.contains("SSL", ignoreCase = true) ||
name.contains("TLS", ignoreCase = true) ||
msg.contains("certificate", ignoreCase = true) ||
msg.contains("CertPath", ignoreCase = true) ||
msg.contains("handshake", ignoreCase = true) ||
msg.contains("PKIX", ignoreCase = true)
) {
return true
}
cur = cur.cause
}
return false
}
@@ -0,0 +1,120 @@
package ru.fromchat.network.proxy
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.Json
import ru.fromchat.api.local.AttachmentMediaLog
import ru.fromchat.utils.settings.Settings as PlatformSettings
@Serializable
data class TrustedTlsCertificate(
val id: String,
val host: String,
val label: String,
val pem: String,
val addedAtEpochMs: Long = 0,
)
object ProxyTlsTrust {
private const val STORE_KEY = "proxy_trusted_certs_v1"
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
private val listSerializer = ListSerializer(TrustedTlsCertificate.serializer())
private val settings = PlatformSettings()
@Volatile
var sessionHost: String? = null
private set
@Volatile
var sessionPem: String? = null
private set
fun clearSession() {
sessionHost = null
sessionPem = null
}
fun trustThisSession(host: String, pem: String) {
sessionHost = host.trim()
sessionPem = pem.trim()
}
fun trustPersistently(host: String, label: String, pem: String) {
runBlocking {
trustPersistentlySuspend(host, label, pem)
}
}
suspend fun trustPersistentlySuspend(host: String, label: String, pem: String) {
withContext(Dispatchers.IO) {
val trimmedHost = host.trim()
val trimmedPem = pem.trim()
val id = certId(trimmedHost, trimmedPem)
val list = readPersisted().toMutableList()
list.removeAll { it.id == id || (it.host == trimmedHost && it.pem == trimmedPem) }
list.add(
TrustedTlsCertificate(
id = id,
host = trimmedHost,
label = label.trim(),
pem = trimmedPem,
addedAtEpochMs = AttachmentMediaLog.nowMs(),
),
)
savePersisted(list)
}
}
fun removePersisted(id: String) {
runBlocking {
withContext(Dispatchers.IO) {
savePersisted(readPersisted().filterNot { it.id == id })
}
}
}
fun loadPersisted(): List<TrustedTlsCertificate> = runBlocking { readPersisted() }
suspend fun readPersisted(): List<TrustedTlsCertificate> = withContext(Dispatchers.IO) {
val raw = settings.getString(STORE_KEY, "")
if (raw.isBlank()) return@withContext emptyList()
runCatching {
json.decodeFromString(listSerializer, raw)
}.getOrDefault(emptyList())
}
fun extraPemForHost(host: String): List<String> {
val h = host.trim()
val persisted = loadPersisted().filter { it.host.equals(h, ignoreCase = true) }.map { it.pem }
val session = if (sessionHost.equals(h, ignoreCase = true)) {
sessionPem?.let { listOf(it) } ?: emptyList()
} else {
emptyList()
}
return (persisted + session).distinct()
}
fun hasTrustForPem(host: String, pem: String?): Boolean {
if (pem.isNullOrBlank()) return false
val normalized = pem.trim()
return extraPemForHost(host).any { it.trim() == normalized }
}
private suspend fun savePersisted(list: List<TrustedTlsCertificate>) {
settings.putString(STORE_KEY, json.encodeToString(listSerializer, list))
}
private fun certId(host: String, pem: String): String =
"${host.lowercase()}_${pem.hashCode().toUInt().toString(16)}"
}
fun tlsHostFromUrl(url: String): String =
url.trim()
.removePrefix("https://")
.removePrefix("http://")
.substringBefore('/')
.substringBefore(':')
@@ -33,6 +33,7 @@ import ru.fromchat.ui.main.settings.account.changeyandex.ChangeYandexOAuthScreen
import ru.fromchat.ui.main.settings.account.delete.DeleteAccountScreen
import ru.fromchat.ui.main.settings.proxy.AddProxyFlowScreen
import ru.fromchat.ui.main.settings.proxy.ProxyScreen
import ru.fromchat.ui.main.settings.proxy.TrustedCertificatesScreen
import ru.fromchat.ui.main.settings.server.ServerConfigScreen
import ru.fromchat.ui.main.desktop.detailPaneShowBackButton
import ru.fromchat.ui.profile.EditProfileFocusField
@@ -304,6 +305,17 @@ fun NavGraphBuilder.settingsDetailDestinations(
launchSingleTop = true
}
},
onManageTrustedCerts = {
navController.navigate(SettingsRoutes.ProxyTrustedCerts) {
launchSingleTop = true
}
},
)
}
composable(SettingsRoutes.ProxyTrustedCerts) {
TrustedCertificatesScreen(
onBack = { navController.navigateUp() },
)
}
@@ -22,4 +22,5 @@ object SettingsRoutes {
const val Logs = "settings/logs"
const val LogFiles = "settings/logs/files"
const val ProxyAdd = "settings/proxy/add"
const val ProxyTrustedCerts = "settings/proxy/trusted-certs"
}
@@ -196,7 +196,6 @@ fun SettingsTab() {
Category(
Modifier.padding(top = 8.dp),
title = stringResource(Res.string.settings_category_app),
) {
ExpressiveListItem(
icon = Icons.Rounded.Info,
@@ -53,15 +53,19 @@ import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import ru.fromchat.Res
import ru.fromchat.config.ServerConfig
import ru.fromchat.network.proxy.ProxyCheckResult
import ru.fromchat.network.proxy.ProxyChecker
import ru.fromchat.network.proxy.ProxyCheckTarget
import ru.fromchat.network.proxy.ProxyRuntime
import ru.fromchat.network.proxy.ProxySelection
import ru.fromchat.network.proxy.ProxyTlsTrust
import ru.fromchat.network.proxy.ProxyType
import ru.fromchat.network.proxy.SavedProxy
import ru.fromchat.network.proxy.systemProxyAvailable
import ru.fromchat.network.proxy.tlsHostFromUrl
import ru.fromchat.proxy_add
import ru.fromchat.proxy_certificate_issue
import ru.fromchat.proxy_check_failed
import ru.fromchat.proxy_checking
import ru.fromchat.proxy_custom_proxies
@@ -74,7 +78,11 @@ import ru.fromchat.proxy_system_proxy
import ru.fromchat.proxy_type_http
import ru.fromchat.proxy_type_socks
import ru.fromchat.proxy_type_ssh
import ru.fromchat.proxy_trusted_certs_manage
import ru.fromchat.settings_proxy_title
import ru.fromchat.ui.components.ExpressiveListItem
import ru.fromchat.ui.components.ExpressiveTints
import androidx.compose.material.icons.rounded.VerifiedUser
import ru.fromchat.ui.components.Text
import ru.fromchat.ui.main.settings.SettingsDetailTopBar
import ru.fromchat.ui.main.settings.rememberSettingsCollapsingScrollBehavior
@@ -89,6 +97,12 @@ import ru.fromchat.utils.conditional
private val ProxyPingSuccessColor = Color(0xFF2E7D32)
private data class PendingCertTrust(
val selection: ProxySelection,
val pem: String,
val label: String,
)
@OptIn(
ExperimentalMaterial3Api::class,
ExperimentalMaterial3ExpressiveApi::class,
@@ -98,6 +112,7 @@ private val ProxyPingSuccessColor = Color(0xFF2E7D32)
fun ProxyScreen(
onBack: () -> Unit,
onAddProxy: () -> Unit,
onManageTrustedCerts: () -> Unit,
) {
val scope = rememberCoroutineScope()
val useCollapsing = settingsDetailUseCollapsingTopBar()
@@ -115,6 +130,8 @@ fun ProxyScreen(
var addSheetOpen by remember { mutableStateOf(false) }
var editingProxy by remember { mutableStateOf<SavedProxy?>(null) }
var pendingCertTrust by remember { mutableStateOf<PendingCertTrust?>(null) }
val apiHost = remember { tlsHostFromUrl(ServerConfig.apiBaseUrl) }
suspend fun runConnectivityChecks() {
directCheck = ProxyCheckResult.Checking
@@ -149,6 +166,18 @@ fun ProxyScreen(
runConnectivityChecks()
}
fun certPemFrom(result: ProxyCheckResult?): String? =
(result as? ProxyCheckResult.CertificateIssue)?.pem?.takeIf { it.isNotBlank() }
fun requestSelection(selection: ProxySelection, check: ProxyCheckResult?, label: String) {
val pem = certPemFrom(check)
if (pem != null && !ProxyTlsTrust.hasTrustForPem(apiHost, pem)) {
pendingCertTrust = PendingCertTrust(selection = selection, pem = pem, label = label)
return
}
scope.launch { ProxyRuntime.applySelection(selection) }
}
LaunchedEffect(savedProxies) {
savedProxies.forEach { proxy ->
if (proxy.id !in customChecks) {
@@ -243,7 +272,18 @@ fun ProxyScreen(
}
item {
Category(margin = PaddingValues(horizontal = 16.dp)) {
Category(margin = PaddingValues(start = 16.dp, end = 16.dp, bottom = 8.dp)) {
ExpressiveListItem(
icon = Icons.Rounded.VerifiedUser,
iconPreset = ExpressiveTints.Cyan,
headline = stringResource(Res.string.proxy_trusted_certs_manage),
onClick = onManageTrustedCerts,
)
}
}
item {
Category(margin = PaddingValues(start = 16.dp, end = 16.dp)) {
ProxySelectionRow(
headline = stringResource(Res.string.proxy_direct_connection),
selected = selection is ProxySelection.Direct,
@@ -253,7 +293,7 @@ fun ProxyScreen(
divider = systemProxyEnabled,
containerColor = scheme.surfaceContainer,
onSelect = {
scope.launch { ProxyRuntime.applySelection(ProxySelection.Direct) }
requestSelection(ProxySelection.Direct, directCheck, apiHost)
},
)
if (systemProxyEnabled) {
@@ -266,7 +306,7 @@ fun ProxyScreen(
divider = false,
containerColor = scheme.surfaceContainer,
onSelect = {
scope.launch { ProxyRuntime.applySelection(ProxySelection.System) }
requestSelection(ProxySelection.System, systemCheck, apiHost)
},
)
}
@@ -334,9 +374,11 @@ fun ProxyScreen(
position = listItemPositionInGroup(index, sortedProxies.size),
groupItemCount = sortedProxies.size,
onClick = {
scope.launch {
ProxyRuntime.applySelection(ProxySelection.Custom(proxy.id))
}
requestSelection(
ProxySelection.Custom(proxy.id),
check,
proxy.label,
)
},
contextMenu = {
item(Icons.Rounded.Edit, editProxyLabel) {
@@ -349,6 +391,31 @@ fun ProxyScreen(
}
}
ProxyTrustCertificateDialog(
visible = pendingCertTrust != null,
onDismiss = { pendingCertTrust = null },
onTrustPermanent = {
val pending = pendingCertTrust ?: return@ProxyTrustCertificateDialog
ProxyTlsTrust.trustPersistently(apiHost, pending.label, pending.pem)
ProxyChecker.notifyTlsTrustChanged()
pendingCertTrust = null
scope.launch {
ProxyRuntime.applySelection(pending.selection)
runConnectivityChecks()
}
},
onTrustSession = {
val pending = pendingCertTrust ?: return@ProxyTrustCertificateDialog
ProxyTlsTrust.trustThisSession(apiHost, pending.pem)
ProxyChecker.notifyTlsTrustChanged()
pendingCertTrust = null
scope.launch {
ProxyRuntime.applySelection(pending.selection)
runConnectivityChecks()
}
},
)
if (addSheetOpen && editingProxy != null) {
val sheetState = rememberBottomSheetState(
initialValue = SheetValue.Expanded,
@@ -471,6 +538,14 @@ private fun ProxyCheckStatusText(result: ProxyCheckResult) {
color = scheme.error,
)
}
is ProxyCheckResult.CertificateIssue -> {
Text(
text = stringResource(Res.string.proxy_certificate_issue),
style = MaterialTheme.typography.bodyMedium,
color = scheme.error,
)
}
}
}
}
@@ -0,0 +1,88 @@
package ru.fromchat.ui.main.settings.proxy
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Lock
import androidx.compose.material3.BasicAlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import ru.fromchat.Res
import ru.fromchat.proxy_trust_cert_body
import ru.fromchat.proxy_trust_cert_title
import ru.fromchat.proxy_trust_once
import ru.fromchat.proxy_trust_yes
import ru.fromchat.ui.components.Text
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun ProxyTrustCertificateDialog(
visible: Boolean,
onDismiss: () -> Unit,
onTrustPermanent: () -> Unit,
onTrustSession: () -> Unit,
) {
if (!visible) return
val scheme = MaterialTheme.colorScheme
BasicAlertDialog(onDismissRequest = onDismiss) {
Surface(
shape = MaterialTheme.shapes.extraLarge,
color = scheme.surfaceContainerHigh,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp, vertical = 28.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Icon(
imageVector = Icons.Rounded.Lock,
contentDescription = null,
modifier = Modifier.size(56.dp),
tint = scheme.primary,
)
Spacer(Modifier.height(16.dp))
Text(
text = stringResource(Res.string.proxy_trust_cert_title),
style = MaterialTheme.typography.headlineSmall,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(8.dp))
Text(
text = stringResource(Res.string.proxy_trust_cert_body),
style = MaterialTheme.typography.bodyLarge,
color = scheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(24.dp))
Button(
onClick = onTrustPermanent,
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(Res.string.proxy_trust_yes))
}
TextButton(
onClick = onTrustSession,
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(Res.string.proxy_trust_once))
}
}
}
}
}
@@ -0,0 +1,143 @@
package ru.fromchat.ui.main.settings.proxy
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import ru.fromchat.Res
import ru.fromchat.network.proxy.ProxyChecker
import ru.fromchat.network.proxy.ProxyTlsTrust
import ru.fromchat.network.proxy.TrustedTlsCertificate
import ru.fromchat.proxy_delete
import ru.fromchat.proxy_trusted_certs_empty
import ru.fromchat.proxy_trusted_certs_title
import ru.fromchat.ui.components.Text
import ru.fromchat.ui.main.settings.SettingsDetailTopBar
import ru.fromchat.ui.main.settings.rememberSettingsCollapsingScrollBehavior
import ru.fromchat.ui.main.settings.rememberSettingsDetailHazeState
import ru.fromchat.ui.main.settings.settingsDetailHazeSource
import ru.fromchat.ui.main.settings.settingsDetailUseCollapsingTopBar
import ru.fromchat.utils.components.ListItem
import ru.fromchat.utils.components.listItemPositionInGroup
import ru.fromchat.utils.conditional
import androidx.compose.ui.input.nestedscroll.nestedScroll
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TrustedCertificatesScreen(
onBack: () -> Unit,
) {
val useCollapsing = settingsDetailUseCollapsingTopBar()
val scrollBehavior = rememberSettingsCollapsingScrollBehavior()
val hazeState = rememberSettingsDetailHazeState()
val scheme = MaterialTheme.colorScheme
var certs by remember { mutableStateOf(ProxyTlsTrust.loadPersisted()) }
fun reload() {
certs = ProxyTlsTrust.loadPersisted()
}
Scaffold(
modifier = Modifier.fillMaxSize(),
containerColor = Color.Transparent,
contentColor = scheme.onSurface,
topBar = {
SettingsDetailTopBar(
title = stringResource(Res.string.proxy_trusted_certs_title),
onBack = onBack,
hazeState = hazeState,
scrollBehavior = scrollBehavior,
)
},
) { innerPadding ->
LazyColumn(
modifier = Modifier
.fillMaxSize()
.consumeWindowInsets(innerPadding)
.settingsDetailHazeSource(hazeState)
.conditional(useCollapsing) {
Modifier.nestedScroll(scrollBehavior.nestedScrollConnection)
},
contentPadding = PaddingValues(
top = innerPadding.calculateTopPadding(),
bottom = innerPadding.calculateBottomPadding() + 24.dp,
),
) {
if (certs.isEmpty()) {
item {
Text(
text = stringResource(Res.string.proxy_trusted_certs_empty),
style = MaterialTheme.typography.bodyLarge,
color = scheme.onSurfaceVariant,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 32.dp, vertical = 32.dp),
)
}
} else {
items(certs, key = { it.id }) { cert ->
TrustedCertRow(
cert = cert,
index = certs.indexOf(cert),
total = certs.size,
onDelete = {
ProxyTlsTrust.removePersisted(cert.id)
ProxyChecker.notifyTlsTrustChanged()
reload()
},
)
}
}
}
}
}
@Composable
private fun TrustedCertRow(
cert: TrustedTlsCertificate,
index: Int,
total: Int,
onDelete: () -> Unit,
) {
val scheme = MaterialTheme.colorScheme
ListItem(
modifier = Modifier.padding(horizontal = 16.dp),
headline = cert.label.ifBlank { cert.host },
supportingText = cert.host,
trailingContent = {
IconButton(onClick = onDelete) {
Icon(
imageVector = Icons.Rounded.Delete,
contentDescription = stringResource(Res.string.proxy_delete),
tint = scheme.error,
)
}
},
containerColor = scheme.surfaceContainer,
position = listItemPositionInGroup(index, total),
groupItemCount = total,
divider = index < total - 1,
)
}
@@ -15,7 +15,11 @@ actual fun createPlatformHttpClient(
proxyRoute: ProxyRoute?,
block: HttpClientConfig<*>.() -> Unit,
): HttpClient {
val route = proxyRoute ?: ProxyRuntime.currentRoute
val route = when {
proxyRoute != null -> proxyRoute
ProxyRuntime.probeIsolation -> ProxyRoute.Direct
else -> ProxyRuntime.currentRoute
}
return HttpClient(Darwin) {
engine {
configureRequest {
@@ -0,0 +1,7 @@
package ru.fromchat.network.proxy
import io.ktor.client.HttpClientConfig
actual fun configureEngineTls(config: HttpClientConfig<*>) = Unit
actual suspend fun fetchPeerCertificatePem(route: ProxyRoute): String? = null
@@ -15,7 +15,11 @@ actual fun createPlatformHttpClient(
proxyRoute: ProxyRoute?,
block: HttpClientConfig<*>.() -> Unit,
): HttpClient {
val route = proxyRoute ?: ProxyRuntime.currentRoute
val route = when {
proxyRoute != null -> proxyRoute
ProxyRuntime.probeIsolation -> ProxyRoute.Direct
else -> ProxyRuntime.currentRoute
}
return HttpClient(CIO) {
defaultRequest {
contentType(ContentType.Application.Json)
@@ -8,6 +8,7 @@ import java.net.ProxySelector
import java.net.URI
actual fun configureEngineProxy(config: HttpClientConfig<*>, route: ProxyRoute) {
configureEngineTls(config)
val javaProxy = when (route) {
ProxyRoute.Direct -> return
ProxyRoute.System -> resolveSystemProxy() ?: return
@@ -32,7 +33,7 @@ actual fun systemProxyIsHttp(): Boolean {
internal fun jvmSystemProxyConfigured(): Boolean = resolveSystemProxy() != null
private fun resolveSystemProxy(): Proxy? {
internal fun resolveSystemProxy(): Proxy? {
val target = URI(ServerConfig.apiBaseUrl)
ProxySelector.getDefault()?.select(target)?.firstOrNull { it.type() != Proxy.Type.DIRECT }?.let {
return it
@@ -0,0 +1,114 @@
package ru.fromchat.network.proxy
import io.ktor.client.HttpClientConfig
import io.ktor.client.engine.cio.CIOEngineConfig
import ru.fromchat.config.ServerConfig
import java.io.ByteArrayInputStream
import java.net.InetSocketAddress
import java.net.Proxy
import java.net.URL
import java.security.KeyStore
import java.security.cert.CertificateException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.util.Base64
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
actual fun configureEngineTls(config: HttpClientConfig<*>) {
val pinningTrustManager = ProxyPinningTrustManager()
config.engine {
val cio = this as? CIOEngineConfig ?: return@engine
cio.https {
trustManager = pinningTrustManager
}
}
}
actual suspend fun fetchPeerCertificatePem(route: ProxyRoute): String? {
val apiUrl = ServerConfig.apiBaseUrl.trimEnd('/')
val host = tlsHostFromUrl(apiUrl)
val port = runCatching {
val url = URL(apiUrl)
if (url.port > 0) url.port else url.defaultPort
}.getOrDefault(443)
return runCatching {
val connection = URL("https://$host:$port/").openConnection(resolveJavaProxy(route)) as HttpsURLConnection
connection.connectTimeout = 5_000
connection.readTimeout = 5_000
connection.sslSocketFactory = trustAllSslContext().socketFactory
connection.hostnameVerifier = javax.net.ssl.HttpsURLConnection.getDefaultHostnameVerifier()
connection.requestMethod = "GET"
connection.connect()
val certs = connection.serverCertificates
val leaf = certs.firstOrNull() as? X509Certificate ?: return@runCatching null
certificateToPem(leaf)
}.getOrNull()
}
private fun resolveJavaProxy(route: ProxyRoute): Proxy = when (route) {
ProxyRoute.Direct -> Proxy.NO_PROXY
ProxyRoute.System -> resolveSystemProxy() ?: Proxy.NO_PROXY
is ProxyRoute.Custom -> when (route.endpointType) {
ProxyType.HTTP -> Proxy(Proxy.Type.HTTP, InetSocketAddress(route.host, route.port))
ProxyType.SOCKS5, ProxyType.SSH ->
Proxy(Proxy.Type.SOCKS, InetSocketAddress(route.host, route.port))
}
}
private fun trustAllSslContext(): SSLContext {
val trustAll = object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
}
return SSLContext.getInstance("TLS").apply {
init(null, arrayOf<TrustManager>(trustAll), null)
}
}
internal class ProxyPinningTrustManager : X509TrustManager {
private val delegate: X509TrustManager = defaultTrustManager()
private val apiHost: String
get() = tlsHostFromUrl(ServerConfig.apiBaseUrl)
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
delegate.checkClientTrusted(chain, authType)
}
override fun getAcceptedIssuers(): Array<X509Certificate> = delegate.acceptedIssuers
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
try {
delegate.checkServerTrusted(chain, authType)
} catch (e: CertificateException) {
val leaf = chain?.firstOrNull() ?: throw e
val pem = certificateToPem(leaf)
if (ProxyTlsTrust.extraPemForHost(apiHost).any { it.trim() == pem.trim() }) {
return
}
throw e
}
}
private fun defaultTrustManager(): X509TrustManager {
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
factory.init(null as KeyStore?)
return factory.trustManagers.filterIsInstance<X509TrustManager>().first()
}
}
internal fun certificateToPem(certificate: X509Certificate): String {
val encoded = Base64.getMimeEncoder(64, "\n".toByteArray()).encodeToString(certificate.encoded)
return "-----BEGIN CERTIFICATE-----\n$encoded\n-----END CERTIFICATE-----"
}
internal fun pemToCertificate(pem: String): X509Certificate? {
val trimmed = pem.trim()
if (trimmed.isEmpty()) return null
val factory = CertificateFactory.getInstance("X.509")
return factory.generateCertificate(ByteArrayInputStream(trimmed.toByteArray())) as? X509Certificate
}