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

+29 -2
View File
@@ -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.
+93
View File
@@ -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
}
+42
View File
@@ -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")
}
}