diff --git a/README.md b/README.md index 77e7c54..5755833 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,10 @@ Android Studio 本机编辑 → 增量上传 → 局域网服务编译 → 下载 APK → 本机 adb 安装。 +插件 0.1.3 支持 [局域网 HTTPS 直连](docs/lan-direct.md),无需本机 SSH 转发端口。 + +插件 0.1.4 支持 [连接配置与 Token 自动恢复](docs/plugin-0.1.4.md),保存一次后重启恢复,新项目复用最近保存的默认连接。 + ## 目录 | 目录 | 内容 | diff --git a/client/remote_run.py b/client/remote_run.py index b51883a..b6ad983 100644 --- a/client/remote_run.py +++ b/client/remote_run.py @@ -6,6 +6,7 @@ import json import os from pathlib import Path import subprocess +import ssl import time import urllib.request import urllib.parse @@ -19,6 +20,7 @@ def main(): parser.add_argument('--url', default='http://127.0.0.1:8765') parser.add_argument('--task', default=':app:assembleDebug') parser.add_argument('--adb', default='adb') + parser.add_argument('--server-cert', help='Trusted server public PEM certificate for LAN HTTPS') parser.add_argument('--device', help='Explicit adb device serial; omit to download only') args = parser.parse_args() token = os.environ.get('REMOTE_BUILD_TOKEN', '') @@ -38,7 +40,8 @@ def main(): data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(endpoint + '/api/v1' + path, data=data, method=method, headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}) - with urllib.request.urlopen(req, timeout=300) as response: + context = ssl.create_default_context(cafile=args.server_cert) if args.server_cert else None + with urllib.request.urlopen(req, timeout=300, context=context) as response: result = response.read() return result if '/artifacts/' in path else json.loads(result) diff --git a/client/test_smoke.py b/client/test_smoke.py index 037313b..ac61d41 100644 --- a/client/test_smoke.py +++ b/client/test_smoke.py @@ -18,6 +18,12 @@ ROOT = Path(__file__).resolve().parents[1] class SmokeTest(unittest.TestCase): def test_sync_build_download_and_second_revision(self): + self.exercise(False) + + def test_https_sync_build_download_and_second_revision(self): + self.exercise(True) + + def exercise(self, secure): binary = ROOT / 'dist' / ('remotecompile-windows-amd64.exe' if os.name == 'nt' else 'remotecompile') if not binary.exists(): self.skipTest(f'Build service binary first: {binary}') @@ -34,20 +40,29 @@ class SmokeTest(unittest.TestCase): with socket.socket() as sock: sock.bind(('127.0.0.1', 0)) port = sock.getsockname()[1] - endpoint = f'http://127.0.0.1:{port}' + endpoint = f'{"https" if secure else "http"}://127.0.0.1:{port}' env = dict(os.environ, REMOTE_BUILD_TOKEN='test-only-token-abcdefghijklmnopqrstuvwxyz') - process = subprocess.Popen([str(binary), '-listen', f'127.0.0.1:{port}', '-data', str(root / 'data')], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + command = [str(binary), '-listen', f'127.0.0.1:{port}', '-data', str(root / 'data')] + context = None + if secure: + import ssl + subprocess.run([str(binary), '-init-tls-host', '127.0.0.1', '-tls-dir', str(root/'tls')], check=True, capture_output=True) + command += ['-tls-cert', str(root/'tls/server.crt'), '-tls-key', str(root/'tls/server.key')] + context = ssl.create_default_context(cafile=str(root/'tls/server.crt')) + process = subprocess.Popen(command, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) try: for _ in range(100): try: req = urllib.request.Request(endpoint + '/api/v1/health', headers={'Authorization': 'Bearer ' + env['REMOTE_BUILD_TOKEN']}) - with urllib.request.urlopen(req, timeout=1): + with urllib.request.urlopen(req, timeout=1, context=context): break except OSError: time.sleep(.05) else: self.fail('Service did not start') command = [sys.executable, str(ROOT / 'client' / 'remote_run.py'), str(source), '--url', endpoint] + if secure: + command += ['--server-cert', str(root/'tls/server.crt')] first = subprocess.run(command, env=env, capture_output=True, text=True, timeout=30) self.assertEqual(first.returncode, 0, first.stderr) self.assertEqual(next((source / '.remotecompile').glob('*.apk')).read_bytes(), b'first') diff --git a/deploy/windows/enable-lan.ps1 b/deploy/windows/enable-lan.ps1 new file mode 100644 index 0000000..9ebd326 --- /dev/null +++ b/deploy/windows/enable-lan.ps1 @@ -0,0 +1,30 @@ +param( + [string]$Root='C:\ProgramData\VibeCodingRemoteCompilation', + [string]$Address='192.168.5.222', + [string]$AllowedSubnet='192.168.5.0/24', + [int]$Port=8765 +) +$ErrorActionPreference='Stop' +$configPath=Join-Path $Root 'bin\RemoteCompileService.xml' +[xml]$config=Get-Content -LiteralPath $configPath -Raw +$active=@(Get-ChildItem -LiteralPath "$Root\data\projects" -Filter active-build -Recurse -File -ErrorAction SilentlyContinue) +if($active.Count){throw 'A build is active; wait for completion before upgrading.'} +$exe=Join-Path $PSScriptRoot 'remotecompile-windows-amd64.exe' +if(-not(Test-Path -LiteralPath $exe)){throw 'Upload the new server executable next to this script.'} +$tlsDir=Join-Path $Root 'bin\tls' +& $exe -init-tls-host $Address -tls-dir $tlsDir +if($LASTEXITCODE -ne 0){throw 'Certificate generation failed'} +$backup="$configPath.before-lan.xml" +if(-not(Test-Path -LiteralPath $backup)){Copy-Item -LiteralPath $configPath -Destination $backup} +Stop-Service RemoteCompile +(Get-Service RemoteCompile).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(45)) +Copy-Item -LiteralPath $exe -Destination "$Root\bin\remotecompile.exe" -Force +$config.service.arguments="-listen $($Address):$Port -data `"$Root\data`" -tasks :app:assembleDebug -tls-cert `"$tlsDir\server.crt`" -tls-key `"$tlsDir\server.key`"" +[IO.File]::WriteAllText($configPath,$config.OuterXml,(New-Object Text.UTF8Encoding($false))) +if(Get-NetFirewallRule -Name 'RemoteCompile-LAN-HTTPS' -ErrorAction SilentlyContinue){Remove-NetFirewallRule -Name 'RemoteCompile-LAN-HTTPS'} +New-NetFirewallRule -Name 'RemoteCompile-LAN-HTTPS' -DisplayName 'Remote Compilation LAN HTTPS' -Direction Inbound -Action Allow -Protocol TCP -LocalAddress $Address -LocalPort $Port -RemoteAddress $AllowedSubnet -Profile Any -Program "$Root\bin\remotecompile.exe" | Out-Null +Start-Service RemoteCompile +Copy-Item -LiteralPath "$tlsDir\server.crt" -Destination (Join-Path $env:USERPROFILE '.remotecompile-server.crt') -Force +Get-Service RemoteCompile | Select-Object Name,Status +Write-Output "LAN endpoint: https://$($Address):$Port" +Write-Output 'Copy .remotecompile-server.crt to the client and configure it in the plugin. Never copy server.key.' diff --git a/docs/lan-direct.md b/docs/lan-direct.md new file mode 100644 index 0000000..ea04ffc --- /dev/null +++ b/docs/lan-direct.md @@ -0,0 +1,59 @@ +# 局域网 HTTPS 直连(插件 0.1.3) + +2026-11-24 状态:代码与产物已完成,本机服务端测试、8 项插件测试、HTTP/HTTPS 两条端到端测试通过;Windows/Linux/macOS 服务均已编译。Windows 服务器 SSH 不可达,用户确认稍后测试,因此尚未执行远端升级与防火墙变更。服务器恢复后再部署,当前不要将旧服务地址直接改为 HTTPS。 + +连接:Android Studio → `https://192.168.5.222:8765` → 编译服务。本机无需监听 18765 或运行 SSH 隧道。 + +## Windows 服务升级 + +管理员在服务器运行。把新版 `remotecompile-windows-amd64.exe` 和 `deploy/windows/enable-lan.ps1` 放到同一目录: + +```powershell +.\enable-lan.ps1 -Address '192.168.5.222' -AllowedSubnet '192.168.5.0/24' +``` + +脚本会: + +1. 拒绝在活动构建期间升级。 +2. 生成该服务器 IP 的 ECDSA 自签证书(有效期一年),已有匹配证书直接复用,不自动更换身份。 +3. 备份现有 XML 配置,保留 Token、JDK、SDK 与工作区,更新服务程序。 +4. 改为仅在指定局域网 IP 的 8765 端口提供 HTTPS。 +5. 创建 Windows 防火墙规则,仅允许指定网段访问该端口和程序。 +6. 启动服务,将公钥证书导出到部署用户的 `.remotecompile-server.crt`。 + +私钥保存在服务目录 `bin/tls/server.key`,不得复制到客户端或提交仓库。公钥证书 `server.crt` 可以复制给开发者,首次传递应通过已确认身份的 SSH 或可信渠道。 + +原来的回环 HTTP/SSH 转发地址不再适用于升级后的此实例;其他服务器不受影响。未配置 TLS 的服务仍可按旧方式监听回环地址;程序拒绝将明文 HTTP 绑定非回环地址。 + +## 插件配置 + +安装 `dist/remote-compilation-plugin-0.1.3.zip` 后重启 IDE。在右侧 Remote Configuration 设置: + +- 服务地址:`https://192.168.5.222:8765`。 +- Token:原 Windows 服务的 Token,地址变化后需要重新保存到该地址对应的 PasswordSafe 项。 +- 服务器公钥证书:选择复制到本机的 `.crt` 文件。可放在本项目被 Git 忽略的 `.deployment/` 下。 +- 保存后显示 SHA-256 指纹;与服务器生成证书时输出的指纹核对。 + +插件仅对该连接使用导入证书作为信任锚,仍采用 Java 标准证书及 HTTPS 地址校验;不禁用验证、不修改 JVM 全局信任库。使用可信 CA 签发的证书时可留空,使用 JVM 默认信任库。 + +然后在底部选择设备,点击 Remote Run。服务器证书不匹配、过期或地址不在证书 SAN 内时,应修正配置或重新核验服务器身份;不要绕过校验。IP 改变或证书到期时需明确重新签发,并更新客户端证书。 + +命令行客户端: + +```powershell +$env:REMOTE_BUILD_TOKEN = '<原服务Token>' +python client/remote_run.py 'D:\项目目录' --url 'https://192.168.5.222:8765' --server-cert '.deployment\server-192.168.5.222.crt' +``` + +## 其他平台 + +```sh +./remotecompile -init-tls-host 192.168.5.224 -tls-dir ./tls +./remotecompile -listen 192.168.5.224:8765 -data ./data -tls-cert ./tls/server.crt -tls-key ./tls/server.key +``` + +运行账户需要读取证书/私钥,并写入数据和构建缓存;防火墙仅开放所需局域网范围。 + +## 回退 + +确认没有活动构建后停止服务,恢复备份 XML `RemoteCompileService.xml.before-lan.xml`,删除 `RemoteCompile-LAN-HTTPS` 防火墙规则,再启动服务。回退到原回环 HTTP 配置后,客户端恢复原 SSH 隧道地址。证书不必删除,避免不必要的身份变更。 diff --git a/docs/plugin-0.1.4.md b/docs/plugin-0.1.4.md new file mode 100644 index 0000000..df651bf --- /dev/null +++ b/docs/plugin-0.1.4.md @@ -0,0 +1,13 @@ +# 插件 0.1.4:记住连接配置 + +保存一次后,服务地址、Gradle 任务、adb 路径、服务器证书路径和安装开关写入 IDE 持久状态,重启后恢复;新项目自动使用最近保存的默认连接配置。已有项目保留自己的连接设置。 + +Token 继续按服务地址保存在 IDE PasswordSafe 中;打开配置页时后台读取并以密码掩码恢复,显示“已保存并自动恢复”。留空保存会保留该地址已有 Token。输入新 Token 后保存才会替换;修改服务地址后只读取新地址对应的 Token,不会自动把旧服务器凭据传给新服务器。 + +全局默认配置写入 IDE options 下的 `remote-compilation-defaults.xml`,不包含 Token。远程工作区 ID 和设备选择仍按项目保存,不共享到其他项目。配置字段沿用旧版名称,兼容迁移已有项目设置。 + +请在 IDE 密码管理设置中启用持久密码保存并允许解锁密码库;如果用户明确将 IDE 设为“仅会话/不保存密码”,插件不能保证重启后恢复 Token,也不会改为明文写入项目文件。 + +升级:通过 Install Plugin from Disk 安装 `remote-compilation-plugin-0.1.4.zip`,重启 IDE。在已有项目确认配置后点击一次保存,将它作为新项目的默认值。 + +2026-11-24:编译打包成功,11 项测试通过,包含真实 IDE XML 序列化往返、全局默认值不共享工作区/设备、旧版配置迁移。已核对本机 Android Studio 2026.2.2 的 PasswordSafe.isMemoryOnly 方法存在,避免引入新的签名兼容问题。操作系统密码库的实际解锁与跨重启读取仍由 IDE 运行环境验证。 diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 093f97f..4329a82 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -3,7 +3,7 @@ plugins { id("org.jetbrains.intellij.platform") version "2.5.0" } group = "studio.tongtong" -version = "0.1.2" +version = "0.1.4" repositories { mavenCentral() intellijPlatform { defaultRepositories() } diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt index 65a3f6d..042e530 100644 --- a/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt @@ -77,7 +77,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos @Volatile private var cancelRequested = false @Volatile private var busy = false private val gson = Gson() - private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build() + private var http = ServerTls.client("") private val polling = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay({ refreshDevices() }, 1, 5, TimeUnit.SECONDS) init { val configure = JButton("连接设置") @@ -170,6 +170,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos override fun run(indicator: ProgressIndicator) { var secret = "" try { + http = ServerTls.client(cfg.serverCertificate) secret = PasswordSafe.instance.getPassword(credentials(base)) ?: "" check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" } if (cfg.install) { diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerTls.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerTls.kt new file mode 100644 index 0000000..82f4e00 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerTls.kt @@ -0,0 +1,31 @@ +package studio.tongtong.remotecompile + +import java.net.http.HttpClient +import java.nio.file.Files +import java.nio.file.Path +import java.security.KeyStore +import java.security.MessageDigest +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import java.time.Duration +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManagerFactory + +object ServerTls { + fun certificate(file: String): X509Certificate = Files.newInputStream(Path.of(file)).use { + (CertificateFactory.getInstance("X.509").generateCertificate(it) as X509Certificate).apply { checkValidity() } + } + fun fingerprint(file: String): String = MessageDigest.getInstance("SHA-256").digest(certificate(file).encoded).joinToString(":") { "%02X".format(it) } + fun client(file: String): HttpClient { + val builder = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)) + if (file.isNotBlank()) { + val cert = certificate(file) + val store = KeyStore.getInstance(KeyStore.getDefaultType()).apply { load(null, null); setCertificateEntry("remotecompile", cert) } + val trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { init(store) } + val context = SSLContext.getInstance("TLS").apply { init(null, trust.trustManagers, null) } + builder.sslContext(context) + } + // Keep the JDK HTTPS hostname verification and redirect policy intact. + return builder.build() + } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt index c8547b3..3043802 100644 --- a/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt @@ -12,6 +12,16 @@ import java.awt.BorderLayout import java.awt.GridLayout import java.net.URI import javax.swing.* +import javax.swing.event.DocumentEvent +import javax.swing.event.DocumentListener + +@State(name = "RemoteCompilationDefaults", storages = [Storage("remote-compilation-defaults.xml")]) +@Service(Service.Level.APP) +class ConnectionDefaults : PersistentStateComponent { + @Volatile private var data = Settings.Data() + @Synchronized override fun getState() = data.copy() + @Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "") } +} @State(name = "RemoteCompilation", storages = [Storage("remote-compilation.xml")]) @Service(Service.Level.PROJECT) @@ -22,18 +32,31 @@ class Settings : PersistentStateComponent { var task: String = ":app:assembleDebug", var adb: String = "", var device: String = "", - var install: Boolean = false + var install: Boolean = false, + var serverCertificate: String = "", + var configured: Boolean = false ) @Volatile private var data = Data() - @Synchronized fun snapshot(): Data = data.copy() - override fun getState(): Data = snapshot() - @Synchronized override fun loadState(state: Data) { data = state.copy() } + private fun defaults() = ApplicationManager.getApplication()?.getService(ConnectionDefaults::class.java) + @Synchronized fun snapshot(): Data { + val shared = if (!data.configured) defaults()?.getState() else null + return if (shared?.configured == true) shared.copy(projectId = data.projectId, device = data.device) else data.copy() + } + @Synchronized override fun getState(): Data = data.copy() + @Synchronized override fun loadState(state: Data) { + val initial = Data() + val legacy = state.url != initial.url || state.projectId.isNotBlank() || state.task != initial.task || state.adb.isNotBlank() || state.install || state.serverCertificate.isNotBlank() + data = state.copy(configured = state.configured || legacy) + } @Synchronized fun saveConfiguration(next: Data) { - data = next.copy(projectId = if (data.url == next.url) data.projectId else "", device = data.device) + val current = snapshot() + data = next.copy(projectId = if (current.url == next.url) current.projectId else "", device = current.device, configured = true) + defaults()?.loadState(data) } @Synchronized fun selectDevice(serial: String) { data = data.copy(device = serial) } @Synchronized fun projectAllocated(url: String, id: String) { - if (data.url == url) data = data.copy(projectId = id) + val current = snapshot() + if (current.url == url) data = current.copy(projectId = id, configured = true) } } @@ -60,27 +83,52 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL private val token = JPasswordField() private val task = JTextField(original.task) private val adb = JTextField(original.adb) + private val certificate = JTextField(original.serverCertificate) private val install = JCheckBox("构建成功后安装到所选设备", original.install) private val save = JButton("保存配置") private val status = JLabel("Token 留空保留已保存值") + private val tokenStatus = JLabel("正在读取已保存 Token…") + private var tokenRequest = 0 init { val fields = JPanel(GridLayout(0, 1, 0, 5)) listOf("服务地址" to url, "Token(留空保留)" to token, "Gradle 任务" to task, "adb 路径(留空自动使用项目 SDK)" to adb).forEach { (label, field) -> fields.add(JLabel(label)); fields.add(field) } - fields.add(install); fields.add(save); fields.add(status) + fields.add(tokenStatus) + fields.add(JLabel("服务器公钥证书(自签 HTTPS,留空使用默认信任库)")); fields.add(certificate) + val choose = JButton("选择服务器证书 .crt / .pem") + choose.addActionListener { + val picker = JFileChooser().apply { fileFilter = javax.swing.filechooser.FileNameExtensionFilter("服务器证书", "crt", "pem", "cer") } + if (picker.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) certificate.text = picker.selectedFile.absolutePath + } + fields.add(choose); fields.add(install); fields.add(save); fields.add(status) border = BorderFactory.createEmptyBorder(12, 12, 12, 12) add(fields, BorderLayout.NORTH) + val tokenTimer = Timer(350) { restoreToken() }.apply { isRepeats = false } + url.document.addDocumentListener(object : DocumentListener { + private fun changed() { + tokenRequest++; token.text = "" + tokenStatus.text = "地址已改变,正在查找对应 Token…" + tokenTimer.restart() + } + override fun insertUpdate(e: DocumentEvent) = changed() + override fun removeUpdate(e: DocumentEvent) = changed() + override fun changedUpdate(e: DocumentEvent) = changed() + }) + restoreToken() save.addActionListener { val base = url.text.trim().trimEnd('/') try { validateEndpoint(base); require(task.text.isNotBlank()) { "请填写 Gradle 任务" } } catch (e: IllegalArgumentException) { status.text = e.message; return@addActionListener } + tokenRequest++ // Discard a pending restore before replacing/saving this credential. val entered = String(token.password); token.text = "" val previous = settings.snapshot() - val next = previous.copy(url = base, task = task.text.trim(), adb = adb.text.trim(), install = install.isSelected, + val next = previous.copy(url = base, task = task.text.trim(), adb = adb.text.trim(), install = install.isSelected, serverCertificate = certificate.text.trim(), projectId = if (previous.url == base) previous.projectId else "") save.isEnabled = false; status.text = "正在保存…" ApplicationManager.getApplication().executeOnPooledThread { + var fingerprint = "" val failure = runCatching { + if (next.serverCertificate.isNotBlank()) fingerprint = ServerTls.fingerprint(next.serverCertificate) if (entered.isNotEmpty()) { require(entered.length >= 24) { "Token 至少需要 24 个字符" } PasswordSafe.instance.setPassword(credentials(base), entered) @@ -90,11 +138,36 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL ApplicationManager.getApplication().invokeLater { if (!project.isDisposed) { save.isEnabled = true - status.text = if (failure == null) "已保存;点击工具栏 Remote Run 执行" else "保存失败,请检查 Token 或密码库" + status.text = if (failure == null) (if (fingerprint.isEmpty()) "已保存;点击 Remote Run 执行" else "证书 SHA256: $fingerprint") else "保存失败,请检查证书、Token 或密码库" + if (failure == null) restoreToken() project.getService(PanelService::class.java).panel?.refreshDevices() } } } } } + private fun restoreToken() { + val base = url.text.trim().trimEnd('/') + val request = ++tokenRequest + ApplicationManager.getApplication().executeOnPooledThread { + val saved = runCatching { + val safe = PasswordSafe.instance + safe.getPassword(credentials(base)).orEmpty() to safe.isMemoryOnly + } + ApplicationManager.getApplication().invokeLater { + if (!project.isDisposed && request == tokenRequest && url.text.trim().trimEnd('/') == base) { + if (saved.isFailure) tokenStatus.text = "密码库不可用,请检查 IDE 密码保存设置" + else { + val (value, memoryOnly) = saved.getOrDefault("" to false) + if (token.password.isEmpty()) token.text = value + tokenStatus.text = when { + memoryOnly -> "IDE 当前仅在内存保存密码;请在密码设置中启用持久保存" + value.isNotEmpty() -> "Token 已保存并自动恢复(掩码显示,无需重输)" + else -> "该服务尚未保存 Token,请首次输入后保存" + } + } + } + } + } + } } diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/ServerTlsTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/ServerTlsTest.kt new file mode 100644 index 0000000..1b918d1 --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/ServerTlsTest.kt @@ -0,0 +1,50 @@ +package studio.tongtong.remotecompile + +import com.sun.net.httpserver.HttpsConfigurator +import com.sun.net.httpserver.HttpsServer +import org.junit.Assert.* +import org.junit.Test +import java.net.InetSocketAddress +import java.net.URI +import java.net.http.HttpRequest +import java.net.http.HttpResponse +import java.nio.file.Files +import java.nio.file.Path +import java.security.KeyStore +import java.util.concurrent.TimeUnit +import javax.net.ssl.KeyManagerFactory +import javax.net.ssl.SSLContext + +class ServerTlsTest { + @Test fun trustedLanCertificateWorksAndDifferentCertificateFails() { + val root = Files.createTempDirectory("remote-tls-test") + var server: HttpsServer? = null + try { + fun certificate(name: String): Pair { + val path = root.resolve("$name.p12") + val log = root.resolve("$name.log") + val tool = Path.of(System.getProperty("java.home"), "bin", if (System.getProperty("os.name").startsWith("Windows")) "keytool.exe" else "keytool") + val process = ProcessBuilder(tool.toString(), "-genkeypair", "-alias", "server", "-keyalg", "EC", "-dname", "CN=localhost", "-ext", "SAN=IP:127.0.0.1,DNS:localhost", "-validity", "2", "-storetype", "PKCS12", "-keystore", path.toString(), "-storepass", "test-password", "-noprompt") + .redirectErrorStream(true).redirectOutput(log.toFile()).start() + try { assertTrue(process.waitFor(30, TimeUnit.SECONDS)); assertEquals(String(Files.readAllBytes(log), Charsets.ISO_8859_1), 0, process.exitValue()) } + finally { if (process.isAlive) process.destroyForcibly() } + val store = KeyStore.getInstance("PKCS12").apply { Files.newInputStream(path).use { load(it, "test-password".toCharArray()) } } + val cert = root.resolve("$name.crt"); Files.write(cert, store.getCertificate("server").encoded) + return store to cert + } + val (store, cert) = certificate("trusted") + val (_, wrong) = certificate("wrong") + val managers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(store, "test-password".toCharArray()) } + val context = SSLContext.getInstance("TLS").apply { init(managers.keyManagers, null, null) } + server = HttpsServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + httpsConfigurator = HttpsConfigurator(context) + createContext("/") { exchange -> exchange.sendResponseHeaders(200, 2); exchange.responseBody.use { it.write("ok".toByteArray()) } } + start() + } + val request = HttpRequest.newBuilder(URI("https://127.0.0.1:${server.address.port}/")).build() + assertEquals(200, ServerTls.client(cert.toString()).send(request, HttpResponse.BodyHandlers.ofString()).statusCode()) + assertTrue(runCatching { ServerTls.client(wrong.toString()).send(request, HttpResponse.BodyHandlers.ofString()) }.isFailure) + assertEquals(95, ServerTls.fingerprint(cert.toString()).length) + } finally { server?.stop(0); root.toFile().deleteRecursively() } + } +} diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/SettingsTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/SettingsTest.kt index 936eead..f038847 100644 --- a/plugin/src/test/kotlin/studio/tongtong/remotecompile/SettingsTest.kt +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/SettingsTest.kt @@ -4,6 +4,34 @@ import org.junit.Assert.* import org.junit.Test class SettingsTest { + @Test fun allConnectionFieldsSurvivePlatformXmlSerialization() { + val saved = Settings().apply { + saveConfiguration(Settings.Data(url = "https://192.168.5.222:8765", task = ":app:assembleDebug", + adb = "D:/Android SDK/platform-tools/adb.exe", install = true, serverCertificate = "D:/证书/server.crt")) + selectDevice("USB123") + projectAllocated("https://192.168.5.222:8765", "workspace-123") + } + val xml = com.intellij.util.xmlb.XmlSerializer.serialize(saved.getState()) + val state = com.intellij.util.xmlb.XmlSerializer.deserialize(xml, Settings.Data::class.java) + val reopened = Settings().apply { loadState(state) } + assertEquals(saved.snapshot(), reopened.snapshot()) + assertTrue(reopened.snapshot().configured) + } + @Test fun globalDefaultsNeverShareProjectWorkspaceOrDevice() { + val shared = ConnectionDefaults() + shared.loadState(Settings.Data(url = "https://192.168.5.222:8765", adb = "custom-adb", serverCertificate = "server.crt", configured = true, + projectId = "must-not-share", device = "must-not-share")) + assertEquals("", shared.getState().projectId) + assertEquals("", shared.getState().device) + assertEquals("custom-adb", shared.getState().adb) + assertEquals("server.crt", shared.getState().serverCertificate) + } + @Test fun legacyProjectSettingsAreKeptAfterUpgrade() { + val settings = Settings() + settings.loadState(Settings.Data(url = "http://127.0.0.1:18765", adb = "old-adb")) + assertTrue(settings.snapshot().configured) + assertEquals("old-adb", settings.snapshot().adb) + } @Test fun savingConfigurationDoesNotLoseWorkspaceAllocatedByRunningBuild() { val settings = Settings() val editing = settings.snapshot().copy(task = ":app:assembleDemoDebug") diff --git a/server/main.go b/server/main.go index 6268b9c..629ce3d 100644 --- a/server/main.go +++ b/server/main.go @@ -5,6 +5,7 @@ import ( "crypto/rand" "crypto/sha256" "crypto/subtle" + "crypto/tls" "encoding/base64" "encoding/hex" "encoding/json" @@ -13,6 +14,7 @@ import ( "fmt" "io" "log" + "net" "net/http" "os" "os/exec" @@ -142,7 +144,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") fail := func(e error) { http.Error(w, e.Error(), 400) } if r.URL.Path == "/api/v1/health" { - jsonOut(w, map[string]any{"version": "0.1.0", "os": runtime.GOOS, "sync": "http-manifest"}) + jsonOut(w, map[string]any{"version": "0.1.1", "os": runtime.GOOS, "sync": "http-manifest"}) return } if len(parts) < 3 || parts[0] != "api" || parts[1] != "v1" { @@ -509,7 +511,27 @@ func main() { addr := flag.String("listen", "127.0.0.1:8765", "HTTP bind address; use HTTPS proxy or SSH tunnel remotely") root := flag.String("data", "./data", "service data directory") tasks := flag.String("tasks", ":app:assembleDebug", "comma separated allowed Gradle tasks") + cert := flag.String("tls-cert", "", "PEM certificate path") + key := flag.String("tls-key", "", "PEM private key path") + initHost := flag.String("init-tls-host", "", "generate a local certificate for this IP/hostname and exit") + tlsDir := flag.String("tls-dir", "./tls", "certificate output directory") flag.Parse() + if *initHost != "" { + if e := initCertificate(*initHost, *tlsDir); e != nil { + log.Fatal(e) + } + return + } + if (*cert == "") != (*key == "") { + log.Fatal("tls-cert and tls-key must be provided together") + } + host, _, e := net.SplitHostPort(*addr) + if e != nil { + log.Fatal(e) + } + if *cert == "" && host != "localhost" && (net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback()) { + log.Fatal("non-loopback listeners require TLS") + } token := os.Getenv("REMOTE_BUILD_TOKEN") if len(token) < 24 { log.Fatal("REMOTE_BUILD_TOKEN must contain at least 24 characters") @@ -555,6 +577,7 @@ func main() { } log.Printf("remotecompile listening on %s (%s)", *addr, runtime.GOOS) srv := &http.Server{Addr: *addr, Handler: s, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 5 * time.Minute, IdleTimeout: 60 * time.Second} + srv.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt, syscall.SIGTERM) go func() { @@ -573,7 +596,11 @@ func main() { defer cancel() srv.Shutdown(ctx) }() - if e := srv.ListenAndServe(); e != nil && e != http.ErrServerClosed { + serve := srv.ListenAndServe + if *cert != "" { + serve = func() error { return srv.ListenAndServeTLS(*cert, *key) } + } + if e := serve(); e != nil && e != http.ErrServerClosed { log.Fatal(e) } // Let workers persist terminal state and clear their active markers. diff --git a/server/tls.go b/server/tls.go new file mode 100644 index 0000000..afa67f9 --- /dev/null +++ b/server/tls.go @@ -0,0 +1,93 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "fmt" + "math/big" + "net" + "os" + "path/filepath" + "strings" + "time" +) + +func initCertificate(host, dir string) error { + if strings.TrimSpace(host) != host || host == "" || strings.ContainsAny(host, "/\\ :\x00") { + if net.ParseIP(host) == nil { + return fmt.Errorf("invalid certificate host") + } + } + certFile, keyFile := filepath.Join(dir, "server.crt"), filepath.Join(dir, "server.key") + if _, e := os.Stat(certFile); e == nil { + pair, e := tls.LoadX509KeyPair(certFile, keyFile) + if e != nil { + return e + } + cert, e := x509.ParseCertificate(pair.Certificate[0]) + if e != nil { + return e + } + if e = cert.VerifyHostname(host); e != nil { + return e + } + if time.Now().After(cert.NotAfter) { + return fmt.Errorf("certificate expired; rotate explicitly") + } + fmt.Printf("Certificate SHA256: %s\n", digest(pair.Certificate[0])) + return nil + } + if _, e := os.Stat(keyFile); e == nil { + return fmt.Errorf("private key already exists without certificate; recover explicitly") + } + private, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if e != nil { + return e + } + serial, e := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + if e != nil { + return e + } + cert := &x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "Remote Compilation"}, NotBefore: time.Now().Add(-5 * time.Minute), NotAfter: time.Now().AddDate(1, 0, 0), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, DNSNames: []string{"localhost"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}} + if ip := net.ParseIP(host); ip != nil { + cert.IPAddresses = append(cert.IPAddresses, ip) + } else { + cert.DNSNames = append(cert.DNSNames, host) + } + der, e := x509.CreateCertificate(rand.Reader, cert, cert, &private.PublicKey, private) + if e != nil { + return e + } + key, e := x509.MarshalPKCS8PrivateKey(private) + if e != nil { + return e + } + if e = os.MkdirAll(dir, 0700); e != nil { + return e + } + write := func(path string, b []byte) error { + f, e := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if e != nil { + return e + } + _, e = f.Write(b) + closeErr := f.Close() + if e != nil { + return e + } + return closeErr + } + if e = write(keyFile, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key})); e != nil { + return e + } + if e = write(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})); e != nil { + return e + } + fmt.Printf("Certificate SHA256: %s\n", digest(der)) + return nil +} diff --git a/server/tls_test.go b/server/tls_test.go new file mode 100644 index 0000000..a18c45b --- /dev/null +++ b/server/tls_test.go @@ -0,0 +1,42 @@ +package main + +import ( + "crypto/tls" + "crypto/x509" + "os" + "path/filepath" + "testing" +) + +func TestLocalCertificateIdentityAndReuse(t *testing.T) { + dir := t.TempDir() + if e := initCertificate("192.168.5.222", dir); e != nil { + t.Fatal(e) + } + c := filepath.Join(dir, "server.crt") + k := filepath.Join(dir, "server.key") + before, _ := os.ReadFile(c) + pair, e := tls.LoadX509KeyPair(c, k) + if e != nil { + t.Fatal(e) + } + cert, _ := x509.ParseCertificate(pair.Certificate[0]) + for _, host := range []string{"192.168.5.222", "localhost", "127.0.0.1"} { + if e = cert.VerifyHostname(host); e != nil { + t.Fatal(e) + } + } + if cert.VerifyHostname("192.168.5.223") == nil { + t.Fatal("wrong IP trusted") + } + if e = initCertificate("192.168.5.222", dir); e != nil { + t.Fatal(e) + } + after, _ := os.ReadFile(c) + if string(before) != string(after) { + t.Fatal("certificate unexpectedly rotated") + } + if initCertificate("192.168.5.223", dir) == nil { + t.Fatal("existing mismatched certificate accepted") + } +}