feat: configure HTTP/HTTPS public entry and managed certificates

This commit is contained in:
Codex committed 2026-10-26 14:06:41 +08:00
1 parent 35596cda9d
commit 88ea6b7854
21 files changed
+1309 -149

No files matched your search

+238 -77
View File
@@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
@@ -23,6 +24,8 @@ var domainPattern = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:
type configuration struct {
domain string
scheme string
port int
mode string
dataDir string
cacheDir string
@@ -36,36 +39,123 @@ var state struct {
}
type CertificateStatus struct {
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
ConfiguredMode string `json:"configured_mode"`
Domain string `json:"domain"`
ConfiguredDomain string `json:"configured_domain"`
RestartRequired bool `json:"restart_required"`
DNS []string `json:"dns"`
HTTPAddr string `json:"http_address"`
HTTPSAddr string `json:"https_address"`
Cached bool `json:"certificate_cached"`
Valid bool `json:"certificate_valid"`
Issuer string `json:"issuer,omitempty"`
NotBefore time.Time `json:"not_before,omitempty"`
NotAfter time.Time `json:"not_after,omitempty"`
Renewal string `json:"renewal_mode"`
DirectPortPublic bool `json:"management_direct_public"`
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
ConfiguredMode string `json:"configured_mode"`
Scheme string `json:"scheme"`
ConfiguredScheme string `json:"configured_scheme"`
Domain string `json:"domain"`
ConfiguredDomain string `json:"configured_domain"`
Port int `json:"port"`
ConfiguredPort int `json:"configured_port"`
PublicBase string `json:"public_base"`
ConfiguredPublicBase string `json:"configured_public_base"`
RestartRequired bool `json:"restart_required"`
DNS []string `json:"dns"`
HTTPAddr string `json:"http_address"`
HTTPSAddr string `json:"https_address"`
Cached bool `json:"certificate_cached"`
Valid bool `json:"certificate_valid"`
CertSource string `json:"cert_source,omitempty"`
Issuer string `json:"issuer,omitempty"`
NotBefore time.Time `json:"not_before,omitempty"`
NotAfter time.Time `json:"not_after,omitempty"`
Renewal string `json:"renewal_mode"`
DirectPortPublic bool `json:"management_direct_public"`
}
// DataDir returns the active TLS data directory (empty before Start).
func DataDir() string {
state.RLock()
defer state.RUnlock()
return state.config.dataDir
}
func ValidDomain(domain string) bool {
return len(domain) <= 253 && domainPattern.MatchString(domain) && net.ParseIP(domain) == nil
}
func ValidScheme(scheme string) bool {
return scheme == "http" || scheme == "https"
}
// EffectivePort returns the listen/public port. port<=0 means scheme default.
func EffectivePort(scheme string, port int) int {
if port > 0 {
return port
}
if scheme == "http" {
return 80
}
return 443
}
// PublicBaseURL builds {scheme}://{host}[:port], omitting :80/:443 defaults.
func PublicBaseURL(scheme, host string, port int) string {
scheme = strings.ToLower(strings.TrimSpace(scheme))
host = strings.ToLower(strings.TrimSpace(host))
if !ValidScheme(scheme) || host == "" || !ValidDomain(host) {
return ""
}
eff := EffectivePort(scheme, port)
if (scheme == "http" && eff == 80) || (scheme == "https" && eff == 443) {
return scheme + "://" + host
}
return fmt.Sprintf("%s://%s:%d", scheme, host, eff)
}
func normalizeScheme(scheme string) string {
scheme = strings.ToLower(strings.TrimSpace(scheme))
if scheme == "" {
return "https"
}
return scheme
}
func readPersisted(dataDir, name string) (string, error) {
raw, err := os.ReadFile(filepath.Join(dataDir, name))
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
if err != nil {
return "", err
}
return strings.TrimSpace(string(raw)), nil
}
func writePersisted(dataDir, name, value string) error {
if err := os.MkdirAll(dataDir, 0o700); err != nil {
return err
}
temp, err := os.CreateTemp(dataDir, "."+name+"-*")
if err != nil {
return err
}
defer os.Remove(temp.Name())
defer temp.Close()
if err := temp.Chmod(0o600); err != nil {
return err
}
if _, err := temp.WriteString(value + "\n"); err != nil {
return err
}
if err := temp.Sync(); err != nil {
return err
}
if err := temp.Close(); err != nil {
return err
}
return os.Rename(temp.Name(), filepath.Join(dataDir, name))
}
func configFromEnvironment(dataDir string) (configuration, error) {
mode := os.Getenv("VPN_TLS_MODE")
if mode == "" {
if raw, err := os.ReadFile(filepath.Join(dataDir, "tls-mode")); err == nil {
mode = strings.TrimSpace(string(raw))
} else if !errors.Is(err, os.ErrNotExist) {
raw, err := readPersisted(dataDir, "tls-mode")
if err != nil {
return configuration{}, fmt.Errorf("读取 TLS 模式配置: %w", err)
}
mode = raw
}
if mode == "" {
mode = "autocert"
@@ -75,56 +165,111 @@ func configFromEnvironment(dataDir string) (configuration, error) {
}
domain := strings.ToLower(strings.TrimSpace(os.Getenv("VPN_TLS_DOMAIN")))
if domain == "" {
if raw, err := os.ReadFile(filepath.Join(dataDir, "tls-domain")); err == nil {
domain = strings.ToLower(strings.TrimSpace(string(raw)))
} else if !errors.Is(err, os.ErrNotExist) {
raw, err := readPersisted(dataDir, "tls-domain")
if err != nil {
return configuration{}, fmt.Errorf("读取 TLS 域名配置: %w", err)
}
domain = strings.ToLower(raw)
}
if domain != "" && !ValidDomain(domain) {
return configuration{}, fmt.Errorf("VPN_TLS_DOMAIN 不是有效的单个完整域名")
}
schemeEnv := strings.TrimSpace(os.Getenv("VPN_TLS_SCHEME"))
scheme := normalizeScheme(schemeEnv)
if schemeEnv == "" {
raw, err := readPersisted(dataDir, "tls-scheme")
if err != nil {
return configuration{}, fmt.Errorf("读取公网协议配置: %w", err)
}
scheme = normalizeScheme(raw)
}
if !ValidScheme(scheme) {
return configuration{}, fmt.Errorf("VPN_TLS_SCHEME 仅支持 http 或 https")
}
port := 0
if raw := strings.TrimSpace(os.Getenv("VPN_TLS_PORT")); raw != "" {
var err error
port, err = strconv.Atoi(raw)
if err != nil || port < 1 || port > 65535 {
return configuration{}, fmt.Errorf("VPN_TLS_PORT 必须是 1-65535")
}
} else {
raw, err := readPersisted(dataDir, "tls-port")
if err != nil {
return configuration{}, fmt.Errorf("读取公网端口配置: %w", err)
}
if raw != "" {
port, err = strconv.Atoi(raw)
if err != nil || port < 1 || port > 65535 {
return configuration{}, fmt.Errorf("tls-port 必须是 1-65535")
}
}
}
httpAddr := os.Getenv("VPN_TLS_HTTP_ADDR")
if httpAddr == "" {
httpAddr = ":80"
if scheme == "http" {
httpAddr = fmt.Sprintf(":%d", EffectivePort(scheme, port))
} else {
httpAddr = ":80"
}
}
httpsAddr := os.Getenv("VPN_TLS_HTTPS_ADDR")
if httpsAddr == "" {
httpsAddr = ":443"
if scheme == "https" {
httpsAddr = fmt.Sprintf(":%d", EffectivePort(scheme, port))
} else {
httpsAddr = ":443"
}
}
return configuration{domain: domain, mode: mode, dataDir: dataDir, cacheDir: filepath.Join(dataDir, "acme"), httpAddr: httpAddr, httpsAddr: httpsAddr}, nil
return configuration{domain: domain, scheme: scheme, port: port, mode: mode, dataDir: dataDir, cacheDir: filepath.Join(dataDir, "acme"), httpAddr: httpAddr, httpsAddr: httpsAddr}, nil
}
func ConfigureDomain(dataDir, domain string) error {
if os.Getenv("VPN_TLS_DOMAIN") != "" {
return fmt.Errorf("当前由 VPN_TLS_DOMAIN 环境变量管理域名,请修改启动配置")
return ConfigurePublicEntry(dataDir, "https", domain, 0)
}
// ConfigurePublicEntry persists scheme/host/port for the public management entry.
// port<=0 means scheme default (80 for http, 443 for https).
func ConfigurePublicEntry(dataDir, scheme, domain string, port int) error {
if os.Getenv("VPN_TLS_DOMAIN") != "" || os.Getenv("VPN_TLS_SCHEME") != "" || os.Getenv("VPN_TLS_PORT") != "" {
return fmt.Errorf("当前由 VPN_TLS_* 环境变量管理公网入口,请修改启动配置")
}
scheme = normalizeScheme(scheme)
domain = strings.ToLower(strings.TrimSpace(domain))
if !ValidScheme(scheme) {
return fmt.Errorf("协议仅支持 http 或 https")
}
if !ValidDomain(domain) {
return fmt.Errorf("请输入单个有效的完整域名")
}
if err := os.MkdirAll(dataDir, 0o700); err != nil {
return err
if port < 0 || port > 65535 {
return fmt.Errorf("端口必须是 0-65535(0 表示协议默认端口)")
}
temp, err := os.CreateTemp(dataDir, ".tls-domain-*")
if err != nil {
return err
if scheme == "https" && EffectivePort(scheme, port) == 80 {
return fmt.Errorf("HTTPS 不能使用 HTTP-01 验证端口 80")
}
defer os.Remove(temp.Name())
defer temp.Close()
if err := temp.Chmod(0o600); err != nil {
return err
portValue := ""
if port > 0 {
portValue = fmt.Sprintf("%d", port)
}
if _, err := temp.WriteString(domain + "\n"); err != nil {
return err
values := []struct{ name, value string }{{"tls-domain", domain}, {"tls-scheme", scheme}, {"tls-port", portValue}}
old := make([]string, len(values))
for i, entry := range values {
var err error
old[i], err = readPersisted(dataDir, entry.name)
if err != nil {
return err
}
}
if err := temp.Sync(); err != nil {
return err
for i, entry := range values {
if err := writePersisted(dataDir, entry.name, entry.value); err != nil {
for j := i - 1; j >= 0; j-- {
_ = writePersisted(dataDir, values[j].name, old[j])
}
return err
}
}
if err := temp.Close(); err != nil {
return err
}
return os.Rename(temp.Name(), filepath.Join(dataDir, "tls-domain"))
return nil
}
func ConfigureMode(dataDir, mode string) error {
@@ -134,28 +279,7 @@ func ConfigureMode(dataDir, mode string) error {
if mode != "autocert" && mode != "nginx" {
return fmt.Errorf("入口模式仅支持 autocert 或 nginx")
}
if err := os.MkdirAll(dataDir, 0o700); err != nil {
return err
}
temp, err := os.CreateTemp(dataDir, ".tls-mode-*")
if err != nil {
return err
}
defer os.Remove(temp.Name())
defer temp.Close()
if err := temp.Chmod(0o600); err != nil {
return err
}
if _, err := temp.WriteString(mode + "\n"); err != nil {
return err
}
if err := temp.Sync(); err != nil {
return err
}
if err := temp.Close(); err != nil {
return err
}
return os.Rename(temp.Name(), filepath.Join(dataDir, "tls-mode"))
return writePersisted(dataDir, "tls-mode", mode)
}
// Start keeps certificates in the persistent data directory. Issuance occurs
@@ -165,7 +289,8 @@ func Start(handler http.Handler, dataDir string) error {
if err != nil {
return err
}
if config.domain == "" || config.mode == "nginx" {
if config.domain == "" || config.mode == "nginx" || normalizeScheme(config.scheme) == "http" {
// Plain HTTP public entry is terminated by Nginx (or left unset); Go autocert is HTTPS-only.
state.Lock()
state.config = config
state.Unlock()
@@ -188,8 +313,12 @@ func Start(handler http.Handler, dataDir string) error {
httpListener.Close()
return fmt.Errorf("监听 HTTPS 端口 %s: %w", config.httpsAddr, err)
}
publicBase := PublicBaseURL("https", config.domain, config.port)
redirect := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Host != config.domain && r.Host != config.domain+":80" {
eff := EffectivePort("https", config.port)
allowedHost := config.domain
allowedWithPort := fmt.Sprintf("%s:%d", config.domain, eff)
if r.Host != allowedHost && r.Host != allowedWithPort && r.Host != config.domain+":80" {
http.NotFound(w, r)
return
}
@@ -197,7 +326,7 @@ func Start(handler http.Handler, dataDir string) error {
http.Error(w, "Use HTTPS", http.StatusBadRequest)
return
}
http.Redirect(w, r, "https://"+config.domain+r.URL.RequestURI(), http.StatusPermanentRedirect)
http.Redirect(w, r, publicBase+r.URL.RequestURI(), http.StatusPermanentRedirect)
})
httpServer := &http.Server{Handler: manager.HTTPHandler(redirect), ReadHeaderTimeout: 10 * time.Second}
httpsServer := &http.Server{Handler: handler, TLSConfig: manager.TLSConfig(), ReadHeaderTimeout: 10 * time.Second}
@@ -222,7 +351,17 @@ func Status() CertificateStatus {
state.RLock()
config := state.config
state.RUnlock()
status := CertificateStatus{Enabled: config.domain != "" && config.mode == "autocert", Domain: config.domain, Mode: config.mode, DNS: []string{}, HTTPAddr: config.httpAddr, HTTPSAddr: config.httpsAddr, Renewal: config.mode}
scheme := normalizeScheme(config.scheme)
status := CertificateStatus{
Enabled: config.domain != "" && config.mode == "autocert",
Domain: config.domain,
Scheme: scheme,
Port: config.port,
Mode: config.mode,
DNS: []string{},
HTTPAddr: config.httpAddr, HTTPSAddr: config.httpsAddr,
Renewal: config.mode,
}
if config.mode == "nginx" {
listenAddress := os.Getenv("VPN_LISTEN_ADDR")
if listenAddress == "" {
@@ -235,21 +374,38 @@ func Status() CertificateStatus {
if desired, err := configFromEnvironment(config.dataDir); err == nil {
status.ConfiguredDomain = desired.domain
status.ConfiguredMode = desired.mode
status.RestartRequired = desired.domain != config.domain || desired.mode != config.mode
status.ConfiguredScheme = normalizeScheme(desired.scheme)
status.ConfiguredPort = desired.port
status.ConfiguredPublicBase = PublicBaseURL(status.ConfiguredScheme, desired.domain, desired.port)
status.RestartRequired = desired.domain != config.domain || desired.mode != config.mode ||
normalizeScheme(desired.scheme) != scheme || desired.port != config.port
}
if config.mode == "nginx" {
// Certbot owns this certificate. Read only the public certificate and
// never mistake a configured domain for a listening HTTPS gateway.
// Certbot or uploaded PEMs own HTTPS certificates. HTTP needs no leaf.
status.Domain = ""
if config.domain != "" {
readCertificate(filepath.Join("/etc/letsencrypt/live", config.domain, "fullchain.pem"), config.domain, &status)
if status.Valid {
status.Domain = config.domain
domain := config.domain
if domain == "" {
domain = status.ConfiguredDomain
}
if domain != "" {
if scheme == "http" {
status.Domain = domain
} else {
fullchain, _, source := CertificateFiles(domain)
readCertificate(fullchain, domain, &status)
if status.Cached || status.Valid {
status.CertSource = source
}
if status.Valid {
status.Domain = domain
}
}
}
status.PublicBase = PublicBaseURL(scheme, status.Domain, config.port)
return status
}
if !status.Enabled {
status.PublicBase = PublicBaseURL(scheme, status.Domain, config.port)
return status
}
if ips, err := net.LookupIP(config.domain); err == nil {
@@ -261,10 +417,15 @@ func Status() CertificateStatus {
// Parse only the public leaf metadata; never return private key material.
data, err := os.ReadFile(filepath.Join(config.cacheDir, config.domain))
if err != nil {
status.PublicBase = PublicBaseURL(scheme, "", config.port)
return status
}
_, data = pem.Decode(data)
readCertificateBytes(data, config.domain, &status)
if !status.Valid {
status.Domain = ""
}
status.PublicBase = PublicBaseURL(scheme, status.Domain, config.port)
return status
}