Add proxy networking layer and HttpClient integration

Co-authored-by: denis0001-dev <denis0001.dev@ya.ru>
This commit is contained in:
Cursor Agent
2026-11-11 15:21:33 +00:00
Unverified
parent f1f191d302
commit 0deb0cceed
19 changed files with 1169 additions and 119 deletions
+2
View File
@@ -225,6 +225,7 @@ kotlin {
implementation(libs.livekit.android)
implementation(libs.livekit.android.compose.components)
implementation(libs.androidx.webkit)
implementation(libs.sshj)
}
iosMain.dependencies {
@@ -268,6 +269,7 @@ kotlin {
}
}
implementation(libs.jna.platform)
implementation(libs.sshj)
}
}
}
@@ -4,13 +4,21 @@ import io.ktor.client.HttpClient
import io.ktor.client.HttpClientConfig
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.HttpTimeout
import ru.fromchat.network.proxy.ProxyRoute
import ru.fromchat.network.proxy.ProxyRuntime
import ru.fromchat.network.proxy.configureEngineProxy
actual fun createPlatformHttpClient(block: HttpClientConfig<*>.() -> Unit) =
actual fun createPlatformHttpClient(
proxyRoute: ProxyRoute?,
block: HttpClientConfig<*>.() -> Unit,
): HttpClient =
HttpClient(OkHttp) {
install(HttpTimeout) {
requestTimeoutMillis = 30_000
connectTimeoutMillis = 5_000
socketTimeoutMillis = 30_000
}
val route = proxyRoute ?: ProxyRuntime.currentRoute
configureEngineProxy(this, route)
block()
}
}
@@ -0,0 +1,9 @@
package ru.fromchat.network.proxy
import io.ktor.client.HttpClientConfig
actual fun configureEngineProxy(config: HttpClientConfig<*>, route: ProxyRoute) = Unit
actual fun systemProxyAvailable(): Boolean = false
actual fun systemProxyIsHttp(): Boolean = false
@@ -0,0 +1,168 @@
package ru.fromchat.network.proxy
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import net.schmizz.sshj.userauth.keyprovider.OpenSSHKeyFile
import java.io.IOException
import java.io.StringReader
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
/**
* Local SOCKS5 listener that forwards flows through SSH direct-tcpip channels (ssh -D semantics).
*/
actual class SshDynamicSocksForwarder actual constructor(
private val host: String,
private val sshPort: Int,
private val username: String,
private val authType: SshAuthType,
private val password: String?,
private val privateKeyPem: String?,
) {
private var sshClient: SSHClient? = null
private var serverSocket: ServerSocket? = null
private var workers: ExecutorService? = null
private val running = AtomicBoolean(false)
actual fun start(): Int {
if (!running.compareAndSet(false, true)) {
return serverSocket?.localPort ?: error("SSH forwarder already running")
}
val ssh = SSHClient()
ssh.addHostKeyVerifier(PromiscuousVerifier())
ssh.connect(host, sshPort)
when (authType) {
SshAuthType.Password -> ssh.authPassword(username, password.orEmpty())
SshAuthType.PrivateKey -> {
val key = OpenSSHKeyFile()
key.init(StringReader(privateKeyPem.orEmpty()), null, null)
ssh.authPublickey(username, key)
}
}
val server = ServerSocket()
server.bind(InetSocketAddress(InetAddress.getLoopbackAddress(), 0))
val localPort = server.localPort
sshClient = ssh
serverSocket = server
val executor = Executors.newCachedThreadPool()
workers = executor
executor.execute { acceptLoop(ssh, server) }
return localPort
}
actual fun stop() {
if (!running.getAndSet(false)) return
runCatching { serverSocket?.close() }
runCatching { workers?.shutdownNow() }
runCatching { sshClient?.disconnect() }
serverSocket = null
workers = null
sshClient = null
}
private fun acceptLoop(ssh: SSHClient, server: ServerSocket) {
while (running.get() && !server.isClosed) {
runCatching {
val client = server.accept()
workers?.execute { handleSocksClient(ssh, client) }
}.onFailure {
if (running.get() && !server.isClosed) {
ru.fromchat.logging.Logger.w("SshDynamicSocksForwarder", "Accept failed: ${it.message}")
}
}
}
}
private fun handleSocksClient(ssh: SSHClient, client: Socket) {
client.soTimeout = 30_000
try {
val input = client.getInputStream()
val output = client.getOutputStream()
val version = input.read()
if (version != 0x05) return
val methodCount = input.read()
if (methodCount <= 0) return
val methods = ByteArray(methodCount)
if (input.read(methods) != methodCount) return
output.write(byteArrayOf(0x05, 0x00))
output.flush()
val header = ByteArray(4)
if (input.read(header) < 4) return
if (header[0] != 0x05.toByte() || header[1] != 0x01.toByte()) return
val addressType = header[3].toInt()
val (remoteHost, remotePort) = when (addressType) {
0x01 -> readIpv4Target(input)
0x03 -> readDomainTarget(input)
0x04 -> readIpv6Target(input)
else -> return
}
val direct = ssh.newDirectConnection(remoteHost, remotePort)
output.write(byteArrayOf(0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0))
output.flush()
relayBidirectional(client, direct.inputStream, direct.outputStream)
} catch (_: IOException) {
// Client closed or handshake failed.
} finally {
runCatching { client.close() }
}
}
private fun readIpv4Target(input: java.io.InputStream): Pair<String, Int> {
val addr = ByteArray(4)
if (input.read(addr) != 4) throw IOException("short ipv4")
val portHi = input.read()
val portLo = input.read()
val port = (portHi shl 8) or portLo
val host = InetAddress.getByAddress(addr).hostAddress ?: throw IOException("bad ipv4")
return host to port
}
private fun readDomainTarget(input: java.io.InputStream): Pair<String, Int> {
val len = input.read()
if (len <= 0) throw IOException("short domain")
val domain = ByteArray(len)
if (input.read(domain) != len) throw IOException("short domain name")
val portHi = input.read()
val portLo = input.read()
val port = (portHi shl 8) or portLo
return String(domain, Charsets.US_ASCII) to port
}
private fun readIpv6Target(input: java.io.InputStream): Pair<String, Int> {
val addr = ByteArray(16)
if (input.read(addr) != 16) throw IOException("short ipv6")
val portHi = input.read()
val portLo = input.read()
val port = (portHi shl 8) or portLo
val host = InetAddress.getByAddress(addr).hostAddress ?: throw IOException("bad ipv6")
return host to port
}
private fun relayBidirectional(
client: Socket,
remoteIn: java.io.InputStream,
remoteOut: java.io.OutputStream,
) {
val clientIn = client.getInputStream()
val clientOut = client.getOutputStream()
val t1 = Thread {
runCatching { clientIn.copyTo(remoteOut) }
runCatching { remoteOut.flush() }
runCatching { client.shutdownOutput() }
}
val t2 = Thread {
runCatching { remoteIn.copyTo(clientOut) }
runCatching { clientOut.flush() }
runCatching { client.close() }
}
t1.start()
t2.start()
t1.join()
t2.join()
}
}
@@ -139,15 +139,17 @@ import ru.fromchat.api.schema.websocket.types.DmTypingData
import ru.fromchat.api.schema.websocket.types.SubscribeStatusData
import ru.fromchat.config.ServerConfig
import ru.fromchat.config.Settings
import ru.fromchat.network.proxy.ProxyRoute
import ru.fromchat.network.proxy.ProxyRuntime
import kotlin.concurrent.Volatile
import kotlin.time.Duration.Companion.milliseconds
/**
* Creates a platform-specific HTTP client that supports WebSockets
* The config block is applied to configure plugins like WebSockets, JSON, etc.
*/
expect fun createPlatformHttpClient(
block: io.ktor.client.HttpClientConfig<*>.() -> Unit = {}
proxyRoute: ProxyRoute? = null,
block: io.ktor.client.HttpClientConfig<*>.() -> Unit = {},
): HttpClient
object ApiClient {
@@ -227,114 +229,14 @@ object ApiClient {
// --- HTTP clients ---
val http = createPlatformHttpClient {
install(ContentNegotiation) {
json(json)
}
val http: HttpClient
get() = HttpClients.http
install(Logging) {
logger = Logger.SIMPLE
level = LogLevel.INFO
}
private val httpProbe: HttpClient
get() = HttpClients.httpProbe
install(WebSockets) {
pingInterval = 5000.milliseconds
}
val currentDevice = currentDeviceInfo()
val osName = currentDevice.osName?.takeIfNotBlank()
val osVersion = currentDevice.osVersion?.takeIfNotBlank()
val brand = currentDevice.brand?.takeIfNotBlank()
val model = currentDevice.model?.takeIfNotBlank()
val userAgent = buildLoginUserAgent(
osName = osName,
osVersion = osVersion,
model = model,
brand = brand
)
defaultRequest {
token?.let { authToken ->
bearerAuth(authToken)
}
header("User-Agent", userAgent)
}
// Handle HTTP auth errors globally.
// - 401 => token/session invalid, clear auth state and trigger auth recovery flow.
// - 403 => forbidden, keep session intact (used for read-only/suspension workflows).
HttpResponseValidator {
validateResponse { response ->
val instanceHeader = response.headers[InstanceIdGuard.INSTANCE_ID_HEADER]
runCatching {
ServerConfig.serverConfig.value?.let { cfg ->
InstanceIdGuard.onResponseHeader(instanceHeader, cfg)
}
}
if (response.status.value == 401) {
val path = response.call.request.url.encodedPath
val isCredentialCheck = path.endsWith("/auth/steps/password") || path.endsWith("/auth/steps/register/confirm")
if (!isCredentialCheck && !logoutInProgress) {
MainScope().launch {
runCatching { WebSocketManager.disconnect() }
runCatching { clearLocalSession() }
onAuthError?.invoke()
}
}
}
if (response.status.value == 403) {
handleForbiddenAsPotentialSuspension(response)
}
if (response.status.value in 200..299 && token != null) {
WebSocketManager.onServerLikelyReachable()
}
if (response.status.value !in (200..299) + 101) {
throw ClientRequestException(
response,
response.status.description
)
}
}
}
}
/** GET-only client: no global 401 handler (used when probing a not-yet-saved server URL). */
private val httpProbe by lazy {
createPlatformHttpClient {
install(ContentNegotiation) {
json(json)
}
install(Logging) {
logger = Logger.SIMPLE
level = LogLevel.INFO
}
val currentDevice = currentDeviceInfo()
val userAgent = buildLoginUserAgent(
osName = currentDevice.osName?.takeIfNotBlank(),
osVersion = currentDevice.osVersion?.takeIfNotBlank(),
model = currentDevice.model?.takeIfNotBlank(),
brand = currentDevice.brand?.takeIfNotBlank(),
)
defaultRequest {
header("User-Agent", userAgent)
}
HttpResponseValidator {
validateResponse { response ->
val instanceHeader = response.headers[InstanceIdGuard.INSTANCE_ID_HEADER]
runCatching {
InstanceIdGuard.onResponseHeader(instanceHeader)
}
if (response.status.value !in (200..299) + 101) {
throw ClientRequestException(
response,
response.status.description,
)
}
}
}
}
fun rebuildHttpClients() {
HttpClients.rebuildHttpClients()
}
// --- Server probe ---
@@ -345,9 +247,10 @@ object ApiClient {
}
/** Minimal TCP/HTTP check: true if a GET succeeds without throwing (any HTTP status). */
suspend fun probeHttpGet(url: String): Boolean =
suspend fun probeHttpGet(url: String, bypassProxy: Boolean = false): Boolean =
runCatching {
httpProbe.get(url.trim())
val client = if (bypassProxy) HttpClients.callDirectHttp else httpProbe
client.get(url.trim())
}.isSuccess
sealed interface CheckAuthResult {
@@ -424,7 +327,7 @@ object ApiClient {
.replace(".", "_")
.trim('_')
private fun buildLoginUserAgent(
internal fun buildLoginUserAgent(
osName: String?,
osVersion: String?,
model: String?,
@@ -451,14 +354,14 @@ object ApiClient {
var user: User? = null
@Volatile
private var logoutInProgress = false
internal var logoutInProgress = false
var onAuthError: (() -> Unit)? = null
private fun getSuspensionReasonFromForbiddenResponse(response: HttpResponse): String? =
response.headers["suspension_reason"]?.trim()?.takeIf { it.isNotBlank() }
private fun handleForbiddenAsPotentialSuspension(response: HttpResponse) {
internal fun handleForbiddenAsPotentialSuspension(response: HttpResponse) {
if (response.status.value != 403) return
getSuspensionReasonFromForbiddenResponse(response)?.let { reason ->
setSuspended(reason)
@@ -1870,7 +1773,8 @@ object ApiClient {
if (_suspensionState.value.isSuspended) {
throw IllegalStateException("Suspended")
}
return http
val client = if (ProxyRuntime.needsDirectBypassForCalls) HttpClients.callDirectHttp else http
return client
.post("${ServerConfig.apiBaseUrl}/livekit/token") {
contentType(ContentType.Application.Json)
setBody(LiveKitTokenRequest(peerUserId = peerUserId, roomName = roomName))
@@ -0,0 +1,225 @@
package ru.fromchat.api
import io.ktor.client.HttpClient
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.plugins.HttpResponseValidator
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.plugins.logging.SIMPLE
import io.ktor.client.plugins.websocket.WebSockets
import io.ktor.client.plugins.websocket.pingInterval
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.header
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import ru.fromchat.api.instance.InstanceIdGuard
import ru.fromchat.api.local.WebSocketManager
import ru.fromchat.config.ServerConfig
import ru.fromchat.network.proxy.ProxyRoute
import ru.fromchat.network.proxy.ProxyRuntime
import ru.fromchat.utils.currentDeviceInfo
import kotlin.concurrent.Volatile
import kotlin.time.Duration.Companion.milliseconds
/**
* Holds [HttpClient] instances that must be recreated when the active proxy route changes.
*/
internal object HttpClients {
@Volatile
private var mainClient: HttpClient? = null
@Volatile
private var probeClient: HttpClient? = null
@Volatile
private var directBypassClient: HttpClient? = null
val http: HttpClient
get() = mainClient ?: buildMainClient().also { mainClient = it }
val httpProbe: HttpClient
get() = probeClient ?: buildProbeClient().also { probeClient = it }
/** Direct (no proxy) client for LiveKit token and health when an HTTP proxy is active. */
val callDirectHttp: HttpClient
get() {
if (!ProxyRuntime.needsDirectBypassForCalls) {
return http
}
return directBypassClient ?: buildDirectBypassClient().also { directBypassClient = it }
}
fun rebuildHttpClients() {
val oldMain = mainClient
val oldProbe = probeClient
val oldDirect = directBypassClient
mainClient = buildMainClient()
probeClient = buildProbeClient()
directBypassClient = if (ProxyRuntime.needsDirectBypassForCalls) {
buildDirectBypassClient()
} else {
null
}
oldMain?.close()
oldProbe?.close()
oldDirect?.close()
}
private fun buildMainClient(): HttpClient =
createPlatformHttpClient(proxyRoute = ProxyRuntime.currentRoute) {
install(ContentNegotiation) {
json(ApiClient.json)
}
install(Logging) {
logger = Logger.SIMPLE
level = LogLevel.INFO
}
install(WebSockets) {
pingInterval = 5000.milliseconds
}
val currentDevice = currentDeviceInfo()
val userAgent = ApiClient.buildLoginUserAgent(
osName = currentDevice.osName?.takeIf { it.isNotBlank() },
osVersion = currentDevice.osVersion?.takeIf { it.isNotBlank() },
model = currentDevice.model?.takeIf { it.isNotBlank() },
brand = currentDevice.brand?.takeIf { it.isNotBlank() },
)
defaultRequest {
ApiClient.token?.let { authToken ->
bearerAuth(authToken)
}
header("User-Agent", userAgent)
}
HttpResponseValidator {
validateResponse { response ->
val instanceHeader = response.headers[InstanceIdGuard.INSTANCE_ID_HEADER]
runCatching {
ServerConfig.serverConfig.value?.let { cfg ->
InstanceIdGuard.onResponseHeader(instanceHeader, cfg)
}
}
if (response.status.value == 401) {
val path = response.call.request.url.encodedPath
val isCredentialCheck = path.endsWith("/auth/steps/password") ||
path.endsWith("/auth/steps/register/confirm")
if (!isCredentialCheck && !ApiClient.logoutInProgress) {
MainScope().launch {
runCatching { WebSocketManager.disconnect() }
runCatching { ApiClient.clearLocalSession() }
ApiClient.onAuthError?.invoke()
}
}
}
if (response.status.value == 403) {
ApiClient.handleForbiddenAsPotentialSuspension(response)
}
if (response.status.value in 200..299 && ApiClient.token != null) {
WebSocketManager.onServerLikelyReachable()
}
if (response.status.value !in (200..299) + 101) {
throw ClientRequestException(response, response.status.description)
}
}
}
}
private fun buildProbeClient(): HttpClient =
createPlatformHttpClient(proxyRoute = ProxyRuntime.currentRoute) {
install(ContentNegotiation) {
json(ApiClient.json)
}
install(Logging) {
logger = Logger.SIMPLE
level = LogLevel.INFO
}
val currentDevice = currentDeviceInfo()
val userAgent = ApiClient.buildLoginUserAgent(
osName = currentDevice.osName?.takeIf { it.isNotBlank() },
osVersion = currentDevice.osVersion?.takeIf { it.isNotBlank() },
model = currentDevice.model?.takeIf { it.isNotBlank() },
brand = currentDevice.brand?.takeIf { it.isNotBlank() },
)
defaultRequest {
header("User-Agent", userAgent)
}
HttpResponseValidator {
validateResponse { response ->
val instanceHeader = response.headers[InstanceIdGuard.INSTANCE_ID_HEADER]
runCatching {
InstanceIdGuard.onResponseHeader(instanceHeader)
}
if (response.status.value !in (200..299) + 101) {
throw ClientRequestException(
response,
response.status.description,
)
}
}
}
}
private fun buildDirectBypassClient(): HttpClient =
createPlatformHttpClient(proxyRoute = ProxyRoute.Direct) {
install(ContentNegotiation) {
json(ApiClient.json)
}
install(Logging) {
logger = Logger.SIMPLE
level = LogLevel.INFO
}
val currentDevice = currentDeviceInfo()
val userAgent = ApiClient.buildLoginUserAgent(
osName = currentDevice.osName?.takeIf { it.isNotBlank() },
osVersion = currentDevice.osVersion?.takeIf { it.isNotBlank() },
model = currentDevice.model?.takeIf { it.isNotBlank() },
brand = currentDevice.brand?.takeIf { it.isNotBlank() },
)
defaultRequest {
ApiClient.token?.let { authToken ->
bearerAuth(authToken)
}
header("User-Agent", userAgent)
}
HttpResponseValidator {
validateResponse { response ->
if (response.status.value !in (200..299) + 101) {
throw ClientRequestException(
response,
response.status.description,
)
}
}
}
}
}
/** One-off probe client (e.g. proxy checker); caller must [HttpClient.close]. */
fun createProbeHttpClient(
proxyRoute: ProxyRoute,
bypassHttpProxyForCalls: Boolean = false,
): HttpClient {
val route = if (bypassHttpProxyForCalls) ProxyRoute.Direct else proxyRoute
return createPlatformHttpClient(proxyRoute = route) {
install(ContentNegotiation) {
json(ApiClient.json)
}
install(Logging) {
logger = Logger.SIMPLE
level = LogLevel.INFO
}
HttpResponseValidator {
validateResponse { response ->
if (response.status.value !in (200..299) + 101) {
throw ClientRequestException(
response,
response.status.description,
)
}
}
}
}
}
@@ -73,7 +73,8 @@ suspend fun probeCallsReachable(config: ServerConfigData) = runCatching {
append(":")
append(config.apiPort)
append("/livekit-health")
}
},
bypassProxy = true,
)
}
}.getOrDefault(false)
@@ -0,0 +1,68 @@
package ru.fromchat.network.proxy
import io.ktor.client.call.body
import io.ktor.client.request.get
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import ru.fromchat.api.createProbeHttpClient
import ru.fromchat.api.schema.server.ServerInstanceIdResponse
import ru.fromchat.config.ServerConfig
import kotlin.time.TimeSource
private const val MAX_PARALLEL_CHECKS = 10
private const val MAX_CUSTOM_PROXIES_TO_CHECK = 10
object ProxyChecker {
suspend fun checkProxy(endpoint: ProxyCheckTarget): ProxyCheckResult {
val route = ProxyRuntime.routeForCheckTarget(endpoint) ?: return ProxyCheckResult.Failed("Unknown proxy")
if (route is ProxyRoute.Direct) {
return checkWithRoute(ProxyRoute.Direct)
}
return checkWithRoute(route)
}
suspend fun checkDirect(): ProxyCheckResult = checkWithRoute(ProxyRoute.Direct)
suspend fun checkSystem(): ProxyCheckResult =
if (systemProxyAvailable()) {
checkWithRoute(ProxyRoute.System)
} else {
ProxyCheckResult.Failed("System proxy unavailable")
}
suspend fun checkAllSavedProxies(): Map<String, ProxyCheckResult> = coroutineScope {
val proxies = ProxyStore.readProxies().take(MAX_CUSTOM_PROXIES_TO_CHECK)
val semaphore = Semaphore(MAX_PARALLEL_CHECKS)
proxies.map { proxy ->
async {
semaphore.withPermit {
proxy.id to checkProxy(ProxyCheckTarget.SavedProxyById(proxy.id))
}
}
}.awaitAll().toMap()
}
private suspend fun checkWithRoute(route: ProxyRoute): ProxyCheckResult {
val mark = TimeSource.Monotonic.markNow()
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")
} else {
ProxyCheckResult.Success(
pingMs = mark.elapsedNow().inWholeMilliseconds.toInt(),
instanceId = instanceId,
)
}
} catch (e: Exception) {
ProxyCheckResult.Failed(e.message)
} finally {
client.close()
}
}
}
@@ -0,0 +1,22 @@
package ru.fromchat.network.proxy
import io.ktor.client.HttpClientConfig
expect fun configureEngineProxy(config: HttpClientConfig<*>, route: ProxyRoute)
expect fun systemProxyAvailable(): Boolean
/** When [route] is [ProxyRoute.System], true if the OS proxy is HTTP (not SOCKS). */
expect fun systemProxyIsHttp(): Boolean
expect class SshDynamicSocksForwarder(
host: String,
sshPort: Int,
username: String,
authType: SshAuthType,
password: String?,
privateKeyPem: String?,
) {
fun start(): Int
fun stop()
}
@@ -0,0 +1,88 @@
package ru.fromchat.network.proxy
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
sealed class ProxySelection {
@Serializable
@SerialName("direct")
data object Direct : ProxySelection()
@Serializable
@SerialName("system")
data object System : ProxySelection()
@Serializable
@SerialName("custom")
data class Custom(val id: String) : ProxySelection()
}
@Serializable
enum class ProxyType {
@SerialName("http")
HTTP,
@SerialName("socks5")
SOCKS5,
@SerialName("ssh")
SSH,
}
@Serializable
enum class SshAuthType {
@SerialName("password")
Password,
@SerialName("privateKey")
PrivateKey,
}
/**
* Persisted proxy entry. Secrets ([password], SSH private key) live in secure settings
* keyed by [id] — see [ProxyStore].
*/
@Serializable
data class SavedProxy(
val id: String,
val label: String,
val type: ProxyType,
val host: String,
val port: Int,
val user: String? = null,
val sshPort: Int = 22,
val sshAuthType: SshAuthType = SshAuthType.Password,
)
/** Effective routing for Ktor engine configuration. */
sealed class ProxyRoute {
data object Direct : ProxyRoute()
data object System : ProxyRoute()
data class Custom(
val endpointType: ProxyType,
val host: String,
val port: Int,
val user: String? = null,
val password: String? = null,
) : ProxyRoute()
}
sealed class ProxyTunnelState {
data object Idle : ProxyTunnelState()
data object Connecting : ProxyTunnelState()
data class Active(val localSocksPort: Int) : ProxyTunnelState()
data class Error(val message: String) : ProxyTunnelState()
}
sealed class ProxyCheckTarget {
data object ActiveSelection : ProxyCheckTarget()
data class SavedProxyById(val id: String) : ProxyCheckTarget()
}
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()
}
@@ -0,0 +1,210 @@
package ru.fromchat.network.proxy
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import ru.fromchat.api.ApiClient
object ProxyRuntime {
private val applyMutex = Mutex()
private val _selection = MutableStateFlow<ProxySelection>(ProxySelection.Direct)
val selection: StateFlow<ProxySelection> = _selection.asStateFlow()
private val _tunnelState = MutableStateFlow<ProxyTunnelState>(ProxyTunnelState.Idle)
val tunnelState: StateFlow<ProxyTunnelState> = _tunnelState.asStateFlow()
private val _savedProxies = MutableStateFlow<List<SavedProxy>>(emptyList())
val savedProxies: StateFlow<List<SavedProxy>> = _savedProxies.asStateFlow()
private val _currentRoute = MutableStateFlow<ProxyRoute>(ProxyRoute.Direct)
val currentRoute: ProxyRoute
get() = _currentRoute.value
private var sshForwarder: SshDynamicSocksForwarder? = null
fun initialize() {
_savedProxies.value = ProxyStore.loadProxies()
_selection.value = ProxyStore.loadSelection()
kotlinx.coroutines.runBlocking {
refreshEffectiveRoute(startTunnel = true)
}
}
val needsDirectBypassForCalls: Boolean
get() = when (val route = currentRoute) {
is ProxyRoute.Direct -> false
is ProxyRoute.System -> systemProxyIsHttp()
is ProxyRoute.Custom -> route.endpointType == ProxyType.HTTP
}
suspend fun applySelection(selection: ProxySelection) {
applyMutex.withLock {
stopSshTunnel()
_selection.value = selection
ProxyStore.setSelection(selection)
refreshEffectiveRoute(startTunnel = true)
ApiClient.rebuildHttpClients()
}
}
suspend fun refreshSavedProxies() {
_savedProxies.value = ProxyStore.readProxies()
refreshEffectiveRoute(startTunnel = false)
}
suspend fun upsertProxy(proxy: SavedProxy, password: String?, privateKey: String?) {
val list = ProxyStore.readProxies().toMutableList()
val idx = list.indexOfFirst { it.id == proxy.id }
if (idx >= 0) {
list[idx] = proxy
} else {
list.add(proxy)
}
ProxyStore.setProxies(list)
ProxyStore.writePassword(proxy.id, password)
if (proxy.type == ProxyType.SSH) {
ProxyStore.writePrivateKey(proxy.id, privateKey)
}
_savedProxies.value = list
if (_selection.value == ProxySelection.Custom(proxy.id)) {
applySelection(_selection.value)
}
}
suspend fun removeProxy(id: String) {
val list = ProxyStore.readProxies().filterNot { it.id == id }
ProxyStore.setProxies(list)
ProxyStore.removeSecrets(id)
_savedProxies.value = list
if (_selection.value == ProxySelection.Custom(id)) {
applySelection(ProxySelection.Direct)
}
}
private suspend fun refreshEffectiveRoute(startTunnel: Boolean) {
if (startTunnel) {
prepareTunnelForSelection(_selection.value)
}
_currentRoute.value = buildRoute(_selection.value, _savedProxies.value, loadSecrets = true)
}
private suspend fun prepareTunnelForSelection(selection: ProxySelection) {
val customId = (selection as? ProxySelection.Custom)?.id ?: return
val proxy = _savedProxies.value.firstOrNull { it.id == customId }
?: ProxyStore.readProxies().firstOrNull { it.id == customId }
?: return
if (proxy.type != ProxyType.SSH) return
_tunnelState.value = ProxyTunnelState.Connecting
val password = ProxyStore.readPassword(proxy.id)
val privateKey = ProxyStore.readPrivateKey(proxy.id)
val user = proxy.user?.trim().orEmpty()
if (user.isEmpty()) {
_tunnelState.value = ProxyTunnelState.Error("SSH user required")
return
}
runCatching {
val forwarder = SshDynamicSocksForwarder(
host = proxy.host,
sshPort = proxy.sshPort,
username = user,
authType = proxy.sshAuthType,
password = password,
privateKeyPem = privateKey,
)
val localPort = forwarder.start()
sshForwarder = forwarder
_tunnelState.value = ProxyTunnelState.Active(localPort)
}.onFailure { e ->
_tunnelState.value = ProxyTunnelState.Error(e.message ?: e::class.simpleName.orEmpty())
}
}
private fun stopSshTunnel() {
runCatching { sshForwarder?.stop() }
sshForwarder = null
_tunnelState.value = ProxyTunnelState.Idle
}
private suspend fun buildRoute(
selection: ProxySelection,
proxies: List<SavedProxy>,
loadSecrets: Boolean,
): ProxyRoute =
when (selection) {
ProxySelection.Direct -> ProxyRoute.Direct
ProxySelection.System -> if (systemProxyAvailable()) ProxyRoute.System else ProxyRoute.Direct
is ProxySelection.Custom -> {
val proxy = proxies.firstOrNull { it.id == selection.id } ?: return ProxyRoute.Direct
val password = if (loadSecrets) ProxyStore.readPassword(proxy.id) else null
when (proxy.type) {
ProxyType.HTTP -> ProxyRoute.Custom(
endpointType = ProxyType.HTTP,
host = proxy.host,
port = proxy.port,
user = proxy.user,
password = password,
)
ProxyType.SOCKS5 -> ProxyRoute.Custom(
endpointType = ProxyType.SOCKS5,
host = proxy.host,
port = proxy.port,
user = proxy.user,
password = password,
)
ProxyType.SSH -> {
val tunnel = _tunnelState.value as? ProxyTunnelState.Active
?: return ProxyRoute.Direct
ProxyRoute.Custom(
endpointType = ProxyType.SOCKS5,
host = "127.0.0.1",
port = tunnel.localSocksPort,
)
}
}
}
}
suspend fun routeForCheckTarget(target: ProxyCheckTarget): ProxyRoute? = when (target) {
ProxyCheckTarget.ActiveSelection -> currentRoute
is ProxyCheckTarget.SavedProxyById -> {
val proxy = ProxyStore.readProxies().firstOrNull { it.id == target.id } ?: return null
ephemeralRouteForProxy(proxy)
}
}
private suspend fun ephemeralRouteForProxy(proxy: SavedProxy): ProxyRoute? = when (proxy.type) {
ProxyType.HTTP, ProxyType.SOCKS5 -> ProxyRoute.Custom(
endpointType = proxy.type,
host = proxy.host,
port = proxy.port,
user = proxy.user,
password = ProxyStore.readPassword(proxy.id),
)
ProxyType.SSH -> {
val user = proxy.user?.trim().orEmpty()
if (user.isEmpty()) return null
val forwarder = SshDynamicSocksForwarder(
host = proxy.host,
sshPort = proxy.sshPort,
username = user,
authType = proxy.sshAuthType,
password = ProxyStore.readPassword(proxy.id),
privateKeyPem = ProxyStore.readPrivateKey(proxy.id),
)
val localPort = runCatching { forwarder.start() }.getOrNull() ?: return null
try {
ProxyRoute.Custom(
endpointType = ProxyType.SOCKS5,
host = "127.0.0.1",
port = localPort,
)
} finally {
forwarder.stop()
}
}
}
}
@@ -0,0 +1,113 @@
package ru.fromchat.network.proxy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.Json
import ru.fromchat.utils.settings.Settings as PlatformSettings
import ru.fromchat.utils.settings.secureSettings
object ProxyStore {
private const val SAVED_PROXIES_KEY = "saved_proxies_v1"
private const val PROXY_SELECTION_KEY = "proxy_selection_v1"
private fun passwordKey(id: String) = "proxy_secret_password_$id"
private fun privateKeyKey(id: String) = "proxy_secret_private_key_$id"
private val settings = PlatformSettings()
private val json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
}
private fun runIo(block: suspend CoroutineScope.() -> Unit) {
CoroutineScope(Dispatchers.IO).launch(block = block)
}
fun loadProxies(): List<SavedProxy> = runBlocking { readProxies() }
suspend fun readProxies(): List<SavedProxy> = withContext(Dispatchers.IO) {
val raw = settings.getString(SAVED_PROXIES_KEY, "")
if (raw.isEmpty()) return@withContext emptyList()
runCatching {
json.decodeFromString(ListSerializer(SavedProxy.serializer()), raw)
}.getOrDefault(emptyList())
}
fun saveProxies(proxies: List<SavedProxy>) {
runIo {
val enc = json.encodeToString(ListSerializer(SavedProxy.serializer()), proxies)
settings.putString(SAVED_PROXIES_KEY, enc)
}
}
suspend fun setProxies(proxies: List<SavedProxy>) {
withContext(Dispatchers.IO) {
val enc = json.encodeToString(ListSerializer(SavedProxy.serializer()), proxies)
settings.putString(SAVED_PROXIES_KEY, enc)
}
}
fun loadSelection(): ProxySelection = runBlocking { readSelection() }
suspend fun readSelection(): ProxySelection = withContext(Dispatchers.IO) {
val raw = settings.getString(PROXY_SELECTION_KEY, "")
if (raw.isEmpty()) return@withContext ProxySelection.Direct
runCatching {
json.decodeFromString(ProxySelection.serializer(), raw)
}.getOrDefault(ProxySelection.Direct)
}
fun saveSelection(selection: ProxySelection) {
runIo {
settings.putString(PROXY_SELECTION_KEY, json.encodeToString(ProxySelection.serializer(), selection))
}
}
suspend fun setSelection(selection: ProxySelection) {
withContext(Dispatchers.IO) {
settings.putString(PROXY_SELECTION_KEY, json.encodeToString(ProxySelection.serializer(), selection))
}
}
suspend fun readPassword(id: String): String? = withContext(Dispatchers.IO) {
val v = secureSettings.getString(passwordKey(id), "")
v.takeIf { it.isNotEmpty() }
}
suspend fun writePassword(id: String, password: String?) {
withContext(Dispatchers.IO) {
if (password.isNullOrEmpty()) {
secureSettings.remove(passwordKey(id))
} else {
secureSettings.putString(passwordKey(id), password)
}
}
}
suspend fun readPrivateKey(id: String): String? = withContext(Dispatchers.IO) {
val v = secureSettings.getString(privateKeyKey(id), "")
v.takeIf { it.isNotEmpty() }
}
suspend fun writePrivateKey(id: String, privateKey: String?) {
withContext(Dispatchers.IO) {
if (privateKey.isNullOrEmpty()) {
secureSettings.remove(privateKeyKey(id))
} else {
secureSettings.putString(privateKeyKey(id), privateKey)
}
}
}
suspend fun removeSecrets(id: String) {
withContext(Dispatchers.IO) {
secureSettings.remove(passwordKey(id))
secureSettings.remove(privateKeyKey(id))
}
}
}
@@ -258,6 +258,8 @@ fun App(
LaunchedEffect(Unit) {
runCatching { ServerConfig.initialize() }
runCatching { ru.fromchat.network.proxy.ProxyRuntime.initialize() }
runCatching { ApiClient.rebuildHttpClients() }
withContext(messageDatabaseDispatcher) {
runCatching { ensureFromChatCacheGeneration() }
runCatching { ApiClient.loadPersistedData() }
@@ -7,10 +7,15 @@ import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.defaultRequest
import io.ktor.http.ContentType
import io.ktor.http.contentType
import ru.fromchat.network.proxy.ProxyRoute
import ru.fromchat.network.proxy.ProxyRuntime
import ru.fromchat.network.proxy.configureEngineProxy
actual fun createPlatformHttpClient(
block: HttpClientConfig<*>.() -> Unit
proxyRoute: ProxyRoute?,
block: HttpClientConfig<*>.() -> Unit,
): HttpClient {
val route = proxyRoute ?: ProxyRuntime.currentRoute
return HttpClient(Darwin) {
engine {
configureRequest {
@@ -35,6 +40,7 @@ actual fun createPlatformHttpClient(
socketTimeoutMillis = 30_000
}
configureEngineProxy(this, route)
block(this)
}
}
@@ -0,0 +1,22 @@
package ru.fromchat.network.proxy
import io.ktor.client.HttpClientConfig
actual fun configureEngineProxy(config: HttpClientConfig<*>, route: ProxyRoute) = Unit
actual fun systemProxyAvailable(): Boolean = false
actual fun systemProxyIsHttp(): Boolean = false
actual class SshDynamicSocksForwarder actual constructor(
host: String,
sshPort: Int,
username: String,
authType: SshAuthType,
password: String?,
privateKeyPem: String?,
) {
actual fun start(): Int = error("SSH dynamic forward is not available")
actual fun stop() = Unit
}
@@ -7,10 +7,15 @@ import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.defaultRequest
import io.ktor.http.ContentType
import io.ktor.http.contentType
import ru.fromchat.network.proxy.ProxyRoute
import ru.fromchat.network.proxy.ProxyRuntime
import ru.fromchat.network.proxy.configureEngineProxy
actual fun createPlatformHttpClient(
block: HttpClientConfig<*>.() -> Unit
proxyRoute: ProxyRoute?,
block: HttpClientConfig<*>.() -> Unit,
): HttpClient {
val route = proxyRoute ?: ProxyRuntime.currentRoute
return HttpClient(CIO) {
defaultRequest {
contentType(ContentType.Application.Json)
@@ -27,6 +32,7 @@ actual fun createPlatformHttpClient(
socketTimeoutMillis = 30_000
}
configureEngineProxy(this, route)
block(this)
}
}
@@ -0,0 +1,26 @@
package ru.fromchat.network.proxy
import io.ktor.client.HttpClientConfig
import java.net.Proxy
import java.net.ProxySelector
import java.net.URI
actual fun configureEngineProxy(config: HttpClientConfig<*>, route: ProxyRoute) {
when (route) {
ProxyRoute.Direct -> Unit
ProxyRoute.System -> Unit
is ProxyRoute.Custom -> Unit
}
}
actual fun systemProxyAvailable(): Boolean {
val selector = ProxySelector.getDefault() ?: return false
val proxies = selector.select(URI("https://example.com"))
return proxies.any { it.type() != Proxy.Type.DIRECT }
}
actual fun systemProxyIsHttp(): Boolean {
val selector = ProxySelector.getDefault() ?: return false
val proxies = selector.select(URI("https://example.com"))
return proxies.any { it.type() == Proxy.Type.HTTP }
}
@@ -0,0 +1,168 @@
package ru.fromchat.network.proxy
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import net.schmizz.sshj.userauth.keyprovider.OpenSSHKeyFile
import java.io.IOException
import java.io.StringReader
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
/**
* Local SOCKS5 listener that forwards flows through SSH direct-tcpip channels (ssh -D semantics).
*/
actual class SshDynamicSocksForwarder actual constructor(
private val host: String,
private val sshPort: Int,
private val username: String,
private val authType: SshAuthType,
private val password: String?,
private val privateKeyPem: String?,
) {
private var sshClient: SSHClient? = null
private var serverSocket: ServerSocket? = null
private var workers: ExecutorService? = null
private val running = AtomicBoolean(false)
actual fun start(): Int {
if (!running.compareAndSet(false, true)) {
return serverSocket?.localPort ?: error("SSH forwarder already running")
}
val ssh = SSHClient()
ssh.addHostKeyVerifier(PromiscuousVerifier())
ssh.connect(host, sshPort)
when (authType) {
SshAuthType.Password -> ssh.authPassword(username, password.orEmpty())
SshAuthType.PrivateKey -> {
val key = OpenSSHKeyFile()
key.init(StringReader(privateKeyPem.orEmpty()), null, null)
ssh.authPublickey(username, key)
}
}
val server = ServerSocket()
server.bind(InetSocketAddress(InetAddress.getLoopbackAddress(), 0))
val localPort = server.localPort
sshClient = ssh
serverSocket = server
val executor = Executors.newCachedThreadPool()
workers = executor
executor.execute { acceptLoop(ssh, server) }
return localPort
}
actual fun stop() {
if (!running.getAndSet(false)) return
runCatching { serverSocket?.close() }
runCatching { workers?.shutdownNow() }
runCatching { sshClient?.disconnect() }
serverSocket = null
workers = null
sshClient = null
}
private fun acceptLoop(ssh: SSHClient, server: ServerSocket) {
while (running.get() && !server.isClosed) {
runCatching {
val client = server.accept()
workers?.execute { handleSocksClient(ssh, client) }
}.onFailure {
if (running.get() && !server.isClosed) {
ru.fromchat.logging.Logger.w("SshDynamicSocksForwarder", "Accept failed: ${it.message}")
}
}
}
}
private fun handleSocksClient(ssh: SSHClient, client: Socket) {
client.soTimeout = 30_000
try {
val input = client.getInputStream()
val output = client.getOutputStream()
val version = input.read()
if (version != 0x05) return
val methodCount = input.read()
if (methodCount <= 0) return
val methods = ByteArray(methodCount)
if (input.read(methods) != methodCount) return
output.write(byteArrayOf(0x05, 0x00))
output.flush()
val header = ByteArray(4)
if (input.read(header) < 4) return
if (header[0] != 0x05.toByte() || header[1] != 0x01.toByte()) return
val addressType = header[3].toInt()
val (remoteHost, remotePort) = when (addressType) {
0x01 -> readIpv4Target(input)
0x03 -> readDomainTarget(input)
0x04 -> readIpv6Target(input)
else -> return
}
val direct = ssh.newDirectConnection(remoteHost, remotePort)
output.write(byteArrayOf(0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0))
output.flush()
relayBidirectional(client, direct.inputStream, direct.outputStream)
} catch (_: IOException) {
// Client closed or handshake failed.
} finally {
runCatching { client.close() }
}
}
private fun readIpv4Target(input: java.io.InputStream): Pair<String, Int> {
val addr = ByteArray(4)
if (input.read(addr) != 4) throw IOException("short ipv4")
val portHi = input.read()
val portLo = input.read()
val port = (portHi shl 8) or portLo
val host = InetAddress.getByAddress(addr).hostAddress ?: throw IOException("bad ipv4")
return host to port
}
private fun readDomainTarget(input: java.io.InputStream): Pair<String, Int> {
val len = input.read()
if (len <= 0) throw IOException("short domain")
val domain = ByteArray(len)
if (input.read(domain) != len) throw IOException("short domain name")
val portHi = input.read()
val portLo = input.read()
val port = (portHi shl 8) or portLo
return String(domain, Charsets.US_ASCII) to port
}
private fun readIpv6Target(input: java.io.InputStream): Pair<String, Int> {
val addr = ByteArray(16)
if (input.read(addr) != 16) throw IOException("short ipv6")
val portHi = input.read()
val portLo = input.read()
val port = (portHi shl 8) or portLo
val host = InetAddress.getByAddress(addr).hostAddress ?: throw IOException("bad ipv6")
return host to port
}
private fun relayBidirectional(
client: Socket,
remoteIn: java.io.InputStream,
remoteOut: java.io.OutputStream,
) {
val clientIn = client.getInputStream()
val clientOut = client.getOutputStream()
val t1 = Thread {
runCatching { clientIn.copyTo(remoteOut) }
runCatching { remoteOut.flush() }
runCatching { client.shutdownOutput() }
}
val t2 = Thread {
runCatching { remoteIn.copyTo(clientOut) }
runCatching { clientOut.flush() }
runCatching { client.close() }
}
t1.start()
t2.start()
t1.join()
t2.join()
}
}
+2
View File
@@ -49,6 +49,7 @@ markdownRendererM3 = "0.46.0"
bouncycastle = "1.86"
webkit = "1.18.0"
openjfx = "27.0.1"
sshj = "0.41.2"
[libraries]
androidx-core-splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "coreSplashscreen" }
@@ -132,6 +133,7 @@ livekit-android = { module = "io.livekit:livekit-android", version.ref = "liveki
livekit-android-compose-components = { module = "io.livekit:livekit-android-compose-components", version.ref = "livekitAndroidComposeComponents" }
markdown-renderer-m3 = { module = "com.mikepenz:multiplatform-markdown-renderer-m3", version.ref = "markdownRendererM3" }
bouncycastle-bcprov = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }
sshj = { module = "com.hierynomus:sshj", version.ref = "sshj" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }