feat: 支持局域网 HTTPS 直连并持久化插件连接配置

This commit is contained in:
tongtong committed 2026-11-24 16:24:37 +08:00
1 parent 9eba4556db
commit 2203afde3c
15 files changed
+486 -17

No files matched your search

@@ -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) {
@@ -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()
}
}
@@ -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<Settings.Data> {
@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<Settings.Data> {
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,请首次输入后保存"
}
}
}
}
}
}
}