diff --git a/DESIGN.md b/DESIGN.md
index 333b082..bc622a7 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -60,7 +60,7 @@ UI 修改流程见 [.agents/skills/mbrain-style/SKILL.md](.agents/skills/mbrain-
- 工具列表只显示名称与来源;完整说明进入工具详情。搜索同时匹配中文名称、原始名称和描述。
- Token 默认隐藏,复制有反馈。运行记录在独立页,最多 40 条。
- 各主页面和详情保存滚动位置;编辑草稿与导航在 Activity 重建时恢复。
-- 设置中的内网穿透独立管理多条隧道和证书。详情区分服务器连接、隧道注册和本地端口状态;代理类型与客户端插件分别选择。证书显示有效期,导入使用系统文件选择器。
+- 设置中的内网穿透只配置一台服务器,点击服务器行直接进入完整编辑页,不展示服务器列表、单独的编辑按钮或顶部说明。服务器仅填写名称、地址、端口和 Token;隧道共用服务器,只配置本地目标、TCP 映射端口与可选 HTTP 公网地址。没有 HTTPS、TLS、插件和证书入口。
## 实现入口
@@ -69,3 +69,5 @@ UI 修改流程见 [.agents/skills/mbrain-style/SKILL.md](.agents/skills/mbrain-
- OverviewScreens.kt:首页、能力、设置、记录。
- ConnectionScreens.kt:MCP 列表、详情、完整编辑页。
- DetailScreens.kt:工具、凭据。
+
+- 隧道详情默认只显示启用状态、已填写的访问地址和编辑入口;编辑入口合并本地目标与映射端口摘要。连接诊断、访问凭据、重连和删除放入“更多”,诊断与运行记录默认收起;错误直接显示。
diff --git a/README.md b/README.md
index 7387774..01385af 100644
--- a/README.md
+++ b/README.md
@@ -48,7 +48,7 @@ MBrain 是运行在 Android 上的 MCP 网关。它把手机自身的能力和
| **执行命令与操作文件** | 通过 Root 或 Shizuku 执行命令,浏览、读取、写入、复制和移动文件 |
| **接入其他 MCP 服务** | 添加手机本机的 HTTP MCP 服务,或由 MBrain 启动和管理 stdio MCP 进程 |
| **统一管理与连接** | 一个 MCP 地址提供工具目录,支持搜索工具、查看说明、复制连接信息和查看近期运行记录 |
-| **内网穿透** | 内置 frpc,多条 TCP / HTTPS 隧道,可公开 MBrain 或手机其他服务,支持证书和 TLS 插件 |
+| **内网穿透** | 内置 frpc,统一配置一台服务器,多条基础 TCP 隧道转发 MBrain 或手机其他服务 |
- **按需启用**:Root 和 Shizuku 各用一个开关,打开时自动检查并申请权限。
- **随时停止**:首页右下角一键启停,也可从前台通知停止网关。
@@ -105,7 +105,7 @@ adb forward tcp:8765 tcp:8765
默认端口被占用时,网关会自动使用空闲端口。请以“连接地址与凭据”中的实际地址及“使用说明”中的 ADB 命令为准。Token 加密保存在设备上,重启后保持不变;可在凭据页重置。
-**远程客户端**可在“设置 → 远程访问”添加自建 frps 隧道。支持多个隧道同时启用,各自启停和重试,网关停止时全部断开。公网 HTTPS 入口需在服务器配置,具体见[远程访问](docs/remote-access.md)。
+**远程客户端**可在“设置 → 内网穿透”配置一台自建 frps,再添加 TCP 隧道。每条隧道独立启停与重试;MCP 隧道跟随网关,自定义服务隧道独立运行。具体见[内网穿透指南](docs/remote-access.md)。
连接后可以先让 Agent 执行一个简单的只读请求:
@@ -115,7 +115,7 @@ adb forward tcp:8765 tcp:8765
## 接入 MCP 服务
-需要从公网连接时,可进入 **设置 → 内网穿透**,配置自己的 frps。支持 TCP、HTTPS 透传、`https2http` 和 `tls2raw`,自定义服务隧道独立于 MCP 网关运行。证书导入、服务器示例与运行规则见[内网穿透指南](docs/remote-access.md)。
+需要从公网连接时,可进入 **设置 → 内网穿透 → 配置服务器** 填写 frps 地址、端口和 Token。当前仅支持基础 TCP 转发,所有隧道共用一台服务器。配置示例与运行规则见[内网穿透指南](docs/remote-access.md)。
进入 **MCP → 添加服务**,选择连接方式:
@@ -140,7 +140,7 @@ HTTP 服务目前只支持回环地址。托管进程所需的程序和运行环
为什么客户端连接不上?
-先确认首页显示“运行中”,并使用凭据页中的 Token。电脑连接时还需确认实际端口的 ADB 转发成功。网关仅监听手机回环地址;远程访问通过已配置的 frp 隧道和服务器 HTTPS 入口连接。
+先确认首页显示“运行中”,并使用凭据页中的 Token。电脑连接时还需确认实际端口的 ADB 转发成功。网关仅监听手机回环地址;远程访问通过已配置的 TCP 隧道连接。
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 4d548f0..c8bd12e 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -12,8 +12,8 @@ android {
applicationId = "com.powercess.mbrain"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
- versionCode = 3
- versionName = "0.1.0"
+ versionCode = 4
+ versionName = "0.2.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildFeatures { compose = true; buildConfig = true }
diff --git a/app/src/androidTest/kotlin/com/powercess/mbrain/remote/FrpcDeviceTest.kt b/app/src/androidTest/kotlin/com/powercess/mbrain/remote/FrpcDeviceTest.kt
index 023140d..8c5191c 100644
--- a/app/src/androidTest/kotlin/com/powercess/mbrain/remote/FrpcDeviceTest.kt
+++ b/app/src/androidTest/kotlin/com/powercess/mbrain/remote/FrpcDeviceTest.kt
@@ -1,7 +1,6 @@
package com.powercess.mbrain.remote
import android.content.Intent
-import android.util.Base64
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.powercess.mbrain.gateway.GatewayRuntime
@@ -13,74 +12,55 @@ import org.junit.runner.RunWith
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
-import java.security.KeyFactory
-import java.security.KeyStore
-import java.security.spec.PKCS8EncodedKeySpec
-import javax.net.ssl.*
import kotlin.concurrent.thread
/** Run with scripts/smoke-frpc.py: a real frps is reached through adb reverse. */
@RunWith(AndroidJUnit4::class)
class FrpcDeviceTest {
- @Test fun realFrpcSupportsAllModesAndIndependentLifecycles() {
+ @Test fun realTcpFrpcSupportsSharedServerAndIndependentLifecycles() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val args = InstrumentationRegistry.getArguments()
- assumeTrue("Use scripts/smoke-frpc.py to provide the local frps fixture", args.containsKey("certificate"))
+ assumeTrue("Use scripts/smoke-frpc.py to provide the local frps fixture", args.containsKey("controlPort"))
val context = instrumentation.targetContext
- val cert = TunnelCertificate(name = "integration CA", pem = String(Base64.decode(args.getString("certificate"), Base64.DEFAULT)),
- keyPem = String(Base64.decode(args.getString("privateKey"), Base64.DEFAULT)))
- cert.validate()
- val serviceCert = cert.copy(id = newId(), name = "integration service")
- val tls = tlsContext(cert)
val backend = ServerSocket(0, 16, InetAddress.getByName("127.0.0.1"))
- val secureBackend = tls.serverSocketFactory.createServerSocket(0, 16, InetAddress.getByName("127.0.0.1"))
- serve(backend); serve(secureBackend)
- val controlPort = args.getString("controlPort")!!.toInt()
+ serve(backend)
val tcpPort = args.getString("tcpPort")!!.toInt()
- val rawPort = args.getString("rawPort")!!.toInt()
- val httpsPort = args.getString("httpsPort")!!.toInt()
- val base = TunnelConfig(name = "integration tcp", server = "127.0.0.1", serverPort = controlPort,
- token = args.getString("frpToken")!!, target = TunnelTarget.CUSTOM, localPort = backend.localPort,
- remotePort = tcpPort, tlsCaId = cert.id, tlsClientCertificateId = cert.id, tlsServerName = "phone.example.test")
- val raw = base.copy(id = newId(), name = "integration tls2raw", remotePort = rawPort, plugin = TunnelPlugin.TLS2RAW, certificateId = serviceCert.id)
- val https = base.copy(id = newId(), name = "integration MCP", target = TunnelTarget.MCP, type = ProxyType.HTTPS,
- domains = listOf("phone.example.test"), plugin = TunnelPlugin.HTTPS2HTTP, certificateId = serviceCert.id)
- val passthrough = base.copy(id = newId(), name = "integration passthrough", type = ProxyType.HTTPS,
- domains = listOf("passthrough.example.test"), localPort = secureBackend.localPort)
- val tunnels = listOf(base, raw, https, passthrough)
+ val mcpPort = args.getString("mcpPort")!!.toInt()
+ val server = TunnelServer(name = "integration", host = "127.0.0.1",
+ port = args.getString("controlPort")!!.toInt(), token = args.getString("frpToken")!!)
+ val base = TunnelConfig(name = "integration tcp", serverId = server.id,
+ target = TunnelTarget.CUSTOM, localPort = backend.localPort, remotePort = tcpPort)
+ val mcp = base.copy(id = newId(), name = "integration MCP", target = TunnelTarget.MCP, remotePort = mcpPort)
+ val tunnels = listOf(base, mcp)
fun main(block: () -> Unit) = instrumentation.runOnMainSync(block)
try {
main {
GatewayRuntime.initialize(context)
RemoteRuntime.initialize(context)
- RemoteRuntime.saveCertificate(cert); RemoteRuntime.saveCertificate(serviceCert)
+ RemoteRuntime.saveServer(server)
tunnels.forEach(RemoteRuntime::saveTunnel)
tunnels.forEach { RemoteRuntime.enableTunnel(it.id, true) }
}
- await { RemoteRuntime.status.value[https.id]?.phase == TunnelPhase.WAITING }
- await { listOf(base, raw, passthrough).all { RemoteRuntime.status.value[it.id]?.phase == TunnelPhase.CONNECTED } }
+ await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.WAITING }
+ await { RemoteRuntime.status.value[base.id]?.phase == TunnelPhase.CONNECTED }
assertTrue(request(tcpPort).contains("frpc-device-ok"))
- assertTrue(request(rawPort, tls, "phone.example.test").contains("frpc-device-ok"))
- assertTrue(request(httpsPort, tls, "passthrough.example.test").contains("frpc-device-ok"))
main { context.startForegroundService(Intent(context, MBrainService::class.java)) }
- await { GatewayRuntime.status.value.running && RemoteRuntime.status.value[https.id]?.phase == TunnelPhase.CONNECTED }
- val unauthenticated = request(httpsPort, tls, "phone.example.test", "/mcp", "invalid-test-token")
- assertTrue("MCP authentication survives HTTPS forwarding", unauthenticated.contains("401"))
- val initialized = request(httpsPort, tls, "phone.example.test", "/mcp", GatewayRuntime.status.value.token)
- assertTrue("MCP initialize works through https2http", initialized.contains("200") && initialized.contains("protocolVersion"))
+ await { GatewayRuntime.status.value.running && RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.CONNECTED }
+ assertTrue(request(mcpPort, "/mcp", "invalid-test-token").contains("401"))
+ val initialized = request(mcpPort, "/mcp", GatewayRuntime.status.value.token)
+ assertTrue(initialized.contains("200") && initialized.contains("protocolVersion"))
main { context.stopService(Intent(context, MBrainService::class.java)) }
- await { RemoteRuntime.status.value[https.id]?.phase == TunnelPhase.WAITING }
+ await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.WAITING }
assertTrue(request(tcpPort).contains("frpc-device-ok"))
- assertTrue(request(rawPort, tls, "phone.example.test").contains("frpc-device-ok"))
+ assertStreaming(tcpPort)
main {
- RemoteRuntime.enableTunnel(https.id, false)
- RemoteRuntime.saveTunnel(https.copy(target = TunnelTarget.CUSTOM, localPort = backend.localPort))
- RemoteRuntime.enableTunnel(https.id, true)
+ RemoteRuntime.enableTunnel(mcp.id, false)
+ RemoteRuntime.saveTunnel(mcp.copy(target = TunnelTarget.CUSTOM, localPort = backend.localPort))
+ RemoteRuntime.enableTunnel(mcp.id, true)
}
- await { RemoteRuntime.status.value[https.id]?.phase == TunnelPhase.CONNECTED }
- assertStreaming(tls, httpsPort)
+ await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.CONNECTED }
main { RemoteRuntime.enableTunnel(base.id, false) }
- assertTrue(request(rawPort, tls, "phone.example.test").contains("frpc-device-ok"))
+ assertTrue(request(mcpPort).contains("frpc-device-ok"))
main { RemoteRuntime.stopAll() }
await { RemoteRuntime.status.value.values.all { it.phase == TunnelPhase.OFF } }
await { java.io.File(context.noBackupFilesDir, "frpc-runtime").listFiles().orEmpty().isEmpty() }
@@ -88,9 +68,9 @@ class FrpcDeviceTest {
main {
RemoteRuntime.stopAll(); context.stopService(Intent(context, MBrainService::class.java))
tunnels.forEach { RemoteRuntime.removeTunnel(it.id) }
- RemoteRuntime.removeCertificate(serviceCert.id); RemoteRuntime.removeCertificate(cert.id)
+ RemoteRuntime.removeServer(server.id)
}
- backend.close(); secureBackend.close()
+ backend.close()
}
}
@@ -112,14 +92,9 @@ class FrpcDeviceTest {
}
}
- private fun assertStreaming(tls: SSLContext, port: Int) {
- val tcp = Socket("127.0.0.1", port)
- (tls.socketFactory.createSocket(tcp, "phone.example.test", port, true) as SSLSocket).use { socket ->
+ private fun assertStreaming(port: Int) {
+ Socket("127.0.0.1", port).use { socket ->
socket.soTimeout = 2500
- socket.sslParameters = socket.sslParameters.apply {
- serverNames = listOf(SNIHostName("phone.example.test")); endpointIdentificationAlgorithm = "HTTPS"
- }
- socket.startHandshake()
socket.outputStream.write("GET /events HTTP/1.1\r\nHost: phone.example.test\r\nAccept: text/event-stream\r\nConnection: close\r\n\r\n".toByteArray())
val reader = socket.inputStream.bufferedReader()
var line = reader.readLine()
@@ -129,32 +104,16 @@ class FrpcDeviceTest {
}
}
- private fun request(port: Int, tls: SSLContext? = null, hostname: String = "localhost", path: String = "/", token: String? = null): String {
- val tcp = Socket("127.0.0.1", port).apply { soTimeout = 10000 }
- val socket = if (tls == null) tcp else (tls.socketFactory.createSocket(tcp, hostname, port, true) as SSLSocket).apply {
- sslParameters = sslParameters.apply { serverNames = listOf(SNIHostName(hostname)); endpointIdentificationAlgorithm = "HTTPS" }
- startHandshake()
- }
- return socket.use {
+ private fun request(port: Int, path: String = "/", token: String? = null): String {
+ return Socket("127.0.0.1", port).apply { soTimeout = 10000 }.use {
val body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-03-26\",\"capabilities\":{},\"clientInfo\":{\"name\":\"frpc-test\",\"version\":\"1\"}}}"
val headers = if (token == null) "GET $path HTTP/1.1\r\n" else
"POST $path HTTP/1.1\r\nAuthorization: Bearer $token\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nContent-Length: ${body.toByteArray().size}\r\n"
- it.outputStream.write((headers + "Host: $hostname\r\nConnection: close\r\n\r\n" + if (token == null) "" else body).toByteArray())
+ it.outputStream.write((headers + "Host: localhost\r\nConnection: close\r\n\r\n" + if (token == null) "" else body).toByteArray())
it.inputStream.bufferedReader().readText()
}
}
- private fun tlsContext(cert: TunnelCertificate): SSLContext {
- val bytes = Base64.decode(cert.keyPem.lines().filterNot { it.startsWith("-----") }.joinToString(""), Base64.DEFAULT)
- val key = KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(bytes))
- val store = KeyStore.getInstance(KeyStore.getDefaultType()).apply {
- load(null); setKeyEntry("test", key, CharArray(0), cert.chain().toTypedArray()); setCertificateEntry("ca", cert.chain().first())
- }
- val km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(store, CharArray(0)) }
- val tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { init(store) }
- return SSLContext.getInstance("TLS").apply { init(km.keyManagers, tm.trustManagers, null) }
- }
-
private fun await(check: () -> Boolean) {
val deadline = System.nanoTime() + 30_000_000_000
while (!check() && System.nanoTime() < deadline) Thread.sleep(100)
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/Certificates.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/Certificates.kt
index 8b3cf77..b34277f 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/remote/Certificates.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/Certificates.kt
@@ -1,58 +1,7 @@
package com.powercess.mbrain.remote
import kotlinx.serialization.Serializable
-import java.security.KeyFactory
-import java.security.Signature
-import java.security.cert.CertificateFactory
-import java.security.cert.X509Certificate
-import java.security.spec.PKCS8EncodedKeySpec
-import java.util.Base64
-import java.util.Date
+/** Read-only legacy payload. Retained during saves; certificates are no longer imported or used. */
@Serializable
-data class TunnelCertificate(val id: String = newId(), val name: String = "", val pem: String = "", val keyPem: String = "") {
- fun chain(): List = CertificateFactory.getInstance("X.509")
- .generateCertificates(pem.byteInputStream()).map { it as X509Certificate }.also { require(it.isNotEmpty()) { "证书文件为空" } }
-
- fun validate() {
- require(validId(id) && name.isNotBlank() && name.length <= 80) { "请填写证书名称(最多 80 字)" }
- require(pem.toByteArray().size in 1..65536 && keyPem.toByteArray().size <= 65536) { "证书或私钥超过 64 KiB" }
- val cert = runCatching { chain().first() }.getOrElse { throw IllegalArgumentException("无法读取 PEM X.509 证书") }
- if (keyPem.isNotBlank()) {
- require("BEGIN PRIVATE KEY" in keyPem || "BEGIN RSA PRIVATE KEY" in keyPem) { "请导入未加密的 PKCS#8 或 RSA PKCS#1 私钥" }
- try {
- val raw = Base64.getMimeDecoder().decode(keyPem.lines().filterNot { it.startsWith("-----") }.joinToString(""))
- val pkcs8 = if ("BEGIN RSA PRIVATE KEY" in keyPem) wrapRsaKey(raw) else raw
- val algorithm = when (cert.publicKey.algorithm) { "RSA" -> "SHA256withRSA"; "EC" -> "SHA256withECDSA"; else -> error("Unsupported key") }
- val privateKey = KeyFactory.getInstance(cert.publicKey.algorithm).generatePrivate(PKCS8EncodedKeySpec(pkcs8))
- val probe = "MBrain certificate pair check".toByteArray()
- val signature = Signature.getInstance(algorithm).run { initSign(privateKey); update(probe); sign() }
- require(Signature.getInstance(algorithm).run { initVerify(cert.publicKey); update(probe); verify(signature) })
- } catch (_: Exception) { throw IllegalArgumentException("私钥格式无效或与证书不匹配(支持 RSA / EC)") }
- }
- }
-
- fun expiryMessage(now: Date = Date()): String {
- val certificate = chain().first()
- return when {
- now.before(certificate.notBefore) -> "尚未生效"
- now.after(certificate.notAfter) -> "已过期"
- certificate.notAfter.time - now.time < 30L * 86400000 -> "将在 30 天内到期"
- else -> "有效"
- }
- }
-}
-
-// Wrap the existing RSA PKCS#1 bytes in a PKCS#8 PrivateKeyInfo for Android's KeyFactory.
-private fun wrapRsaKey(raw: ByteArray): ByteArray {
- fun der(tag: Int, bytes: ByteArray): ByteArray {
- val length = bytes.size
- val size = if (length < 128) byteArrayOf(length.toByte()) else {
- val parts = listOf(length ushr 24, length ushr 16, length ushr 8, length).map { (it and 255).toByte() }.dropWhile { it == 0.toByte() }
- byteArrayOf((128 or parts.size).toByte()) + parts.toByteArray()
- }
- return byteArrayOf(tag.toByte()) + size + bytes
- }
- val rsaIdentifier = byteArrayOf(0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86.toByte(), 0x48, 0x86.toByte(), 0xf7.toByte(), 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00)
- return der(0x30, byteArrayOf(0x02, 0x01, 0x00) + rsaIdentifier + der(0x04, raw))
-}
+data class TunnelCertificate(val id: String = newId(), val name: String = "", val pem: String = "", val keyPem: String = "")
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/FrpcController.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/FrpcController.kt
index 1520cb6..720ee29 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/remote/FrpcController.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/FrpcController.kt
@@ -16,7 +16,7 @@ class FrpcController(
},
) : AutoCloseable {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
- private class Entry(val config: TunnelConfig, val endpoint: Pair, val certificates: List) {
+ private class Entry(val config: TunnelConfig, val endpoint: Pair) {
var process: Process? = null
lateinit var job: Job
var status = TunnelStatus(TunnelPhase.CONNECTING)
@@ -24,19 +24,18 @@ class FrpcController(
private val entries = mutableMapOf()
private var closed = false
- @Synchronized fun reconcile(configs: List, port: Int?, certificates: List = emptyList()) {
+ @Synchronized fun reconcile(configs: List, port: Int?) {
if (closed) return
val desired = configs.filter { it.enabled && it.endpoint(port) != null }.associateBy { it.id }
entries.keys.toList().forEach { id ->
val entry = entries.getValue(id)
- if (desired[id] != entry.config || desired[id]?.endpoint(port) != entry.endpoint ||
- certificates.filter { it.id in entry.config.certificateIds() } != entry.certificates) stop(id)
+ if (desired[id] != entry.config || desired[id]?.endpoint(port) != entry.endpoint) stop(id)
}
configs.forEach { config ->
val endpoint = config.endpoint(port)
if (!config.enabled || endpoint == null) changed(config.id, TunnelStatus(if (config.enabled) TunnelPhase.WAITING else TunnelPhase.OFF))
else if (config.id !in entries) {
- val entry = Entry(config, endpoint, certificates.filter { it.id in config.certificateIds() })
+ val entry = Entry(config, endpoint)
entry.job = scope.launch(start = CoroutineStart.LAZY) { supervise(entry) }
entries[config.id] = entry
changed(config.id, entry.status)
@@ -57,6 +56,9 @@ class FrpcController(
@Synchronized private fun publish(entry: Entry, phase: TunnelPhase, error: String? = null) {
if (entries[entry.config.id] !== entry) return
+ // A new connection attempt does not resolve the preceding failure. Keep its reason
+ // until the state changes, rather than alternating error/retry rows on every attempt.
+ if (phase == TunnelPhase.RETRYING && entry.status.phase == TunnelPhase.RETRYING && error == null) return
if (entry.status.phase == phase && entry.status.error == error) return
entry.status = entry.status.copy(phase = phase, error = error, events = (listOf(error ?: phase.label) + entry.status.events).take(40),
serverConnected = when (phase) { TunnelPhase.CONNECTED -> true; TunnelPhase.ERROR -> entry.status.serverConnected; else -> false })
@@ -80,13 +82,7 @@ class FrpcController(
check(executable.isFile && executable.canExecute()) { "此设备的 frpc 不可用" }
directory.mkdirs()
attemptDirectory = java.nio.file.Files.createTempDirectory(directory.toPath(), "frpc-").toFile()
- val paths = entry.certificates.associate { certificate ->
- certificate.validate()
- certificate.id to CertificatePaths(
- privateFile(attemptDirectory, "${certificate.id}.crt", certificate.pem).absolutePath,
- certificate.keyPem.takeIf { it.isNotBlank() }?.let { privateFile(attemptDirectory, "${certificate.id}.key", it).absolutePath })
- }
- val configFile = privateFile(attemptDirectory, "frpc.json", entry.config.frpcConfig(entry.endpoint, paths))
+ val configFile = privateFile(attemptDirectory, "frpc.json", entry.config.frpcConfig(entry.endpoint))
currentCoroutineContext().ensureActive()
synchronized(this) {
if (entries[entry.config.id] !== entry) throw CancellationException()
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/RemoteRuntime.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/RemoteRuntime.kt
index ffc796b..e320b80 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/remote/RemoteRuntime.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/RemoteRuntime.kt
@@ -34,7 +34,11 @@ object RemoteRuntime {
@Synchronized fun saveTunnel(tunnel: TunnelConfig) {
check(mutableConfig.value.tunnels.none { it.id == tunnel.id && it.enabled }) { "请先关闭此隧道再编辑" }
val old = mutableConfig.value
- persist(old.copy(tunnels = old.tunnels.filterNot { it.id == tunnel.id } + tunnel.copy(enabled = false)))
+ old.resolve(tunnel).requireBasicTcp()
+ require(tunnel.serverId.isEmpty() || tunnel.serverId == old.server?.id) { "请使用当前服务器" }
+ val next = old.copy(tunnels = old.tunnels.filterNot { it.id == tunnel.id } + tunnel.copy(enabled = false)).migrateServers()
+ require(next.tunnels.first { it.id == tunnel.id }.serverId == next.server?.id) { "请使用当前服务器" }
+ persist(next)
}
@Synchronized fun removeTunnel(id: String) {
@@ -43,18 +47,9 @@ object RemoteRuntime {
refresh()
}
- @Synchronized fun saveCertificate(certificate: TunnelCertificate) {
- certificate.validate()
- val old = mutableConfig.value
- persist(old.copy(certificates = old.certificates.filterNot { it.id == certificate.id } + certificate))
- // Replacing a referenced certificate restarts only affected tunnels.
- refresh()
- }
+ @Synchronized fun saveServer(server: TunnelServer) { persist(mutableConfig.value.saveServer(server)) }
- @Synchronized fun removeCertificate(id: String) {
- check(mutableConfig.value.tunnels.none { id in it.certificateIds() }) { "此证书仍被隧道引用,请先修改隧道配置" }
- persist(mutableConfig.value.copy(certificates = mutableConfig.value.certificates.filterNot { it.id == id }))
- }
+ @Synchronized fun removeServer(id: String) { persist(mutableConfig.value.removeServer(id)) }
private fun persist(next: RemoteConfig) {
check(!loadFailed) { "原配置读取失败,不能覆盖;请重新启动应用后重试" }
@@ -66,6 +61,11 @@ object RemoteRuntime {
check(!loadFailed) { "隧道配置不可用" }
val old = mutableConfig.value
check(old.tunnels.any { it.id == id }) { "隧道不存在" }
+ if (enabled) {
+ val tunnel = old.tunnels.first { it.id == id }
+ require(tunnel.serverId == old.server?.id) { "此隧道使用旧服务器,请先编辑并保存隧道" }
+ old.resolve(tunnel).requireBasicTcp()
+ }
val next = old.copy(tunnels = old.tunnels.map { if (it.id == id) it.copy(enabled = enabled) else it })
next.validate()
mutableConfig.value = next
@@ -111,7 +111,7 @@ object RemoteRuntime {
}
private fun refresh() {
- controller?.reconcile(mutableConfig.value.tunnels, mcpPort, mutableConfig.value.certificates)
+ controller?.reconcile(mutableConfig.value.tunnels.map(mutableConfig.value::resolve), mcpPort)
if (mutableConfig.value.tunnels.none { it.enabled } && controller != null) {
controller?.close(); controller = null
context.stopService(Intent(context, TunnelService::class.java))
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelConfig.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelConfig.kt
index 6c43d44..b0e809b 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelConfig.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelConfig.kt
@@ -22,6 +22,7 @@ internal fun validHost(value: String): Boolean = value.isNotBlank() && value.len
data class TunnelConfig(
val id: String = newId(),
val name: String = "",
+ val serverId: String = "",
val server: String = "",
val serverPort: Int = 7000,
val token: String = "",
@@ -42,6 +43,11 @@ data class TunnelConfig(
@Transient val enabled: Boolean = false,
) {
val proxyName: String get() = "mbrain-$id"
+ val accessUrl: String get() = publicUrl.ifBlank {
+ if (target == TunnelTarget.MCP && validHost(server) && remotePort in 1..65535)
+ URI("http", null, server, remotePort, "/mcp", null, null).toASCIIString()
+ else ""
+ }
fun endpoint(mcpPort: Int?): Pair? = if (target == TunnelTarget.MCP)
mcpPort?.let { "127.0.0.1" to it } else localHost to localPort
@@ -54,7 +60,7 @@ data class TunnelConfig(
require(validHost(localHost) && localPort in 1..65535) { "请填写有效的本地地址和端口" }
require(type != ProxyType.HTTPS || plugin != TunnelPlugin.TLS2RAW) { "TLS → TCP 插件需要 TCP 代理" }
require(target != TunnelTarget.MCP || type != ProxyType.HTTPS || plugin == TunnelPlugin.HTTPS2HTTP) { "MBrain 使用 HTTP,请选择 HTTPS → HTTP 插件" }
- if (type == ProxyType.TCP) require(remotePort in 1..65535) { "映射端口应为 1–65535" }
+ if (type == ProxyType.TCP) require(remotePort in 1..65535) { "公网访问端口应为 1–65535" }
else require(domains.isNotEmpty() && domains.size <= 20 && domains.distinctBy { it.lowercase() }.size == domains.size &&
domains.all { validHost(it) && ':' !in it && it.contains('.') }) { "请填写有效且不重复的域名(不含协议或端口)" }
require(plugin == TunnelPlugin.NONE || validId(certificateId)) { "请选择包含私钥的服务证书" }
@@ -69,48 +75,41 @@ data class TunnelConfig(
}
require(others.none { other -> other.id != id && other.server.equals(server, true) && other.type == type &&
(if (type == ProxyType.TCP) other.remotePort == remotePort else other.serverPort == serverPort &&
- other.domains.any { domain -> domains.any { it.equals(domain, true) } }) }) { "此服务器的映射端口或域名已被其他隧道使用" }
+ other.domains.any { domain -> domains.any { it.equals(domain, true) } }) }) { "此服务器的公网访问端口或域名已被其他隧道使用" }
+ }
+
+ // Legacy fields above remain readable so old configurations can be edited safely.
+ fun supportsBasicTcp(): Boolean = type == ProxyType.TCP && plugin == TunnelPlugin.NONE &&
+ tlsCaId.isEmpty() && tlsClientCertificateId.isEmpty() && tlsServerName.isEmpty()
+
+ fun requireBasicTcp() {
+ require(supportsBasicTcp()) { "此配置使用已停用的 HTTPS / TLS 功能,请重新编辑为 TCP 配置" }
+ require(publicUrl.isBlank() || URI(publicUrl).scheme == "http") { "当前仅支持 HTTP 公网地址" }
}
- fun frpcConfig(endpoint: Pair, certificatePaths: Map = emptyMap()): String {
+ fun asBasicTcp() = copy(type = ProxyType.TCP, plugin = TunnelPlugin.NONE, domains = emptyList(),
+ certificateId = "", hostHeaderRewrite = "", tlsServerName = "", tlsCaId = "", tlsClientCertificateId = "",
+ publicUrl = publicUrl.takeIf { it.isBlank() || runCatching { URI(it).scheme == "http" }.getOrDefault(false) }.orEmpty())
+
+ fun frpcConfig(endpoint: Pair): String {
validate()
+ requireBasicTcp()
require(validHost(endpoint.first) && endpoint.second in 1..65535)
- fun certificate(id: String) = requireNotNull(certificatePaths[id]) { "证书不可用" }
return buildJsonObject {
put("serverAddr", server); put("serverPort", serverPort); put("loginFailExit", false)
putJsonObject("auth") { put("method", "token"); put("token", token) }
- putJsonObject("transport") { putJsonObject("tls") {
- put("enable", true)
- if (tlsServerName.isNotEmpty()) put("serverName", tlsServerName)
- if (tlsCaId.isNotEmpty()) put("trustedCaFile", certificate(tlsCaId).certificate)
- if (tlsClientCertificateId.isNotEmpty()) {
- put("certFile", certificate(tlsClientCertificateId).certificate)
- put("keyFile", requireNotNull(certificate(tlsClientCertificateId).key))
- }
- } }
+ // Transport encryption is independent of the TCP proxy and requires no HTTPS configuration.
+ putJsonObject("transport") { putJsonObject("tls") { put("enable", true) } }
putJsonObject("log") { put("to", "console"); put("level", "info"); put("disablePrintColor", true) }
putJsonArray("proxies") { addJsonObject {
- put("name", proxyName); put("type", type.name.lowercase())
- if (type == ProxyType.TCP) put("remotePort", remotePort)
- else putJsonArray("customDomains") { domains.forEach { add(it) } }
- if (plugin == TunnelPlugin.NONE) {
- put("localIP", endpoint.first); put("localPort", endpoint.second)
- } else putJsonObject("plugin") {
- put("type", plugin.wireName)
- put("localAddr", "${if (':' in endpoint.first) "[${endpoint.first}]" else endpoint.first}:${endpoint.second}")
- put("crtPath", certificate(certificateId).certificate)
- put("keyPath", requireNotNull(certificate(certificateId).key))
- if (plugin == TunnelPlugin.HTTPS2HTTP && hostHeaderRewrite.isNotEmpty()) put("hostHeaderRewrite", hostHeaderRewrite)
- }
+ put("name", proxyName); put("type", "tcp"); put("remotePort", remotePort)
+ put("localIP", endpoint.first); put("localPort", endpoint.second)
} }
}.toString()
}
- fun certificateIds(): Set = setOf(
- certificateId.takeIf { plugin != TunnelPlugin.NONE }.orEmpty(), tlsCaId, tlsClientCertificateId
- ).filter { it.isNotEmpty() }.toSet()
+
}
-data class CertificatePaths(val certificate: String, val key: String?)
enum class TunnelPhase(val label: String) {
OFF("已关闭"), WAITING("等待 MCP 网关"), CONNECTING("连接中"), CONNECTED("隧道已注册"), RETRYING("重连中"), ERROR("连接失败")
}
@@ -123,7 +122,7 @@ data class TunnelStatus(
internal fun classifyFrpcLine(line: String): Pair? = when {
"start proxy success" in line -> TunnelPhase.CONNECTED to null
"token" in line && listOf("mismatch", "invalid", "not match", "doesn't match").any { it in line } -> TunnelPhase.ERROR to "服务器认证失败"
- "port already used" in line || "port already in use" in line -> TunnelPhase.ERROR to "服务器映射端口被占用"
+ "port already used" in line || "port already in use" in line -> TunnelPhase.ERROR to "服务器公网访问端口被占用"
"start error" in line || "start proxy error" in line -> TunnelPhase.ERROR to "隧道注册失败,请检查端口、域名和服务器配置"
"login to server failed" in line || "connect to server error" in line -> TunnelPhase.RETRYING to "无法连接服务器,正在重试"
listOf("try to connect to server", "reconnect", "heartbeat timeout", "control writer is closing", "read from control").any { it in line } -> TunnelPhase.RETRYING to null
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelServer.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelServer.kt
new file mode 100644
index 0000000..5e995f9
--- /dev/null
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelServer.kt
@@ -0,0 +1,35 @@
+package com.powercess.mbrain.remote
+
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class TunnelServer(
+ val id: String = newId(),
+ val name: String = "",
+ val host: String = "",
+ val port: Int = 7000,
+ val token: String = "",
+ val tlsServerName: String = "",
+ val tlsCaId: String = "",
+ val tlsClientCertificateId: String = "",
+) {
+ fun applyTo(tunnel: TunnelConfig) = tunnel.copy(server = host, serverPort = port, token = token,
+ tlsServerName = tlsServerName, tlsCaId = tlsCaId, tlsClientCertificateId = tlsClientCertificateId)
+
+ fun validate() {
+ require(validId(id)) { "服务器 ID 无效" }
+ require(name.isNotBlank() && name.length <= 80) { "请填写服务器名称(最多 80 字)" }
+ applyTo(TunnelConfig(name = name, remotePort = 1)).validate()
+ }
+
+
+ companion object {
+ fun from(tunnel: TunnelConfig) = TunnelServer(id = tunnel.id, name = tunnel.server.take(80), host = tunnel.server,
+ port = tunnel.serverPort, token = tunnel.token, tlsServerName = tunnel.tlsServerName,
+ tlsCaId = tunnel.tlsCaId, tlsClientCertificateId = tunnel.tlsClientCertificateId)
+ }
+}
+
+/** Inline fields are retained only to read old files and feed the existing frpc controller. */
+fun TunnelConfig.referenceServer(id: String) = copy(serverId = id, server = "", serverPort = 7000,
+ token = "", tlsServerName = "", tlsCaId = "", tlsClientCertificateId = "")
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelStore.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelStore.kt
index bdf9b34..d81b10a 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelStore.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelStore.kt
@@ -5,23 +5,59 @@ import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
-data class RemoteConfig(val tunnels: List = emptyList(), val certificates: List = emptyList()) {
+data class RemoteConfig(val tunnels: List = emptyList(), val certificates: List = emptyList(),
+ val servers: List = emptyList()) {
+ // The list is retained only for reading older multi-server configurations.
+ val server: TunnelServer? get() = servers.firstOrNull()
+
+ fun resolve(tunnel: TunnelConfig): TunnelConfig = if (tunnel.serverId.isEmpty()) tunnel else
+ requireNotNull(servers.find { it.id == tunnel.serverId }) { "请选择已配置的服务器" }.applyTo(tunnel)
+
+ fun migrateServers(): RemoteConfig {
+ val migrated = servers.toMutableList()
+ val next = tunnels.map { tunnel ->
+ if (tunnel.serverId.isNotEmpty()) tunnel else {
+ val legacy = TunnelServer.from(tunnel)
+ val candidate = if (migrated.any { it.id == legacy.id }) legacy.copy(id = newId()) else legacy
+ val server = migrated.find { it.copy(id = candidate.id, name = candidate.name) == candidate }
+ ?: run {
+ var name = candidate.name
+ var suffix = 2
+ while (migrated.any { it.name == name }) { name = "${candidate.name.take(70)} (${suffix++})" }
+ candidate.copy(name = name).also { migrated.add(it) }
+ }
+ tunnel.referenceServer(server.id)
+ }
+ }
+ return copy(tunnels = next, servers = migrated)
+ }
+
+ fun saveServer(server: TunnelServer): RemoteConfig {
+ require(this.server == null || this.server?.id == server.id) { "当前只支持配置一台服务器" }
+ server.applyTo(TunnelConfig(name = server.name, remotePort = 1)).requireBasicTcp()
+ require(tunnels.none { it.serverId == server.id && it.enabled }) { "请先关闭使用此服务器的隧道再编辑" }
+ return copy(servers = if (this.server == null) listOf(server) else servers.map { if (it.id == server.id) server else it }).also { it.validate() }
+ }
+
+ fun removeServer(id: String): RemoteConfig {
+ require(tunnels.none { it.serverId == id }) { "此服务器仍被隧道使用,请先修改或删除相关隧道" }
+ return copy(servers = servers.filterNot { it.id == id })
+ }
+
fun validate() {
+ require(servers.map { it.id }.distinct().size == servers.size) { "服务器 ID 重复" }
+ servers.forEach { it.validate() }
require(tunnels.map { it.id }.distinct().size == tunnels.size && certificates.map { it.id }.distinct().size == certificates.size)
- tunnels.forEach { tunnel ->
- tunnel.validate(tunnels)
- tunnel.certificateIds().forEach { id -> require(certificates.any { it.id == id }) { "引用的证书不存在" } }
- if (tunnel.plugin != TunnelPlugin.NONE) require(certificates.first { it.id == tunnel.certificateId }.keyPem.isNotBlank()) { "服务证书需要私钥" }
- if (tunnel.tlsClientCertificateId.isNotEmpty()) require(certificates.first { it.id == tunnel.tlsClientCertificateId }.keyPem.isNotBlank()) { "客户端证书需要私钥" }
- }
+ val resolved = tunnels.map(::resolve)
+ resolved.forEach { it.validate(resolved) }
}
}
class TunnelStore(private val secrets: SecretStore) {
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
- fun load(): RemoteConfig = secrets.read("remote_config_v2")?.let { json.decodeFromString(it) }
- ?.also { it.validate(); it.certificates.forEach(TunnelCertificate::validate) }
- ?: secrets.read("tunnels")?.let { RemoteConfig(tunnels = json.decodeFromString>(it)).also(RemoteConfig::validate) }
- ?: RemoteConfig()
+ fun load(): RemoteConfig = (secrets.read("remote_config_v2")?.let { json.decodeFromString(it) }
+ ?: secrets.read("tunnels")?.let { RemoteConfig(tunnels = json.decodeFromString>(it)) }
+ ?: RemoteConfig()).also { it.validate() }
+ .migrateServers().also { it.validate() }
fun save(config: RemoteConfig) { config.validate(); secrets.write("remote_config_v2", json.encodeToString(config)) }
}
diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/CertificateScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/CertificateScreens.kt
deleted file mode 100644
index 2d486db..0000000
--- a/app/src/main/kotlin/com/powercess/mbrain/ui/CertificateScreens.kt
+++ /dev/null
@@ -1,119 +0,0 @@
-package com.powercess.mbrain.ui
-
-import androidx.activity.compose.BackHandler
-import androidx.activity.compose.rememberLauncherForActivityResult
-import androidx.activity.result.contract.ActivityResultContracts
-import androidx.compose.foundation.layout.*
-import androidx.compose.foundation.lazy.items
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.outlined.*
-import androidx.compose.material3.*
-import androidx.compose.runtime.*
-import androidx.compose.runtime.saveable.rememberSaveable
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.unit.dp
-import com.powercess.mbrain.remote.TunnelCertificate
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
-import java.text.DateFormat
-
-@Composable
-internal fun CertificatesScreen(certificates: List, edit: (String) -> Unit, remove: (String) -> Unit) {
- ScreenList(groupedRows = true) {
- item { SecondaryAction("导入证书", onClick = { edit("new") }) }
- if (certificates.isEmpty()) item { EmptyState("暂无证书") }
- groupedItems(certificates, key = { it.id }) { certificate ->
- val details = remember(certificate) {
- runCatching { "${certificate.expiryMessage()} · 到期 ${DateFormat.getDateInstance().format(certificate.chain().first().notAfter)}" }.getOrDefault("证书不可读")
- }
- Column {
- ActionRow(certificate.name, details, Icons.Outlined.VerifiedUser, { edit(certificate.id) })
- GroupDivider()
- ActionRow(if (certificate.keyPem.isBlank()) "仅证书 / CA" else "包含私钥", null, Icons.Outlined.Key,
- trailing = { IconButton(onClick = { remove(certificate.id) }) { Icon(Icons.Outlined.DeleteOutline, "删除${certificate.name}") } })
- }
- }
- }
-}
-
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable
-internal fun CertificateEditor(initial: TunnelCertificate, dismiss: () -> Unit, save: (TunnelCertificate) -> Unit) {
- val context = LocalContext.current
- val scope = rememberCoroutineScope()
- var name by rememberSaveable { mutableStateOf(initial.name) }
- var pem by rememberSaveable { mutableStateOf(initial.pem) }
- var keyPem by rememberSaveable { mutableStateOf(initial.keyPem) }
- var importingKey by rememberSaveable { mutableStateOf(false) }
- var busy by remember { mutableStateOf(false) }
- var error by rememberSaveable { mutableStateOf(null) }
- var discard by rememberSaveable { mutableStateOf(false) }
- val dirty = name != initial.name || pem != initial.pem || keyPem != initial.keyPem
- val close = { if (!busy) { if (dirty) discard = true else dismiss() } }
- val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
- if (uri != null) scope.launch {
- busy = true
- try {
- val text = withContext(Dispatchers.IO) {
- val bytes = requireNotNull(context.contentResolver.openInputStream(uri)).use { stream ->
- val out = java.io.ByteArrayOutputStream()
- val buffer = ByteArray(4096)
- while (true) {
- val count = stream.read(buffer)
- if (count < 0) break
- require(out.size() + count <= 65536) { "文件超过 64 KiB" }
- out.write(buffer, 0, count)
- }
- out.toByteArray()
- }
- bytes.toString(Charsets.UTF_8)
- }
- if (importingKey) keyPem = text else pem = text
- error = null
- } catch (_: Exception) { error = "读取失败,请选择不超过 64 KiB 的 PEM 文件" }
- finally { busy = false }
- }
- }
- Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
- BackHandler { close() }
- Scaffold(modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding(), contentWindowInsets = WindowInsets(0, 0, 0, 0),
- topBar = { TopAppBar(title = { Text("证书配置") }, navigationIcon = {
- IconButton(onClick = close, enabled = !busy) { Icon(Icons.Outlined.Close, "关闭编辑") }
- }, colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.background), windowInsets = WindowInsets(0, 0, 0, 0)) },
- bottomBar = { EditorSaveBar(if (busy) "处理中…" else "保存证书", enabled = !busy) {
- scope.launch {
- busy = true
- try {
- val next = initial.copy(name = name.trim(), pem = pem.trim(), keyPem = keyPem.trim())
- withContext(Dispatchers.IO) { next.validate() }
- save(next)
- } catch (e: Exception) { error = e.message ?: "保存失败" }
- finally { busy = false }
- }
- } },
- containerColor = MaterialTheme.colorScheme.background) { padding ->
- Box(Modifier.padding(padding).consumeWindowInsets(padding)) { ScreenList {
- error?.let { item(key = "error") { Note(it, error = true) } }
- item(key = "name") { TunnelField("证书名称", name, { name = it }) }
- item(key = "certificate") { SecondaryAction(if (pem.isBlank()) "选择证书链文件" else "替换证书链文件", enabled = !busy,
- onClick = { importingKey = false; picker.launch(arrayOf("*/*")) }) }
- if (pem.isNotBlank()) item(key = "details") {
- val info = remember(pem) { runCatching {
- val cert = initial.copy(pem = pem).chain().first()
- "${cert.subjectX500Principal.name}\n到期:${DateFormat.getDateInstance().format(cert.notAfter)}"
- }.getOrDefault("文件已读取,保存时验证证书格式") }
- Note(info)
- }
- item(key = "key") { SecondaryAction(if (keyPem.isBlank()) "选择私钥文件(CA 可省略)" else "替换私钥文件", enabled = !busy,
- onClick = { importingKey = true; picker.launch(arrayOf("*/*")) }) }
- if (keyPem.isNotBlank()) item(key = "key-present") { Group { ActionRow("私钥已导入", "保存时检查与证书是否匹配", Icons.Outlined.Key,
- trailing = { TextButton(onClick = { keyPem = "" }, enabled = !busy) { Text("清除") } }) } }
- item(key = "help") { Note("支持 PEM X.509 证书链,以及未加密的 RSA / EC PKCS#8 或 RSA PKCS#1 私钥。证书与私钥加密保存在应用内;替换后仅重连引用它的隧道。") }
- } }
- }
- if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text("放弃未保存的修改?") },
- confirmButton = { TextButton(onClick = dismiss) { Text("放弃修改") } }, dismissButton = { TextButton(onClick = { discard = false }) { Text("继续编辑") } })
- }
-}
diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/MBrainApp.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/MBrainApp.kt
index c1af3b4..cb67ca8 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/ui/MBrainApp.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/ui/MBrainApp.kt
@@ -43,7 +43,7 @@ fun MBrainApp(start: () -> Unit, stop: () -> Unit) {
var themePicker by rememberSaveable { mutableStateOf(false) }
var removal by rememberSaveable { mutableStateOf(null) }
var tunnelEditor by rememberSaveable { mutableStateOf(null) }
- var certificateEditor by rememberSaveable { mutableStateOf(null) }
+ var serverEditor by rememberSaveable { mutableStateOf(null) }
var remoteRemoval by rememberSaveable { mutableStateOf(null) }
val snackbar = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
@@ -65,11 +65,10 @@ fun MBrainApp(start: () -> Unit, stop: () -> Unit) {
route == "activity" -> "运行记录"
route == "about" -> "关于 MBrain"
route == "remote" -> "内网穿透"
- route == "certificates" -> "证书管理"
route.startsWith("tunnel:") -> remote.tunnels.find { it.id == route.substringAfter(':') }?.name ?: "隧道详情"
else -> "使用说明"
}
- BackHandler(stack.size > 1 && editor == null && tunnelEditor == null && certificateEditor == null) { back() }
+ BackHandler(stack.size > 1 && editor == null && tunnelEditor == null && serverEditor == null) { back() }
LaunchedEffect(status.error) { status.error?.let { snackbar.showSnackbar(it) } }
val holder = rememberSaveableStateHolder()
MBrainTheme(dark) {
@@ -108,11 +107,16 @@ fun MBrainApp(start: () -> Unit, stop: () -> Unit) {
key == "activity" -> ActivityScreen(status)
key == "about" -> AboutScreen()
key == "help" -> HelpScreen(status, copy)
- key == "remote" -> RemoteScreen(remote, tunnelStates, open, { tunnelEditor = "new" }, notify)
- key == "certificates" -> CertificatesScreen(remote.certificates, { certificateEditor = it }, { remoteRemoval = "certificate:$it" })
+ key == "remote" -> RemoteScreen(remote, tunnelStates, { destination ->
+ if (destination == "servers") serverEditor = remote.server?.id ?: "new" else open(destination)
+ }, {
+ if (remote.server == null) serverEditor = "new" else tunnelEditor = "new"
+ }, notify)
key.startsWith("tunnel:") -> {
val id = key.substringAfter(':')
- TunnelScreen(remote.tunnels.find { it.id == id }, tunnelStates[id] ?: TunnelStatus(), status, open,
+ TunnelScreen(remote.tunnels.find { it.id == id }?.let(remote::resolve), tunnelStates[id] ?: TunnelStatus(), status, { destination ->
+ if (destination == "servers") serverEditor = remote.server?.id ?: "new" else open(destination)
+ },
{ tunnelEditor = it }, { remoteRemoval = "tunnel:$it" }, copy, notify)
}
}
@@ -149,26 +153,26 @@ fun MBrainApp(start: () -> Unit, stop: () -> Unit) {
}
tunnelEditor?.let { editorKey -> key("tunnel-editor:$editorKey") {
- val initial = remember(editorKey) { if (editorKey == "new") TunnelConfig() else remote.tunnels.find { it.id == editorKey } }
+ val initial = remember(editorKey) { if (editorKey == "new") TunnelConfig(serverId = remote.server?.id.orEmpty()) else remote.tunnels.find { it.id == editorKey } }
if (initial != null) TunnelEditor(initial, editorKey != "new", remote, { tunnelEditor = null }) { next ->
RemoteRuntime.saveTunnel(next); tunnelEditor = null
if (editorKey == "new") open("tunnel:${next.id}")
notify("已保存隧道")
}
} }
- certificateEditor?.let { editorKey -> key("certificate-editor:$editorKey") {
- val initial = remember(editorKey) { if (editorKey == "new") TunnelCertificate() else remote.certificates.find { it.id == editorKey } }
- if (initial != null) CertificateEditor(initial, { certificateEditor = null }) { next ->
- RemoteRuntime.saveCertificate(next); certificateEditor = null; notify("已保存证书")
+ serverEditor?.let { editorKey -> key("server-editor:$editorKey") {
+ val initial = remember(editorKey) { if (editorKey == "new") TunnelServer() else remote.servers.find { it.id == editorKey } }
+ if (initial != null) ServerEditor(initial, editorKey != "new", remote, { serverEditor = null }, { remoteRemoval = "server:${initial.id}" }) { next ->
+ RemoteRuntime.saveServer(next); serverEditor = null; notify("已保存服务器")
}
} }
remoteRemoval?.let { target ->
- AlertDialog(onDismissRequest = { remoteRemoval = null }, title = { Text(if (target.startsWith("tunnel:")) "删除此隧道?" else "删除此证书?") },
- text = { Text(if (target.startsWith("tunnel:")) "此隧道会停止并移除配置。" else "仍被隧道引用的证书不能删除。") },
+ AlertDialog(onDismissRequest = { remoteRemoval = null }, title = { Text(if (target.startsWith("tunnel:")) "删除此隧道?" else "删除此服务器?") },
+ text = { Text(if (target.startsWith("tunnel:")) "此隧道会停止并移除配置。" else "删除已保存的服务器配置,之后可重新添加。") },
confirmButton = { TextButton(onClick = {
runCatching {
if (target.startsWith("tunnel:")) { RemoteRuntime.removeTunnel(target.substringAfter(':')); back() }
- else RemoteRuntime.removeCertificate(target.substringAfter(':'))
+ else { RemoteRuntime.removeServer(target.substringAfter(':')); serverEditor = null }
}.onFailure { notify(it.message ?: "删除失败") }
remoteRemoval = null
}) { Text("删除") } }, dismissButton = { TextButton(onClick = { remoteRemoval = null }) { Text("取消") } })
diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/OverviewScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/OverviewScreens.kt
index 85193ff..8b822e4 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/ui/OverviewScreens.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/ui/OverviewScreens.kt
@@ -148,7 +148,7 @@ internal fun SettingsScreen(appearance: String, open: (String) -> Unit, theme: (
item { Group {
ActionRow("地址与凭据", "供 Agent 连接本机网关", Icons.Outlined.Key, { open("credentials") })
GroupDivider()
- ActionRow("内网穿透", "多隧道、HTTPS 与证书", Icons.Outlined.Public, { open("remote") })
+ ActionRow("内网穿透", "服务器与 TCP 隧道", Icons.Outlined.Public, { open("remote") })
GroupDivider()
ActionRow("使用说明", "电脑连接、运行方式与限制", Icons.Outlined.HelpOutline, { open("help") })
} }
diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/RemoteScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/RemoteScreens.kt
index a1d8a1f..20a0f04 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/ui/RemoteScreens.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/ui/RemoteScreens.kt
@@ -21,6 +21,7 @@ import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.*
import androidx.compose.ui.unit.dp
import com.powercess.mbrain.gateway.GatewayStatus
+import com.powercess.mbrain.gateway.GatewayRuntime
import com.powercess.mbrain.remote.*
import kotlinx.coroutines.launch
import kotlinx.serialization.json.*
@@ -30,8 +31,11 @@ internal fun RemoteScreen(config: RemoteConfig, states: Map
@@ -56,52 +60,55 @@ private fun TunnelSwitch(tunnel: TunnelConfig, notify: (String) -> Unit) {
internal fun TunnelScreen(tunnel: TunnelConfig?, state: TunnelStatus, gateway: GatewayStatus, open: (String) -> Unit,
edit: (String) -> Unit, remove: (String) -> Unit, copy: (String, String) -> Unit, notify: (String) -> Unit) {
if (tunnel == null) return
+ var more by remember { mutableStateOf(false) }
+ var diagnostics by rememberSaveable(tunnel.id) { mutableStateOf(false) }
+ val target = if (tunnel.target == TunnelTarget.MCP) "MCP 网关 · 127.0.0.1:${gateway.port ?: GatewayRuntime.PORT}" else "${tunnel.localHost}:${tunnel.localPort}"
ScreenList {
- item { Group { ActionRow("启用隧道", state.phase.label, Icons.Outlined.Public, trailing = { TunnelSwitch(tunnel, notify) }) } }
+ item { Group { ActionRow("启用隧道", state.phase.label, Icons.Outlined.Public,
+ trailing = { TunnelSwitch(tunnel, notify) }) } }
state.error?.let { item { Note(it, error = true) } }
- item { Group {
- ActionRow("frps 连接", if (state.serverConnected) "已连接" else "未连接", Icons.Outlined.Dns)
- GroupDivider(); ActionRow("隧道注册", state.phase.label, Icons.Outlined.Link)
- GroupDivider(); ActionRow("本地服务", state.localHealth.label, Icons.Outlined.PhoneAndroid)
- } }
- if (state.phase == TunnelPhase.WAITING) item { Note("启动首页的 MCP 网关后,此隧道会自动连接。其他自定义隧道不受影响。") }
- if (tunnel.enabled && state.phase != TunnelPhase.WAITING) item {
- SecondaryAction("重新连接", onClick = { RemoteRuntime.retry(tunnel.id) })
- }
- item { SectionLabel("连接信息") }
- item { Group {
- ActionRow("公网地址", tunnel.publicUrl.ifBlank { "未填写" }, Icons.Outlined.Link,
- if (tunnel.publicUrl.isNotBlank()) ({ copy("公网地址", tunnel.publicUrl) }) else null)
- if (tunnel.target == TunnelTarget.MCP) {
- if (tunnel.publicUrl.isNotBlank() && gateway.running && gateway.token != null) {
- GroupDivider()
- ActionRow("复制 MCP 客户端配置", "包含地址与访问 Token", Icons.Outlined.DataObject, {
- val payload = buildJsonObject { putJsonObject("mcpServers") { putJsonObject(tunnel.name) {
- put("url", tunnel.publicUrl)
- putJsonObject("headers") { put("Authorization", "Bearer ${gateway.token}") }
- } } }
- copy("客户端配置", Json { prettyPrint = true }.encodeToString(JsonObject.serializer(), payload))
- })
- }
- GroupDivider(); ActionRow("MCP 访问凭据", "查看或复制 Token", Icons.Outlined.Key, { open("credentials") })
+ if (tunnel.accessUrl.isNotBlank()) item { Group {
+ ActionRow("访问地址", tunnel.accessUrl, Icons.Outlined.Link, { copy("访问地址", tunnel.accessUrl) })
+ if (tunnel.target == TunnelTarget.MCP && gateway.running && gateway.token != null) {
+ GroupDivider()
+ ActionRow("复制客户端配置", icon = Icons.Outlined.ContentCopy, onClick = {
+ val payload = buildJsonObject { putJsonObject("mcpServers") { putJsonObject(tunnel.name) {
+ put("url", tunnel.accessUrl)
+ putJsonObject("headers") { put("Authorization", "Bearer ${gateway.token}") }
+ } } }
+ copy("客户端配置", payload.toString())
+ })
}
} }
- item { SectionLabel("管理") }
- item { Group {
- ActionRow("服务器", "${tunnel.server}:${tunnel.serverPort}", Icons.Outlined.Dns)
- GroupDivider(); ActionRow("转发方式", "${tunnel.type} · ${tunnel.plugin.label}", Icons.Outlined.SettingsEthernet)
- GroupDivider(); ActionRow("本地目标", if (tunnel.target == TunnelTarget.MCP) "MBrain MCP" else "${tunnel.localHost}:${tunnel.localPort}", Icons.Outlined.PhoneAndroid)
- GroupDivider(); ActionRow("公网入口", if (tunnel.type == ProxyType.TCP) "端口 ${tunnel.remotePort}" else tunnel.domains.joinToString(), Icons.Outlined.Language)
- GroupDivider(); ActionRow("编辑配置", if (tunnel.enabled) "先关闭此隧道" else null, Icons.Outlined.Edit, if (!tunnel.enabled) ({ edit(tunnel.id) }) else null)
+ item { Group { ActionRow("编辑隧道", if (tunnel.enabled) "关闭后可编辑" else "$target · 公网访问端口 ${tunnel.remotePort}",
+ Icons.Outlined.Edit, if (!tunnel.enabled) ({ edit(tunnel.id) }) else null) } }
+ item { Box {
+ TextButton(onClick = { more = true }) { Text("更多"); Icon(Icons.Outlined.ExpandMore, null) }
+ DropdownMenu(expanded = more, onDismissRequest = { more = false }) {
+ DropdownMenuItem(text = { Text(if (diagnostics) "收起连接详情" else "连接详情") },
+ onClick = { diagnostics = !diagnostics; more = false })
+ if (tunnel.target == TunnelTarget.MCP) DropdownMenuItem(text = { Text("访问凭据") },
+ onClick = { more = false; open("credentials") })
+ if (tunnel.enabled && state.phase != TunnelPhase.WAITING) DropdownMenuItem(text = { Text("重新连接") },
+ onClick = { more = false; RemoteRuntime.retry(tunnel.id) })
+ DropdownMenuItem(text = { Text("删除隧道", color = MaterialTheme.colorScheme.error) },
+ onClick = { more = false; remove(tunnel.id) })
+ }
} }
- if (state.events.isNotEmpty()) {
- item { SectionLabel("最近运行记录") }
- item { Group { state.events.forEachIndexed { index, event ->
- if (index > 0) GroupDivider()
- ActionRow(event, icon = Icons.Outlined.History)
- } } }
+ if (diagnostics) {
+ item { Group {
+ ActionRow("服务器", "${tunnel.server}:${tunnel.serverPort}", Icons.Outlined.Dns)
+ GroupDivider(); ActionRow("服务器连接", if (state.serverConnected) "已连接" else "未连接", Icons.Outlined.Link)
+ GroupDivider(); ActionRow("本地服务", state.localHealth.label, Icons.Outlined.PhoneAndroid)
+ } }
+ if (state.events.isNotEmpty()) {
+ item { SectionLabel("最近运行记录") }
+ item { Group { state.events.forEachIndexed { index, event ->
+ if (index > 0) GroupDivider()
+ ActionRow(event, icon = Icons.Outlined.History)
+ } } }
+ }
}
- item { TextButton(onClick = { remove(tunnel.id) }, modifier = Modifier.fillMaxWidth()) { Text("删除隧道", color = MaterialTheme.colorScheme.error) } }
}
}
@@ -112,16 +119,12 @@ internal fun TunnelEditor(initial: TunnelConfig, existing: Boolean, config: Remo
var draft by rememberSaveable { mutableStateOf(json.encodeToString(TunnelConfig.serializer(), initial)) }
val value = remember(draft) { json.decodeFromString(TunnelConfig.serializer(), draft) }
fun update(next: TunnelConfig) { draft = json.encodeToString(TunnelConfig.serializer(), next) }
- var port by rememberSaveable { mutableStateOf(initial.serverPort.toString()) }
var localPort by rememberSaveable { mutableStateOf(initial.localPort.toString()) }
var remotePort by rememberSaveable { mutableStateOf(initial.remotePort.takeIf { it > 0 }?.toString().orEmpty()) }
- var domains by rememberSaveable { mutableStateOf(initial.domains.joinToString(", ")) }
- var reveal by rememberSaveable { mutableStateOf(false) }
var error by rememberSaveable { mutableStateOf(null) }
var discard by rememberSaveable { mutableStateOf(false) }
- var advanced by rememberSaveable { mutableStateOf(false) }
- val dirty = value != initial.copy(enabled = false) || port != initial.serverPort.toString() || localPort != initial.localPort.toString() ||
- remotePort != initial.remotePort.takeIf { it > 0 }?.toString().orEmpty() || domains != initial.domains.joinToString(", ")
+ val dirty = value != initial.copy(enabled = false) || localPort != initial.localPort.toString() ||
+ remotePort != initial.remotePort.takeIf { it > 0 }?.toString().orEmpty()
val close = { if (dirty) discard = true else dismiss() }
val list = rememberLazyListState()
val scope = rememberCoroutineScope()
@@ -133,53 +136,36 @@ internal fun TunnelEditor(initial: TunnelConfig, existing: Boolean, config: Remo
navigationIcon = { IconButton(onClick = close) { Icon(Icons.Outlined.Close, "关闭编辑") } }, colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.background), windowInsets = WindowInsets(0, 0, 0, 0)) },
bottomBar = { EditorSaveBar("保存隧道") {
try {
- val next = value.copy(name = value.name.trim(), server = value.server.trim(), serverPort = port.toIntOrNull() ?: 0,
- localHost = value.localHost.trim(), localPort = localPort.toIntOrNull() ?: 0, remotePort = remotePort.toIntOrNull() ?: 0,
- domains = domains.split(Regex("[,,\\s]+")).filter { it.isNotBlank() }, publicUrl = value.publicUrl.trim())
- next.validate(config.tunnels); save(next)
+ val next = value.asBasicTcp().referenceServer(config.server?.id.orEmpty()).copy(name = value.name.trim(),
+ localHost = if (value.target == TunnelTarget.MCP) "127.0.0.1" else value.localHost.trim(),
+ localPort = if (value.target == TunnelTarget.MCP) GatewayRuntime.PORT else localPort.toIntOrNull() ?: 0, remotePort = remotePort.toIntOrNull() ?: 0,
+ publicUrl = value.publicUrl.trim())
+ require(next.serverId.isNotEmpty()) { "请先配置服务器" }
+ config.copy(tunnels = config.tunnels.filterNot { it.id == next.id } + next).validate()
+ save(next.referenceServer(next.serverId))
} catch (e: Exception) { error = e.message ?: "保存失败"; scope.launch { list.animateScrollToItem(0) } }
} }) { padding ->
Box(Modifier.padding(padding).consumeWindowInsets(padding)) {
ScreenList(state = list) {
error?.let { item(key = "error") { Note(it, error = true) } }
+ if (!initial.supportsBasicTcp() || (initial.serverId.isNotEmpty() && initial.serverId != config.server?.id))
+ item(key = "legacy") { Note("保存后将使用当前服务器和基础 TCP 转发,请确认公网访问端口。") }
item(key = "name") { TunnelField("名称", value.name, { update(value.copy(name = it)); error = null }) }
item(key = "target-label") { SectionLabel("本地目标") }
item(key = "target") { ChoiceRow(TunnelTarget.entries, value.target, { if (it == TunnelTarget.MCP) "本应用 MCP" else "自定义服务" }) {
- update(value.copy(target = it, plugin = if (it == TunnelTarget.MCP && value.type == ProxyType.HTTPS) TunnelPlugin.HTTPS2HTTP else value.plugin))
+ update(value.copy(target = it))
} }
+ if (value.target == TunnelTarget.MCP) {
+ item(key = "mcp-endpoint") { Note("转发本机 MCP 网关:127.0.0.1:${GatewayRuntime.PORT}") }
+ }
if (value.target == TunnelTarget.CUSTOM) {
item(key = "local-host") { TunnelField("本地服务地址", value.localHost, { update(value.copy(localHost = it)) }, KeyboardType.Uri) }
item(key = "local-port") { TunnelField("本地服务端口", localPort, { localPort = it }, KeyboardType.Number) }
}
- item(key = "server-label") { SectionLabel("frps 服务器") }
- item(key = "server") { TunnelField("服务器地址", value.server, { update(value.copy(server = it)) }, KeyboardType.Uri) }
- item(key = "port") { TunnelField("服务器端口", port, { port = it }, KeyboardType.Number) }
- item(key = "token") { OutlinedTextField(value.token, { update(value.copy(token = it)) }, Modifier.fillMaxWidth(), label = { Text("服务器 Token(可选)") },
- singleLine = true, shape = MaterialTheme.shapes.medium, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
- visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),
- trailingIcon = { IconButton(onClick = { reveal = !reveal }) { Icon(if (reveal) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility, "显示或隐藏 Token") } }) }
- item(key = "proxy-label") { SectionLabel("公网入口") }
- item(key = "type") { ChoiceRow(ProxyType.entries, value.type, { it.name }) {
- update(value.copy(type = it, plugin = if (it == ProxyType.HTTPS && value.target == TunnelTarget.MCP) TunnelPlugin.HTTPS2HTTP else TunnelPlugin.NONE))
- } }
- if (value.type == ProxyType.TCP) item(key = "remote-port") { TunnelField("映射端口", remotePort, { remotePort = it }, KeyboardType.Number) }
- else item(key = "domains") { TunnelField("域名(多个用逗号分隔)", domains, { domains = it }, KeyboardType.Uri, "phone.example.com") }
- item(key = "plugin") { SelectionField("客户端插件", value.plugin.label,
- TunnelPlugin.entries.filter { value.type == ProxyType.TCP || it != TunnelPlugin.TLS2RAW }.map { it to it.label }) { update(value.copy(plugin = it)) } }
- if (value.plugin != TunnelPlugin.NONE) {
- item(key = "certificate") { CertificateChoice("服务证书与私钥", value.certificateId, config.certificates.filter { it.keyPem.isNotBlank() }) { update(value.copy(certificateId = it)) } }
- item(key = "certificate-help") { Note("请先在内网穿透 → 证书管理中导入证书与私钥。") }
- }
- if (value.plugin == TunnelPlugin.HTTPS2HTTP) item(key = "host-header") { TunnelField("重写 Host(可选)", value.hostHeaderRewrite, { update(value.copy(hostHeaderRewrite = it)) }) }
- item(key = "public-url") { TunnelField("公网访问地址(可选)", value.publicUrl, { update(value.copy(publicUrl = it)) }, KeyboardType.Uri,
- if (value.target == TunnelTarget.MCP) "https://phone.example.com/mcp" else "https://phone.example.com") }
- item(key = "advanced") { Group { ActionRow("frps 连接 TLS", "已启用加密 · 配置 CA 或双向认证", Icons.Outlined.Lock, { advanced = !advanced }) } }
- if (advanced) {
- item(key = "tls-help") { Note("此处配置 frpc 到 frps 的连接,与公网服务证书独立。未选择 CA 时沿用 frp 默认行为,不校验 frps 证书身份。") }
- item(key = "tls-ca") { CertificateChoice("信任的 CA(可选)", value.tlsCaId, config.certificates) { update(value.copy(tlsCaId = it)) } }
- item(key = "tls-name") { TunnelField("TLS 服务器名称(可选)", value.tlsServerName, { update(value.copy(tlsServerName = it)) }) }
- item(key = "tls-client") { CertificateChoice("客户端证书(可选)", value.tlsClientCertificateId, config.certificates.filter { it.keyPem.isNotBlank() }) { update(value.copy(tlsClientCertificateId = it)) } }
- }
+ item(key = "remote-port") { TunnelField("公网访问端口", remotePort, { remotePort = it }, KeyboardType.Number) }
+ item(key = "public-url") { TunnelField("自定义公网地址(可选)", value.publicUrl, { update(value.copy(publicUrl = it)) }, KeyboardType.Uri,
+ if (value.target == TunnelTarget.MCP) value.copy(server = config.server?.host.orEmpty(), remotePort = remotePort.toIntOrNull() ?: 0, publicUrl = "").accessUrl else "http://phone.example.com:18080") }
+
}
}
}
@@ -196,23 +182,6 @@ private fun ChoiceRow(values: List, selected: T, label: (T) -> String, ch
} }
}
-@Composable
-internal fun CertificateChoice(label: String, id: String, certificates: List, change: (String) -> Unit) {
- SelectionField(label, certificates.find { it.id == id }?.name ?: "未选择", listOf("" to "不使用") + certificates.map { it.id to it.name }, change)
-}
-
-@Composable
-private fun SelectionField(label: String, value: String, choices: List>, change: (T) -> Unit) {
- var expanded by remember { mutableStateOf(false) }
- Box {
- Group { ActionRow(label, value, Icons.Outlined.Tune, { expanded = true },
- trailing = { Icon(Icons.Outlined.ExpandMore, null, Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant) }) }
- DropdownMenu(expanded, { expanded = false }) { choices.forEach { (key, name) ->
- DropdownMenuItem(text = { Text(name) }, onClick = { change(key); expanded = false })
- } }
- }
-}
-
@Composable
internal fun TunnelField(label: String, value: String, change: (String) -> Unit, keyboard: KeyboardType = KeyboardType.Text, placeholder: String = "") {
OutlinedTextField(value, change, Modifier.fillMaxWidth(), label = { Text(label) }, singleLine = true,
diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/ServerScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/ServerScreens.kt
new file mode 100644
index 0000000..6349306
--- /dev/null
+++ b/app/src/main/kotlin/com/powercess/mbrain/ui/ServerScreens.kt
@@ -0,0 +1,69 @@
+package com.powercess.mbrain.ui
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.*
+import androidx.compose.material3.*
+import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.input.*
+import com.powercess.mbrain.remote.*
+import kotlinx.coroutines.launch
+import kotlinx.serialization.json.Json
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+internal fun ServerEditor(initial: TunnelServer, existing: Boolean, config: RemoteConfig, dismiss: () -> Unit, remove: () -> Unit, save: (TunnelServer) -> Unit) {
+ val json = remember { Json { encodeDefaults = true } }
+ var draft by rememberSaveable { mutableStateOf(json.encodeToString(TunnelServer.serializer(), initial)) }
+ val value = remember(draft) { json.decodeFromString(TunnelServer.serializer(), draft) }
+ fun update(next: TunnelServer) { draft = json.encodeToString(TunnelServer.serializer(), next) }
+ var port by rememberSaveable { mutableStateOf(initial.port.toString()) }
+ var reveal by remember { mutableStateOf(false) }
+ var error by rememberSaveable { mutableStateOf(null) }
+ var discard by rememberSaveable { mutableStateOf(false) }
+ val close = { if (value != initial || port != initial.port.toString()) discard = true else dismiss() }
+ val list = rememberLazyListState()
+ val scope = rememberCoroutineScope()
+ Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
+ BackHandler { close() }
+ Scaffold(modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding(), contentWindowInsets = WindowInsets(0, 0, 0, 0),
+ containerColor = MaterialTheme.colorScheme.background,
+ topBar = { TopAppBar(title = { Text("配置服务器") },
+ navigationIcon = { IconButton(onClick = close) { Icon(Icons.Outlined.Close, "关闭编辑") } }, colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.background), windowInsets = WindowInsets(0, 0, 0, 0)) },
+ bottomBar = { EditorSaveBar("保存服务器") {
+ try {
+ val next = value.copy(name = value.name.trim(), host = value.host.trim(), port = port.toIntOrNull() ?: 0,
+ tlsServerName = "", tlsCaId = "", tlsClientCertificateId = "")
+ config.saveServer(next); save(next)
+ } catch (e: Exception) { error = e.message ?: "保存失败"; scope.launch { list.animateScrollToItem(0) } }
+ } }) { padding ->
+ Box(Modifier.padding(padding).consumeWindowInsets(padding)) {
+ ScreenList(state = list) {
+ error?.let { item { Note(it, error = true) } }
+ item { TunnelField("服务器名称", value.name, { update(value.copy(name = it)) }) }
+ item { TunnelField("服务器地址", value.host, { update(value.copy(host = it)) }, KeyboardType.Uri, "frp.example.com") }
+ item { TunnelField("服务器端口", port, { port = it }, KeyboardType.Number) }
+ item { OutlinedTextField(value.token, { update(value.copy(token = it)) }, Modifier.fillMaxWidth(), label = { Text("服务器 Token(可选)") },
+ singleLine = true, shape = MaterialTheme.shapes.medium, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
+ visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),
+ trailingIcon = { IconButton(onClick = { reveal = !reveal }) { Icon(if (reveal) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility, "显示或隐藏 Token") } }) }
+ if (existing) item { TextButton(onClick = {
+ runCatching { config.removeServer(initial.id); remove() }.onFailure {
+ error = it.message ?: "无法删除服务器"; scope.launch { list.animateScrollToItem(0) }
+ }
+ }, modifier = Modifier.fillMaxWidth()) {
+ Text("删除服务器", color = MaterialTheme.colorScheme.error)
+ } }
+
+ }
+ }
+ }
+ if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text("放弃未保存的修改?") },
+ confirmButton = { TextButton(onClick = dismiss) { Text("放弃修改") } }, dismissButton = { TextButton(onClick = { discard = false }) { Text("继续编辑") } })
+ }
+}
diff --git a/app/src/test/kotlin/com/powercess/mbrain/remote/CertificatesTest.kt b/app/src/test/kotlin/com/powercess/mbrain/remote/CertificatesTest.kt
deleted file mode 100644
index f3a21a0..0000000
--- a/app/src/test/kotlin/com/powercess/mbrain/remote/CertificatesTest.kt
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.powercess.mbrain.remote
-
-import org.junit.Assert.*
-import org.junit.Test
-import java.io.File
-import java.nio.file.Files
-import java.security.KeyStore
-import java.util.Base64
-import java.util.Date
-
-internal fun testCertificate(algorithm: String = "RSA"): TunnelCertificate {
- val directory = Files.createTempDirectory("certificate-test").toFile()
- try {
- val keytool = File(System.getProperty("java.home"), "bin/" + if (System.getProperty("os.name").startsWith("Windows")) "keytool.exe" else "keytool")
- val file = File(directory, "test.p12")
- val password = "unit-test-only".toCharArray()
- val process = ProcessBuilder(keytool.absolutePath, "-genkeypair", "-alias", "test", "-storetype", "PKCS12",
- "-keyalg", algorithm, "-dname", "CN=localhost", "-validity", "30", "-storepass", String(password),
- "-keystore", file.absolutePath).redirectErrorStream(true).start()
- val output = process.inputStream.bufferedReader().readText()
- check(process.waitFor() == 0) { output }
- val store = KeyStore.getInstance("PKCS12").apply { file.inputStream().use { load(it, password) } }
- fun pem(label: String, bytes: ByteArray) = "-----BEGIN $label-----\n" + Base64.getMimeEncoder(64, "\n".toByteArray()).encodeToString(bytes) + "\n-----END $label-----"
- return TunnelCertificate(name = "test", pem = pem("CERTIFICATE", store.getCertificate("test").encoded),
- keyPem = pem("PRIVATE KEY", store.getKey("test", password).encoded))
- } finally { directory.deleteRecursively() }
-}
-
-class CertificatesTest {
- @Test fun `RSA and EC certificate pairs are validated and CA can omit a key`() {
- listOf("RSA", "EC").forEach { algorithm ->
- val certificate = testCertificate(algorithm)
- certificate.validate()
- certificate.copy(keyPem = "").validate()
- assertEquals("已过期", certificate.expiryMessage(Date(certificate.chain().first().notAfter.time + 1)))
- assertEquals("尚未生效", certificate.expiryMessage(Date(0)))
- }
- }
-
- @Test fun `mismatched key and malformed PEM are rejected`() {
- val first = testCertificate()
- val second = testCertificate()
- assertThrows(IllegalArgumentException::class.java) { first.copy(keyPem = second.keyPem).validate() }
- assertThrows(IllegalArgumentException::class.java) { first.copy(pem = "not a certificate").validate() }
- assertThrows(IllegalArgumentException::class.java) { first.copy(keyPem = "-----BEGIN ENCRYPTED PRIVATE KEY-----").validate() }
- }
-}
diff --git a/app/src/test/kotlin/com/powercess/mbrain/remote/FrpcControllerTest.kt b/app/src/test/kotlin/com/powercess/mbrain/remote/FrpcControllerTest.kt
index b3b2d10..0c6a2d7 100644
--- a/app/src/test/kotlin/com/powercess/mbrain/remote/FrpcControllerTest.kt
+++ b/app/src/test/kotlin/com/powercess/mbrain/remote/FrpcControllerTest.kt
@@ -65,11 +65,9 @@ class FrpcControllerTest {
} finally { controller.close(); directory.deleteRecursively() }
}
- @Test fun `custom service survives MCP shutdown and certificate rotation affects only its users`() {
+ @Test fun `custom service survives MCP shutdown and endpoint edits restart only its process`() {
val directory = Files.createTempDirectory("frpc-independent-test").toFile()
val binary = File(System.getProperty("java.home"), "bin/" + if (System.getProperty("os.name").startsWith("Windows")) "java.exe" else "java")
- val certificate = testCertificate()
- val replacement = testCertificate().copy(id = certificate.id)
val processes = CopyOnWriteArrayList()
val configs = CopyOnWriteArrayList()
val controller = FrpcController(binary, directory, { _, _ -> }, { _, file ->
@@ -77,25 +75,55 @@ class FrpcControllerTest {
})
val mcp = TunnelConfig(name = "mcp", server = "frp.example.com", remotePort = 18081, enabled = true)
val custom = TunnelConfig(name = "custom", server = "frp.example.com", remotePort = 18082,
- target = TunnelTarget.CUSTOM, localPort = 8787, plugin = TunnelPlugin.TLS2RAW, certificateId = certificate.id, enabled = true)
+ target = TunnelTarget.CUSTOM, localPort = 8787, enabled = true)
try {
- controller.reconcile(listOf(custom, mcp), null, listOf(certificate))
+ controller.reconcile(listOf(custom, mcp), null)
await { processes.size == 1 }
val customProcess = processes.single()
- assertTrue(configs.single().contains("tls2raw"))
- controller.reconcile(listOf(custom, mcp), 8765, listOf(certificate))
+ assertFalse(configs.single().contains("plugin"))
+ controller.reconcile(listOf(custom, mcp), 8765)
await { processes.size == 2 }
val mcpProcess = processes.last()
- controller.reconcile(listOf(custom, mcp), 8765, listOf(replacement))
+ val replacement = custom.copy(localPort = 8788)
+ controller.reconcile(listOf(replacement, mcp), 8765)
await { processes.size == 3 }
assertFalse(customProcess.isAlive)
assertTrue(mcpProcess.isAlive)
val replacementProcess = processes.last()
- controller.reconcile(listOf(custom, mcp), null, listOf(replacement))
+ controller.reconcile(listOf(replacement, mcp), null)
await { !mcpProcess.isAlive }
assertTrue(replacementProcess.isAlive)
controller.close()
await { processes.none { it.isAlive } && directory.listFiles().orEmpty().isEmpty() }
} finally { controller.close(); directory.deleteRecursively() }
}
+ @Test fun `repeated retries retain one error until connection recovers`() {
+ val directory = Files.createTempDirectory("frpc-retry-test").toFile()
+ val binary = File(System.getProperty("java.home"), "bin/" + if (System.getProperty("os.name").startsWith("Windows")) "java.exe" else "java")
+ val processes = CopyOnWriteArrayList()
+ val states = ConcurrentHashMap()
+ val controller = FrpcController(binary, directory, { id, state -> states[id] = state }, { _, _ ->
+ FakeProcess().also { processes.add(it) }
+ })
+ val tunnel = TunnelConfig(name = "retry", server = "frp.example.com", remotePort = 18080, enabled = true)
+ try {
+ controller.reconcile(listOf(tunnel), 8765)
+ await { processes.size == 1 }
+ val process = processes.single()
+ repeat(5) {
+ process.line("try to connect to server")
+ process.line("connect to server error: EOF")
+ }
+ process.line("try to connect to server")
+ process.line("login to server success")
+ await { states[tunnel.id]?.serverConnected == true }
+ val failed = states.getValue(tunnel.id)
+ assertEquals("无法连接服务器,正在重试", failed.error)
+ assertEquals(1, failed.events.count { it == failed.error })
+ process.line("start proxy success")
+ await { states[tunnel.id]?.phase == TunnelPhase.CONNECTED }
+ assertNull(states.getValue(tunnel.id).error)
+ } finally { controller.close(); directory.deleteRecursively() }
+ }
+
}
diff --git a/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelConfigTest.kt b/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelConfigTest.kt
index 47486a8..c1c9d7b 100644
--- a/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelConfigTest.kt
+++ b/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelConfigTest.kt
@@ -6,87 +6,67 @@ import org.junit.Assert.*
import org.junit.Test
class TunnelConfigTest {
- @Test fun `legacy tunnels retain configuration without restarting automatically`() {
- val legacy = """[{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","name":"legacy","server":"frp.example.com","remotePort":18080,"enabled":true}]"""
- val tunnels = Json { ignoreUnknownKeys = true }.decodeFromString>(legacy)
- RemoteConfig(tunnels = tunnels).validate()
- assertEquals("legacy", tunnels.single().name)
- assertEquals(TunnelTarget.MCP, tunnels.single().target)
- assertEquals(18080, tunnels.single().remotePort)
- assertFalse(tunnels.single().enabled)
- }
-
private val base = TunnelConfig(name = "phone", server = "frp.example.com", remotePort = 18080)
- private val certificateId = "a".repeat(32)
- private val paths = mapOf(certificateId to CertificatePaths("/private/service.crt", "/private/service.key"))
- private fun proxy(config: TunnelConfig) = Json.parseToJsonElement(config.frpcConfig("127.0.0.1" to 8787, paths))
- .jsonObject["proxies"]!!.jsonArray.single().jsonObject
- @Test fun `tcp forwards arbitrary local port and does not require running MCP`() {
+ @Test fun `MCP forwards gateway port and advertises public port independently of server port`() {
+ val tunnel = base.copy(serverPort = 5080, localHost = "old.example.com", localPort = 9999)
+ val endpoint = tunnel.endpoint(8765)!!
+ assertEquals("127.0.0.1" to 8765, endpoint)
+ val config = Json.parseToJsonElement(tunnel.frpcConfig(endpoint)).jsonObject
+ assertEquals(5080, config["serverPort"]!!.jsonPrimitive.int)
+ val proxy = config["proxies"]!!.jsonArray.single().jsonObject
+ assertEquals(8765, proxy["localPort"]!!.jsonPrimitive.int)
+ assertEquals(18080, proxy["remotePort"]!!.jsonPrimitive.int)
+ assertEquals("http://frp.example.com:18080/mcp", tunnel.accessUrl)
+ assertEquals("http://frp.example.com:19000/mcp", tunnel.copy(remotePort = 19000).accessUrl)
+ assertEquals("http://[::1]:18080/mcp", tunnel.copy(server = "::1").accessUrl)
+ assertEquals("http://external.example.com:80/mcp", tunnel.copy(publicUrl = "http://external.example.com:80/mcp").accessUrl)
+ assertNull(tunnel.endpoint(null))
+ }
+
+ @Test fun `TCP forwards the local endpoint with transport TLS and without HTTPS plugins`() {
val tunnel = base.copy(target = TunnelTarget.CUSTOM, localPort = 8080)
assertEquals("127.0.0.1" to 8080, tunnel.endpoint(null))
assertNull(base.endpoint(null))
- assertEquals("127.0.0.1" to 41234, base.endpoint(41234))
- assertEquals(8787, proxy(tunnel)["localPort"]!!.jsonPrimitive.int)
- assertFalse(proxy(tunnel).containsKey("plugin"))
- }
-
- @Test fun `https routes domains with passthrough for custom targets`() {
- val tunnel = base.copy(type = ProxyType.HTTPS, target = TunnelTarget.CUSTOM, domains = listOf("phone.example.com"))
- val generated = proxy(tunnel)
- assertEquals("https", generated["type"]!!.jsonPrimitive.content)
- assertFalse(generated.containsKey("remotePort"))
- assertEquals("phone.example.com", generated["customDomains"]!!.jsonArray.single().jsonPrimitive.content)
+ val json = Json.parseToJsonElement(tunnel.frpcConfig("127.0.0.1" to 8787)).jsonObject
+ assertTrue(json["transport"]!!.jsonObject["tls"]!!.jsonObject["enable"]!!.jsonPrimitive.boolean)
+ val proxy = json["proxies"]!!.jsonArray.single().jsonObject
+ assertEquals("tcp", proxy["type"]!!.jsonPrimitive.content)
+ assertEquals(8787, proxy["localPort"]!!.jsonPrimitive.int)
+ assertEquals(18080, proxy["remotePort"]!!.jsonPrimitive.int)
+ assertFalse(proxy.containsKey("plugin"))
+ assertFalse(proxy.containsKey("customDomains"))
}
- @Test fun `both TLS plugins replace the raw local endpoint with plugin options`() {
- for (plugin in listOf(TunnelPlugin.HTTPS2HTTP, TunnelPlugin.TLS2RAW)) {
- val generated = proxy(base.copy(plugin = plugin, certificateId = certificateId))
- assertFalse(generated.containsKey("localIP"))
- assertFalse(generated.containsKey("localPort"))
- val options = generated["plugin"]!!.jsonObject
- assertEquals(plugin.wireName, options["type"]!!.jsonPrimitive.content)
- assertEquals("127.0.0.1:8787", options["localAddr"]!!.jsonPrimitive.content)
- assertEquals(paths.getValue(certificateId).key, options["keyPath"]!!.jsonPrimitive.content)
+ @Test fun `legacy HTTPS plugins and TLS never silently become plain TCP`() {
+ val id = "c".repeat(32)
+ listOf(base.copy(type = ProxyType.HTTPS, target = TunnelTarget.CUSTOM, domains = listOf("phone.example.com")),
+ base.copy(plugin = TunnelPlugin.HTTPS2HTTP, certificateId = id),
+ base.copy(plugin = TunnelPlugin.TLS2RAW, certificateId = id), base.copy(tlsCaId = id),
+ base.copy(tlsClientCertificateId = id), base.copy(tlsServerName = "frps.example.com"),
+ base.copy(publicUrl = "https://phone.example.com/mcp")).forEach { legacy ->
+ assertThrows(IllegalArgumentException::class.java) { legacy.frpcConfig("127.0.0.1" to 8765) }
+ legacy.asBasicTcp().copy(remotePort = 18080).frpcConfig("127.0.0.1" to 8765)
}
}
- @Test fun `frps client TLS is independent from service certificate`() {
- val tunnel = base.copy(tlsCaId = certificateId, tlsClientCertificateId = certificateId, tlsServerName = "frps.example.com")
- val generated = Json.parseToJsonElement(tunnel.frpcConfig("::1" to 8080, paths)).jsonObject
- val tls = generated["transport"]!!.jsonObject["tls"]!!.jsonObject
- assertEquals("frps.example.com", tls["serverName"]!!.jsonPrimitive.content)
- assertEquals("/private/service.crt", tls["trustedCaFile"]!!.jsonPrimitive.content)
- assertEquals("/private/service.key", tls["keyFile"]!!.jsonPrimitive.content)
- assertFalse(generated["proxies"]!!.jsonArray.single().jsonObject.containsKey("plugin"))
- }
-
- @Test fun `invalid or conflicting configurations fail before launching`() {
- val bad = listOf(base.copy(server = "https://frp.example.com"), base.copy(serverPort = 0),
- base.copy(localPort = 65536), base.copy(token = "{{ .Envs.SECRET }}"),
- base.copy(type = ProxyType.HTTPS, domains = listOf("phone.example.com")),
- base.copy(plugin = TunnelPlugin.TLS2RAW), base.copy(publicUrl = "https://phone.example.com/wrong"),
- base.copy(type = ProxyType.HTTPS, target = TunnelTarget.CUSTOM, domains = listOf("phone.example.com:443")))
- bad.forEach { assertThrows(IllegalArgumentException::class.java) { it.validate() } }
+ @Test fun `invalid and conflicting TCP configurations fail before launching`() {
+ listOf(base.copy(server = "https://frp.example.com"), base.copy(serverPort = 0), base.copy(localPort = 65536),
+ base.copy(remotePort = 0), base.copy(token = "{{ .Envs.SECRET }}"),
+ base.copy(publicUrl = "http://phone.example.com/wrong")).forEach { bad ->
+ assertThrows(IllegalArgumentException::class.java) { bad.frpcConfig("127.0.0.1" to 8765) }
+ }
assertThrows(IllegalArgumentException::class.java) { base.validate(listOf(base.copy(id = "b".repeat(32)))) }
- val https = base.copy(type = ProxyType.HTTPS, target = TunnelTarget.CUSTOM, domains = listOf("phone.example.com"))
- assertThrows(IllegalArgumentException::class.java) { https.validate(listOf(https.copy(id = "b".repeat(32), domains = listOf("PHONE.example.com")))) }
}
- @Test fun `saved configuration never silently re-enables tunnels`() {
- val json = Json { encodeDefaults = true }
+ @Test fun `legacy and saved configurations never restart automatically`() {
+ val json = Json { ignoreUnknownKeys = true }
+ val legacy = """[{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","name":"legacy","server":"frp.example.com","remotePort":18080,"enabled":true}]"""
+ assertFalse(json.decodeFromString>(legacy).single().enabled)
val text = json.encodeToString(RemoteConfig(tunnels = listOf(base.copy(enabled = true))))
assertFalse(json.decodeFromString(text).tunnels.single().enabled)
}
- @Test fun `certificate references and private keys are required`() {
- val tunnel = base.copy(plugin = TunnelPlugin.HTTPS2HTTP, certificateId = certificateId)
- assertThrows(IllegalArgumentException::class.java) { RemoteConfig(listOf(tunnel)).validate() }
- assertThrows(IllegalArgumentException::class.java) {
- RemoteConfig(listOf(tunnel), listOf(TunnelCertificate(id = certificateId, name = "CA", pem = "placeholder"))).validate()
- }
- }
-
@Test fun `untrusted log messages cannot leak into visible errors`() {
assertNull(classifyFrpcLine("arbitrary secret value"))
assertEquals("服务器认证失败", classifyFrpcLine("token [private] doesn't match")!!.second)
diff --git a/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelServerTest.kt b/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelServerTest.kt
new file mode 100644
index 0000000..41a7bdb
--- /dev/null
+++ b/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelServerTest.kt
@@ -0,0 +1,107 @@
+package com.powercess.mbrain.remote
+
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.Assert.*
+import org.junit.Test
+
+class TunnelServerTest {
+ private val first = TunnelConfig(name = "one", server = "frp.example.com", remotePort = 18080, token = "test-token")
+ private val second = first.copy(id = "b".repeat(32), name = "two", remotePort = 18081)
+
+ @Test fun `migration shares identical connections and preserves frpc output`() {
+ val original = RemoteConfig(tunnels = listOf(first, second))
+ val migrated = original.migrateServers()
+ migrated.validate()
+ assertEquals(1, migrated.servers.size)
+ assertEquals(migrated.tunnels[0].serverId, migrated.tunnels[1].serverId)
+ assertTrue(migrated.tunnels.all { it.token.isEmpty() && it.server.isEmpty() })
+ original.tunnels.zip(migrated.tunnels).forEach { (before, after) ->
+ assertEquals(before.frpcConfig("127.0.0.1" to 8765), migrated.resolve(after).frpcConfig("127.0.0.1" to 8765))
+ }
+ assertEquals(migrated, migrated.migrateServers())
+ }
+
+ @Test fun `migration does not merge different credentials ports or TLS settings`() {
+ listOf(second.copy(token = "other"), second.copy(serverPort = 7001), second.copy(tlsServerName = "tls.example.com"),
+ second.copy(tlsCaId = "c".repeat(32)), second.copy(tlsClientCertificateId = "d".repeat(32))).forEach { different ->
+ val migrated = RemoteConfig(tunnels = listOf(first, different)).migrateServers()
+ assertEquals(2, migrated.servers.size)
+ val restored = migrated.resolve(migrated.tunnels[1])
+ assertEquals(different.server, restored.server)
+ assertEquals(different.token, restored.token)
+ assertEquals(different.tlsCaId, restored.tlsCaId)
+ assertEquals(different.tlsClientCertificateId, restored.tlsClientCertificateId)
+
+ }
+ }
+
+ @Test fun `legacy migration is stable and accepts long valid hostnames`() {
+ val legacy = """[{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","name":"legacy","server":"frp.example.com","remotePort":18080,"enabled":true}]"""
+ val json = Json { ignoreUnknownKeys = true }
+ val config = RemoteConfig(tunnels = json.decodeFromString>(legacy))
+ assertEquals(config.migrateServers(), config.migrateServers())
+ assertFalse(config.migrateServers().tunnels.single().enabled)
+ val longHost = "a".repeat(50) + "." + "b".repeat(50) + ".example.com"
+ RemoteConfig(tunnels = listOf(first.copy(server = longHost))).migrateServers().validate()
+ }
+
+ @Test fun `single server rejects extra servers and retired TLS settings`() {
+ val server = TunnelServer(name = "server", host = "frp.example.com")
+ val config = RemoteConfig().saveServer(server)
+ assertThrows(IllegalArgumentException::class.java) { config.saveServer(server.copy(id = "c".repeat(32))) }
+ listOf(server.copy(host = "https://frp.example.com"), server.copy(port = 0), server.copy(token = "{{ .Envs.SECRET }}"),
+ server.copy(tlsCaId = "c".repeat(32))).forEach { bad ->
+ assertThrows(IllegalArgumentException::class.java) { config.saveServer(bad) }
+ }
+ }
+
+ @Test fun `server edits affect every reference and serialized reload keeps tunnels off`() {
+ val migrated = RemoteConfig(tunnels = listOf(first, second)).migrateServers()
+ val updated = migrated.saveServer(migrated.servers.single().copy(host = "new.example.com", token = "new-token"))
+ updated.tunnels.forEach { tunnel ->
+ val json = Json.parseToJsonElement(updated.resolve(tunnel).frpcConfig("127.0.0.1" to 8765)).jsonObject
+ assertEquals("new.example.com", json["serverAddr"]!!.jsonPrimitive.content)
+ assertEquals("new-token", json["auth"]!!.jsonObject["token"]!!.jsonPrimitive.content)
+ }
+ val running = updated.copy(tunnels = updated.tunnels.map { it.copy(enabled = true) })
+ val restored = Json.decodeFromString(Json.encodeToString(running))
+ restored.validate()
+ assertEquals(updated, restored)
+ }
+
+ @Test fun `referenced and active servers are protected`() {
+ val config = RemoteConfig(tunnels = listOf(first)).migrateServers()
+ val server = config.servers.single()
+ assertThrows(IllegalArgumentException::class.java) { config.removeServer(server.id) }
+ val running = config.copy(tunnels = config.tunnels.map { it.copy(enabled = true) })
+ assertThrows(IllegalArgumentException::class.java) { running.saveServer(server.copy(host = "new.example.com")) }
+ assertTrue(config.copy(tunnels = emptyList()).removeServer(server.id).servers.isEmpty())
+ }
+
+ @Test fun `missing references retired TLS and conflicting mappings fail validation`() {
+ val config = RemoteConfig(tunnels = listOf(first, second)).migrateServers()
+ assertThrows(IllegalArgumentException::class.java) { config.copy(servers = emptyList()).validate() }
+ assertThrows(IllegalArgumentException::class.java) { config.saveServer(config.servers.single().copy(tlsCaId = "c".repeat(32))) }
+ assertThrows(IllegalArgumentException::class.java) {
+ config.copy(tunnels = config.tunnels.map { it.copy(remotePort = 18080) }).validate()
+ }
+ val separate = RemoteConfig(tunnels = listOf(first, second.copy(server = "other.example.com", remotePort = 18080))).migrateServers()
+ assertThrows(IllegalArgumentException::class.java) { separate.saveServer(separate.servers[1].copy(host = first.server)) }
+ }
+
+ @Test fun `editing primary server preserves inactive legacy servers and certificate payloads`() {
+ val certificate = TunnelCertificate(name = "legacy", pem = "legacy-payload", keyPem = "legacy-key")
+ val migrated = RemoteConfig(tunnels = listOf(first, second.copy(server = "other.example.com")),
+ certificates = listOf(certificate)).migrateServers()
+ val primary = migrated.server!!
+ val edited = migrated.saveServer(primary.copy(name = "renamed"))
+ assertEquals(primary.id, edited.server!!.id)
+ assertEquals(migrated.servers[1], edited.servers[1])
+ val restored = Json.decodeFromString(Json.encodeToString(edited))
+ assertEquals(listOf(certificate), restored.certificates)
+ assertEquals(migrated.tunnels, restored.tunnels)
+ }
+}
diff --git a/docs/releases/0.2.0.md b/docs/releases/0.2.0.md
new file mode 100644
index 0000000..7601a08
--- /dev/null
+++ b/docs/releases/0.2.0.md
@@ -0,0 +1,20 @@
+# MBrain 0.2.0
+
+## 内网穿透
+
+- 新增独立服务器配置入口,所有隧道共用一台 frps 服务器。
+- 简化服务器和隧道配置,仅提供基础 TCP 转发,移除 HTTPS 插件和证书管理界面。
+- MCP 隧道转发本机网关 `127.0.0.1:8765`,公网访问端口独立配置;自动生成 MCP 访问地址并支持复制客户端配置。
+- 精简隧道详情页,将连接诊断和运行记录收纳到“更多”。
+- 修复要求 TLS 的 frps 登录失败,保留底层连接加密,并合并重复重连错误。
+
+## 升级说明
+
+- 旧服务器配置会自动整理;旧多服务器数据保留,当前仅支持使用第一台服务器。
+- 旧 HTTPS、插件和证书配置需重新编辑为 TCP 后才能启动。
+- 应用重启或升级后,需手动启动网关和隧道。
+- frps Token 用于服务器登录,MCP Token 用于公网 MCP 请求鉴权,两者独立。
+
+## 验证
+
+- 已在测试设备验证公网 MCP 鉴权、初始化、工具发现和设备、电量、网络、存储四项只读工具调用。
diff --git a/docs/remote-access.md b/docs/remote-access.md
index 4432d6e..5d49e71 100644
--- a/docs/remote-access.md
+++ b/docs/remote-access.md
@@ -1,76 +1,47 @@
# 内网穿透
-在 **设置 → 内网穿透** 添加隧道。MBrain 内置 frpc,不需要 Root 或 Shizuku;用户需要已有可访问的 frps。每条隧道配置自己的服务器、认证信息和目标地址,可以连接同一台或不同的服务器。
+在 **设置 → 内网穿透 → 配置服务器** 填写已有 frps 的名称、地址、端口和 Token。当前只支持配置一台服务器;点击服务器入口直接编辑,所有隧道共用此配置。MBrain 内置 frpc,不需要 Root 或 Shizuku。
-## 支持的转发方式
+## 配置隧道
-| 代理类型 | 客户端插件 | 用途 |
-| --- | --- | --- |
-| TCP | 不使用 | 公网端口转发到指定本地 TCP 端口 |
-| HTTPS | 不使用 | 按域名透传 TLS,本地目标已经提供 HTTPS |
-| HTTPS 或 TCP | HTTPS → HTTP(`https2http`) | frpc 使用所选证书终止 TLS,再访问本地 HTTP 服务 |
-| TCP | TLS → TCP(`tls2raw`) | frpc 终止 TLS,再转发解密后的字节流 |
+返回内网穿透页,点击“添加隧道”,填写名称、本地目标和公网访问端口:
-“本应用 MCP”自动使用正在运行的 MBrain 网关端口。HTTPS 代理应选择 HTTPS → HTTP 插件,因为网关自身提供 HTTP。“自定义服务”可以填写手机上其他服务的地址和端口,不要求服务使用 MCP,也不要求它先加入 MCP 聚合列表。
+- **本应用 MCP**:转发本机 MCP 网关 `127.0.0.1:8765`,运行时跟随网关实际监听端口,无需填写本地端口。
+- **自定义服务**:填写本地地址和端口,默认地址为回环地址。
+- **公网访问端口**:frps 对外提供此隧道的 TCP 端口,与服务器连接端口、本机网关端口分别配置。
+- **自定义公网地址**:可选。留空时,MCP 自动使用 `http://服务器地址:公网访问端口/mcp`;存在额外端口映射或域名时可填写完整 HTTP 地址覆盖,用于显示和复制客户端配置。
-HTTPS 域名需要解析到 frps,且 frps 已配置 `vhostHTTPSPort`。TCP 需要服务器允许所选映射端口。填写“公网访问地址”只保存供复制的连接信息,不会自动配置 DNS、防火墙或服务器;MBrain MCP 的地址路径应为 `/mcp`。
+当前仅提供基础 TCP 转发,不提供 HTTPS 路由、客户端插件或证书管理。frpc 到 frps 的底层连接默认使用 TLS,与隧道转发类型独立,无需额外界面设置;兼容要求 TLS 的 frps。服务器需允许对应映射端口。
-## 独立运行
+## 运行与编辑
-- 打开单条隧道开关即启动独立的前台隧道服务,可从通知停止全部隧道。
-- 自定义服务隧道不依赖 MCP 网关;停止 MCP 后仍继续运行。
-- 指向 MBrain 的隧道在网关未运行时显示“等待 MCP 网关”,网关启动后连接,停止后关闭对应 frpc 进程。
-- 每条隧道使用独立进程,启停、故障和重试不会重启其他隧道。编辑前先关闭对应隧道。
-- frpc 自动重连网络;进程退出后以 1–30 秒退避重启。应用进程死亡或设备重启后不自动启用任何隧道。
-- frps 连接、隧道注册、本地端口可连接性分别显示。本地检测每 15 秒尝试一次 TCP 连接,不发送应用请求;“隧道已注册”不代表公网 DNS、证书或应用协议已验证。
+- 每条隧道独立启停。MCP 隧道在网关关闭时等待,网关启动后连接;自定义服务隧道独立运行。
+- 修改服务器前,先关闭关联隧道。删除服务器前,先删除关联隧道。
+- frpc 网络重连与进程退避重启保持启用;应用进程死亡或设备重启后,隧道保持关闭。
+- 服务器连接、隧道注册和本地端口状态分别显示。“隧道已注册”不代表公网应用访问已验证。
+- MCP 继续使用网关 Bearer Token;服务器 Token 与 MCP Token 是不同凭据。
-MCP 继续使用已有 Bearer 鉴权。frps Token 与 MCP Token 是独立凭据;MCP Token 持久保存,重启网关不改变;在“地址与凭据”中重置后,旧 Token 失效,需要更新客户端配置。
+旧配置中的服务器会自动整理。若旧版本曾配置多台服务器,当前仅使用第一台,其余配置保留在加密存储中,对应隧道需重新编辑保存以使用当前服务器。旧 HTTPS、TLS 和插件配置不会自动改为明文转发;需编辑服务器或隧道,确认基础 TCP 参数后保存。
-## 证书配置
-
-在 **内网穿透 → 证书管理** 导入 PEM X.509 证书链和对应私钥。支持未加密的 RSA / EC PKCS#8 私钥,以及 RSA PKCS#1 私钥;证书链的第一张应是与私钥对应的叶证书。CA 可以不附带私钥。
-
-保存时验证证书格式与私钥匹配关系,列表显示到期日期、过期或即将到期状态。点击已保存证书可以替换;替换只重连引用它的隧道。仍被隧道引用的证书不能删除。当前不自动申请或续期证书。
-
-两套 TLS 配置用途不同:
-
-- **服务证书与私钥**用于 `https2http` / `tls2raw`,保护公网客户端访问服务的连接。HTTPS 透传时证书由本地服务管理。
-- **frps 连接 TLS**保护 frpc 与 frps 的连接,始终启用加密。可指定信任 CA、TLS 服务器名称及客户端证书,实现身份校验和双向 TLS。未指定 CA 时沿用 frp 默认行为,不验证 frps 证书身份。
-
-配置、Token 和证书私钥使用 Android Keystore 的 AES-GCM 加密保存,应用禁止备份。frpc 必需的明文配置与 PEM 只写入应用私有的 `noBackupFilesDir` 临时目录,进程结束时删除,下次启动清理残留。界面只显示分类后的错误与状态,最多保留 40 条,不展示原始 frpc 日志或凭据。配置读取失败时保留原数据并禁止覆盖。
+配置与 Token 继续使用 Android Keystore 的 AES-GCM 加密保存,禁止备份;读取失败时保留原数据并禁止覆盖。运行期间的 frpc 配置仅保存在应用私有临时目录,停止后清理。
## 最小 frps 示例
```toml
bindPort = 7000
-vhostHTTPSPort = 443
auth.method = "token"
-auth.token = "REPLACE_WITH_YOUR_TOKEN"
+auth.token = "replace-with-your-token"
transport.tls.force = true
-allowPorts = [{ start = 18080, end = 18089 }]
+allowPorts = [{ start = 18080, end = 18090 }]
```
-示例 HTTPS 隧道:目标为本应用 MCP,代理类型为 HTTPS,域名为 `phone.example.com`,插件为 HTTPS → HTTP,选择该域名的证书与私钥,公网地址填 `https://phone.example.com/mcp`。启用隧道并在首页启动 MCP 后,即可复制客户端配置。
-
-## 构建与来源
+## 构建与验证
-内核固定为 [fatedier/frp v0.71.0](https://github.com/fatedier/frp/tree/v0.71.0),Apache-2.0,许可证随 APK 保存在 `assets/licenses/frp-LICENSE.txt`。`scripts/build_frpc.py` 固定源码归档 SHA256,使用 Go 1.26.3、NDK 28.2.13676358 为四种 ABI 构建 Android API 28 可执行文件,并设置 16 KiB ELF 页对齐。
+内核固定为 frp v0.71.0,使用 `scripts/build_frpc.py` 构建四种 Android ABI。许可证保存在 `assets/licenses/frp-LICENSE.txt`。
-Gradle 的 `preBuild` 自动生成 `libfrpc.so` 并作为原生库打包、安装提取,在应用身份下作为独立进程执行。没有下载后执行的二进制,也不改写上游隧道协议。未启用 frpc Web 管理端口;构建时仅提供占位嵌入页面。运行方式遵循 [Android 对可写目录执行文件的限制](https://developer.android.com/about/versions/10/behavior-changes-10#execute-permission)。
+`scripts/smoke-frpc.py` 使用仅监听电脑回环地址的临时 frps,通过 ADB reverse 验证共享服务器的两条 TCP 隧道、MCP 鉴权、流式响应、独立启停及运行目录清理。使用独立 QA 包名,不覆盖日常应用。
-## 验证
-
-JVM 测试覆盖配置生成、组合校验、证书匹配、独立启停、MCP 端口变更、证书替换范围、临时文件清理和日志脱敏。
-
-设备测试使用 `scripts/smoke-frpc.py`:创建仅监听电脑回环地址的临时 frps,通过 adb reverse 连接,使用临时证书和双向 TLS,验证四种代理组合、MCP 鉴权与 initialize、HTTPS → HTTP 流式响应、停止网关后的自定义转发、独立停止和清理。测试结束关闭 frps、移除所建 adb reverse 映射;不需要公网服务器。
-
-使用独立的 QA applicationId 构建并安装应用与 androidTest APK 后运行:
-
-```text
+```shell
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest -I scripts/frpc-qa.init.gradle
-adb -s <设备序列号> install -r app/build/outputs/apk/debug/app-debug.apk
-adb -s <设备序列号> install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
python scripts/smoke-frpc.py --serial <设备序列号> --package com.powercess.mbrain.frpcqa
```
-
-此脚本拒绝对正式包与普通 `.debug` 包运行,避免修改日常使用的数据。四种 ABI 的打包检查不等同于所有架构和 OEM 的运行验证。
diff --git a/scripts/fixtures/frpc-certificate.go b/scripts/fixtures/frpc-certificate.go
deleted file mode 100644
index 5fcdefe..0000000
--- a/scripts/fixtures/frpc-certificate.go
+++ /dev/null
@@ -1,49 +0,0 @@
-// Generate ephemeral certificates for the local frpc integration test, never for deployment.
-package main
-
-import (
- "crypto/rand"
- "crypto/rsa"
- "crypto/x509"
- "crypto/x509/pkix"
- "encoding/pem"
- "math/big"
- "os"
- "path/filepath"
- "time"
-)
-
-func main() {
- key, err := rsa.GenerateKey(rand.Reader, 2048)
- if err != nil {
- panic(err)
- }
- serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
- if err != nil {
- panic(err)
- }
- template := &x509.Certificate{
- SerialNumber: serial, Subject: pkix.Name{CommonName: "phone.example.test"},
- DNSNames: []string{"phone.example.test", "passthrough.example.test"},
- NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour),
- IsCA: true, BasicConstraintsValid: true,
- KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
- ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
- }
- certificate, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
- if err != nil {
- panic(err)
- }
- privateKey, err := x509.MarshalPKCS8PrivateKey(key)
- if err != nil {
- panic(err)
- }
- for name, block := range map[string]*pem.Block{
- "certificate.crt": {Type: "CERTIFICATE", Bytes: certificate},
- "private.key": {Type: "PRIVATE KEY", Bytes: privateKey},
- } {
- if err := os.WriteFile(filepath.Join(os.Args[1], name), pem.EncodeToMemory(block), 0600); err != nil {
- panic(err)
- }
- }
-}
diff --git a/scripts/smoke-frpc.py b/scripts/smoke-frpc.py
index 01ab76c..cd1fd91 100644
--- a/scripts/smoke-frpc.py
+++ b/scripts/smoke-frpc.py
@@ -4,7 +4,6 @@
the script refuses the regular user-facing package. Requires Go, adb, built frp source.
"""
import argparse
-import base64
import json
import os
from pathlib import Path
@@ -33,20 +32,18 @@ def run(args):
binary = source / ("frps-test.exe" if os.name == "nt" else "frps-test")
subprocess.run(["go", "build", "-trimpath", "-buildvcs=false", "-tags=frps", "-o", str(binary), "./cmd/frps"], cwd=source, check=True)
ports = {}
- while len(ports) < 4:
+ while len(ports) < 3:
candidate = free_port()
if candidate not in ports.values():
- ports[["controlPort", "tcpPort", "rawPort", "httpsPort"][len(ports)]] = candidate
+ ports[["controlPort", "tcpPort", "mcpPort"][len(ports)]] = candidate
with tempfile.TemporaryDirectory(prefix="mbrain-frpc-test-") as temporary:
directory = Path(temporary)
- subprocess.run(["go", "run", str(root / "scripts/fixtures/frpc-certificate.go"), str(directory)], check=True)
token = secrets.token_urlsafe(24)
config = {
"bindAddr": "127.0.0.1", "bindPort": ports["controlPort"], "proxyBindAddr": "127.0.0.1",
- "vhostHTTPSPort": ports["httpsPort"], "auth": {"method": "token", "token": token},
- "transport": {"tls": {"force": True, "certFile": str(directory / "certificate.crt"),
- "keyFile": str(directory / "private.key"), "trustedCaFile": str(directory / "certificate.crt")}},
- "allowPorts": [{"single": ports["tcpPort"]}, {"single": ports["rawPort"]}],
+ "auth": {"method": "token", "token": token},
+ "transport": {"tls": {"force": True}},
+ "allowPorts": [{"single": ports["tcpPort"]}, {"single": ports["mcpPort"]}],
}
config_file = directory / "frps.json"
config_file.write_text(json.dumps(config), encoding="utf-8")
@@ -71,9 +68,7 @@ def run(args):
subprocess.run(adb + ["shell", "am", "start", "-n", args.package + "/com.powercess.mbrain.MainActivity"], check=True, stdout=subprocess.DEVNULL)
time.sleep(1)
command = adb + ["shell", "am", "instrument", "-w", "-r", "-e", "class", "com.powercess.mbrain.remote.FrpcDeviceTest"]
- parameters = dict(ports, frpToken=token,
- certificate=base64.b64encode((directory / "certificate.crt").read_bytes()).decode(),
- privateKey=base64.b64encode((directory / "private.key").read_bytes()).decode())
+ parameters = dict(ports, frpToken=token)
for name, value in parameters.items():
command += ["-e", name, str(value)]
command += [args.package + ".test/androidx.test.runner.AndroidJUnitRunner"]