feat: 支持局域网 HTTPS 直连并持久化插件连接配置
This commit is contained in:
1 parent
9eba4556db
commit
2203afde3c
15 files changed
+486
-17
No files matched your search
@@ -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() }
|
||||
|
||||
@@ -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,请首次输入后保存"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<KeyStore, Path> {
|
||||
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() }
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user