移除acme-go
This commit is contained in:
@@ -1,300 +0,0 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/certificate"
|
||||
"github.com/go-acme/lego/v4/challenge/http01"
|
||||
"github.com/go-acme/lego/v4/lego"
|
||||
"github.com/go-acme/lego/v4/registration"
|
||||
)
|
||||
|
||||
// CertResult represents the result of a certificate issuance.
|
||||
type CertResult struct {
|
||||
Domain string
|
||||
CertPath string
|
||||
KeyPath string
|
||||
CertPEM string
|
||||
KeyPEM string
|
||||
IssueDate time.Time
|
||||
ExpiryDate time.Time
|
||||
}
|
||||
|
||||
// CertRequest contains all parameters for a certificate request.
|
||||
type CertRequest struct {
|
||||
Email string
|
||||
Domain string
|
||||
Provider string
|
||||
ChallengeMode string
|
||||
WebrootPath string
|
||||
DNSProvider string
|
||||
DNSCredentials map[string]string
|
||||
EABKid string
|
||||
EABHmacKey string
|
||||
}
|
||||
|
||||
// User implements the acme.User interface for lego.
|
||||
type User struct {
|
||||
Email string
|
||||
Registration *registration.Resource
|
||||
key *ecdsa.PrivateKey
|
||||
}
|
||||
|
||||
func (u *User) GetEmail() string { return u.Email }
|
||||
func (u *User) GetRegistration() *registration.Resource { return u.Registration }
|
||||
func (u *User) GetPrivateKey() crypto.PrivateKey { return u.key }
|
||||
|
||||
// Client wraps the lego ACME client.
|
||||
type Client struct {
|
||||
certDir string
|
||||
staging bool
|
||||
httpPort string
|
||||
webrootDir string
|
||||
}
|
||||
|
||||
// ClientOption configures the Client.
|
||||
type ClientOption func(*Client)
|
||||
|
||||
func WithCertDir(dir string) ClientOption {
|
||||
return func(c *Client) { c.certDir = dir }
|
||||
}
|
||||
|
||||
func WithStaging(staging bool) ClientOption {
|
||||
return func(c *Client) { c.staging = staging }
|
||||
}
|
||||
|
||||
func WithHTTPPort(port string) ClientOption {
|
||||
return func(c *Client) { c.httpPort = port }
|
||||
}
|
||||
|
||||
func WithWebrootDir(dir string) ClientOption {
|
||||
return func(c *Client) { c.webrootDir = dir }
|
||||
}
|
||||
|
||||
// NewClient creates a new ACME client.
|
||||
func NewClient(opts ...ClientOption) *Client {
|
||||
c := &Client{
|
||||
certDir: "/etc/miaomiaowu/certs",
|
||||
staging: false,
|
||||
httpPort: ":80",
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// ObtainCertificate requests a new certificate (backward-compatible HTTP-01 only).
|
||||
func (c *Client) ObtainCertificate(ctx context.Context, email, domain string, useWebroot bool) (*CertResult, error) {
|
||||
mode := "standalone"
|
||||
if useWebroot {
|
||||
mode = "webroot"
|
||||
}
|
||||
return c.ObtainCertificateV2(ctx, CertRequest{
|
||||
Email: email,
|
||||
Domain: domain,
|
||||
Provider: CALetsEncrypt,
|
||||
ChallengeMode: mode,
|
||||
WebrootPath: c.webrootDir,
|
||||
})
|
||||
}
|
||||
|
||||
// ObtainCertificateV2 requests a new certificate with full options support.
|
||||
func (c *Client) ObtainCertificateV2(ctx context.Context, req CertRequest) (*CertResult, error) {
|
||||
if req.Email == "" {
|
||||
return nil, errors.New("email is required")
|
||||
}
|
||||
if req.Domain == "" {
|
||||
return nil, errors.New("domain is required")
|
||||
}
|
||||
|
||||
client, err := c.buildLegoClient(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
obtainReq := certificate.ObtainRequest{
|
||||
Domains: []string{req.Domain},
|
||||
Bundle: true,
|
||||
}
|
||||
|
||||
certificates, err := client.Certificate.Obtain(obtainReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("obtain certificate: %w", err)
|
||||
}
|
||||
|
||||
return c.processCertResult(req.Domain, certificates.Certificate, certificates.PrivateKey)
|
||||
}
|
||||
|
||||
func (c *Client) buildLegoClient(req CertRequest) (*lego.Client, error) {
|
||||
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate private key: %w", err)
|
||||
}
|
||||
|
||||
user := &User{Email: req.Email, key: privateKey}
|
||||
|
||||
config := lego.NewConfig(user)
|
||||
provider := req.Provider
|
||||
if provider == "" {
|
||||
provider = CALetsEncrypt
|
||||
}
|
||||
config.CADirURL = ResolveCADirectoryURL(provider, c.staging)
|
||||
config.Certificate.KeyType = certcrypto.EC256
|
||||
|
||||
client, err := lego.NewClient(config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create lego client: %w", err)
|
||||
}
|
||||
|
||||
switch req.ChallengeMode {
|
||||
case "dns":
|
||||
if err := c.setupDNSChallenge(client, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "webroot":
|
||||
if err := c.setupWebrootChallenge(client, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
p := http01.NewProviderServer("", c.httpPort)
|
||||
if err := client.Challenge.SetHTTP01Provider(p); err != nil {
|
||||
return nil, fmt.Errorf("set http01 provider: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
regOpts := registration.RegisterOptions{TermsOfServiceAgreed: true}
|
||||
if req.EABKid != "" && req.EABHmacKey != "" {
|
||||
reg, err := client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
|
||||
TermsOfServiceAgreed: true,
|
||||
Kid: req.EABKid,
|
||||
HmacEncoded: req.EABHmacKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("register with EAB: %w", err)
|
||||
}
|
||||
user.Registration = reg
|
||||
} else {
|
||||
reg, err := client.Registration.Register(regOpts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("register with ACME: %w", err)
|
||||
}
|
||||
user.Registration = reg
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) setupDNSChallenge(client *lego.Client, req CertRequest) error {
|
||||
if req.DNSProvider == "" {
|
||||
return errors.New("dns_provider is required for DNS-01 challenge")
|
||||
}
|
||||
|
||||
if len(req.DNSCredentials) > 0 {
|
||||
cleanup, err := SetDNSCredentialEnv(req.DNSProvider, req.DNSCredentials)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set DNS credentials: %w", err)
|
||||
}
|
||||
defer cleanup()
|
||||
}
|
||||
|
||||
provider, err := NewDNSProviderByName(req.DNSProvider)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create DNS provider %s: %w", req.DNSProvider, err)
|
||||
}
|
||||
|
||||
if err := client.Challenge.SetDNS01Provider(provider); err != nil {
|
||||
return fmt.Errorf("set DNS-01 provider: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) setupWebrootChallenge(client *lego.Client, req CertRequest) error {
|
||||
webrootDir := req.WebrootPath
|
||||
if webrootDir == "" {
|
||||
webrootDir = c.webrootDir
|
||||
}
|
||||
if webrootDir == "" {
|
||||
return errors.New("webroot_path is required for webroot challenge")
|
||||
}
|
||||
provider, err := NewWebrootProvider(webrootDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create webroot provider: %w", err)
|
||||
}
|
||||
if err := client.Challenge.SetHTTP01Provider(provider); err != nil {
|
||||
return fmt.Errorf("set webroot provider: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) processCertResult(domain string, certPEMBytes, keyPEMBytes []byte) (*CertResult, error) {
|
||||
expiryDate, issueDate, err := parseCertificateDates(certPEMBytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse certificate: %w", err)
|
||||
}
|
||||
|
||||
certPath, keyPath, err := c.saveCertificate(domain, certPEMBytes, keyPEMBytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("save certificate: %w", err)
|
||||
}
|
||||
|
||||
return &CertResult{
|
||||
Domain: domain,
|
||||
CertPath: certPath,
|
||||
KeyPath: keyPath,
|
||||
CertPEM: string(certPEMBytes),
|
||||
KeyPEM: string(keyPEMBytes),
|
||||
IssueDate: issueDate,
|
||||
ExpiryDate: expiryDate,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) saveCertificate(domain string, certPEM, keyPEM []byte) (string, string, error) {
|
||||
domainDir := filepath.Join(c.certDir, domain)
|
||||
if err := os.MkdirAll(domainDir, 0700); err != nil {
|
||||
return "", "", fmt.Errorf("create cert directory: %w", err)
|
||||
}
|
||||
|
||||
certPath := filepath.Join(domainDir, "fullchain.pem")
|
||||
keyPath := filepath.Join(domainDir, "privkey.pem")
|
||||
|
||||
if err := os.WriteFile(certPath, certPEM, 0644); err != nil {
|
||||
return "", "", fmt.Errorf("write certificate: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, keyPEM, 0600); err != nil {
|
||||
return "", "", fmt.Errorf("write private key: %w", err)
|
||||
}
|
||||
|
||||
return certPath, keyPath, nil
|
||||
}
|
||||
|
||||
func parseCertificateDates(certPEM []byte) (expiryDate, issueDate time.Time, err error) {
|
||||
block, _ := pem.Decode(certPEM)
|
||||
if block == nil {
|
||||
return time.Time{}, time.Time{}, errors.New("failed to decode PEM block")
|
||||
}
|
||||
|
||||
cert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("parse certificate: %w", err)
|
||||
}
|
||||
|
||||
return cert.NotAfter, cert.NotBefore, nil
|
||||
}
|
||||
|
||||
// GetCertDir returns the certificate storage directory.
|
||||
func (c *Client) GetCertDir() string {
|
||||
return c.certDir
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// DeployCertFiles writes cert and key PEM to the specified paths.
|
||||
func DeployCertFiles(certPEM, keyPEM, certPath, keyPath string) error {
|
||||
if certPath == "" || keyPath == "" {
|
||||
return fmt.Errorf("deploy paths are required")
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(certPath), 0755); err != nil {
|
||||
return fmt.Errorf("create cert dir: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(keyPath), 0755); err != nil {
|
||||
return fmt.Errorf("create key dir: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(certPath, []byte(certPEM), 0644); err != nil {
|
||||
return fmt.Errorf("write cert: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, []byte(keyPEM), 0600); err != nil {
|
||||
return fmt.Errorf("write key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReloadNginx sends a reload signal to nginx.
|
||||
func ReloadNginx() error {
|
||||
cmd := exec.Command("nginx", "-s", "reload")
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("nginx reload: %s: %w", string(output), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RestartXray restarts the xray service via systemctl.
|
||||
func RestartXray() error {
|
||||
cmd := exec.Command("systemctl", "restart", "xray")
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("xray restart: %s: %w", string(output), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Deploy writes cert files and optionally reloads services.
|
||||
func Deploy(certPEM, keyPEM, certPath, keyPath, reloadTarget string) error {
|
||||
if err := DeployCertFiles(certPEM, keyPEM, certPath, keyPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch reloadTarget {
|
||||
case "nginx":
|
||||
return ReloadNginx()
|
||||
case "xray":
|
||||
return RestartXray()
|
||||
case "both":
|
||||
if err := ReloadNginx(); err != nil {
|
||||
return err
|
||||
}
|
||||
return RestartXray()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/providers/dns/alidns"
|
||||
"github.com/go-acme/lego/v4/providers/dns/cloudflare"
|
||||
"github.com/go-acme/lego/v4/providers/dns/dnspod"
|
||||
"github.com/go-acme/lego/v4/providers/dns/godaddy"
|
||||
"github.com/go-acme/lego/v4/providers/dns/namesilo"
|
||||
"github.com/go-acme/lego/v4/providers/dns/tencentcloud"
|
||||
)
|
||||
|
||||
var DNSProviderEnvKeys = map[string][]string{
|
||||
"cloudflare": {"CF_API_EMAIL", "CF_API_KEY", "CF_DNS_API_TOKEN"},
|
||||
"alidns": {"ALICLOUD_ACCESS_KEY", "ALICLOUD_SECRET_KEY"},
|
||||
"tencentcloud": {"TENCENTCLOUD_SECRET_ID", "TENCENTCLOUD_SECRET_KEY"},
|
||||
"dnspod": {"DNSPOD_API_KEY"},
|
||||
"namesilo": {"NAMESILO_API_KEY"},
|
||||
"godaddy": {"GODADDY_API_KEY", "GODADDY_API_SECRET"},
|
||||
}
|
||||
|
||||
func NewDNSProviderByName(name string) (challenge.Provider, error) {
|
||||
switch name {
|
||||
case "cloudflare":
|
||||
return cloudflare.NewDNSProvider()
|
||||
case "alidns":
|
||||
return alidns.NewDNSProvider()
|
||||
case "tencentcloud":
|
||||
return tencentcloud.NewDNSProvider()
|
||||
case "dnspod":
|
||||
return dnspod.NewDNSProvider()
|
||||
case "namesilo":
|
||||
return namesilo.NewDNSProvider()
|
||||
case "godaddy":
|
||||
return godaddy.NewDNSProvider()
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported DNS provider: %s", name)
|
||||
}
|
||||
}
|
||||
|
||||
func SetDNSCredentialEnv(providerType string, credentials map[string]string) (cleanup func(), err error) {
|
||||
keys, ok := DNSProviderEnvKeys[providerType]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unsupported DNS provider type: %s", providerType)
|
||||
}
|
||||
|
||||
var setKeys []string
|
||||
for _, key := range keys {
|
||||
if val, exists := credentials[key]; exists && val != "" {
|
||||
os.Setenv(key, val)
|
||||
setKeys = append(setKeys, key)
|
||||
}
|
||||
}
|
||||
|
||||
if len(setKeys) == 0 {
|
||||
return nil, fmt.Errorf("no valid credentials provided for DNS provider %s", providerType)
|
||||
}
|
||||
|
||||
cleanup = func() {
|
||||
for _, key := range setKeys {
|
||||
os.Unsetenv(key)
|
||||
}
|
||||
}
|
||||
return cleanup, nil
|
||||
}
|
||||
|
||||
const (
|
||||
CALetsEncrypt = "letsencrypt"
|
||||
CALetsEncryptStaging = "letsencrypt-staging"
|
||||
CAZeroSSL = "zerossl"
|
||||
CABuypass = "buypass"
|
||||
CABuypassTest = "buypass-test"
|
||||
)
|
||||
|
||||
var CADirectoryURLs = map[string]string{
|
||||
CALetsEncrypt: "https://acme-v02.api.letsencrypt.org/directory",
|
||||
CALetsEncryptStaging: "https://acme-staging-v02.api.letsencrypt.org/directory",
|
||||
CAZeroSSL: "https://acme.zerossl.com/v2/DV90",
|
||||
CABuypass: "https://api.buypass.com/acme/directory",
|
||||
CABuypassTest: "https://api.test4.buypass.no/acme/directory",
|
||||
}
|
||||
|
||||
func ResolveCADirectoryURL(provider string, staging bool) string {
|
||||
if staging {
|
||||
if url, ok := CADirectoryURLs[provider+"-staging"]; ok {
|
||||
return url
|
||||
}
|
||||
if url, ok := CADirectoryURLs[provider+"-test"]; ok {
|
||||
return url
|
||||
}
|
||||
return CADirectoryURLs[CALetsEncryptStaging]
|
||||
}
|
||||
if url, ok := CADirectoryURLs[provider]; ok {
|
||||
return url
|
||||
}
|
||||
return CADirectoryURLs[CALetsEncrypt]
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/go-acme/lego/v4/challenge/http01"
|
||||
)
|
||||
|
||||
// WebrootProvider implements the HTTP-01 challenge using a webroot directory.
|
||||
type WebrootProvider struct {
|
||||
path string
|
||||
}
|
||||
|
||||
// NewWebrootProvider creates a new webroot provider.
|
||||
func NewWebrootProvider(path string) (*WebrootProvider, error) {
|
||||
if path == "" {
|
||||
return nil, fmt.Errorf("webroot path is required")
|
||||
}
|
||||
|
||||
// Ensure the webroot directory exists
|
||||
challengeDir := filepath.Join(path, http01.ChallengePath(""))
|
||||
if err := os.MkdirAll(challengeDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("create challenge directory: %w", err)
|
||||
}
|
||||
|
||||
return &WebrootProvider{path: path}, nil
|
||||
}
|
||||
|
||||
// Present writes the challenge token to the webroot directory.
|
||||
func (w *WebrootProvider) Present(domain, token, keyAuth string) error {
|
||||
challengePath := filepath.Join(w.path, http01.ChallengePath(token))
|
||||
|
||||
// Ensure parent directory exists
|
||||
if err := os.MkdirAll(filepath.Dir(challengePath), 0755); err != nil {
|
||||
return fmt.Errorf("create challenge directory: %w", err)
|
||||
}
|
||||
|
||||
// Write the key authorization to the challenge file
|
||||
if err := os.WriteFile(challengePath, []byte(keyAuth), 0644); err != nil {
|
||||
return fmt.Errorf("write challenge file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanUp removes the challenge token file.
|
||||
func (w *WebrootProvider) CleanUp(domain, token, keyAuth string) error {
|
||||
challengePath := filepath.Join(w.path, http01.ChallengePath(token))
|
||||
if err := os.Remove(challengePath); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("remove challenge file: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -10,12 +10,13 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mmw-agent/internal/acme"
|
||||
"mmw-agent/internal/collector"
|
||||
"mmw-agent/internal/config"
|
||||
|
||||
@@ -919,26 +920,10 @@ func (e *AuthError) IsTokenInvalid() bool {
|
||||
|
||||
// WebSocket message types
|
||||
const (
|
||||
WSMsgTypeCertRequest = "cert_request"
|
||||
WSMsgTypeCertUpdate = "cert_update"
|
||||
WSMsgTypeCertDeploy = "cert_deploy"
|
||||
WSMsgTypeTokenUpdate = "token_update"
|
||||
)
|
||||
|
||||
// WSCertRequestPayload represents a certificate request from master
|
||||
type WSCertRequestPayload struct {
|
||||
CertID int64 `json:"cert_id"`
|
||||
Domain string `json:"domain"`
|
||||
Email string `json:"email"`
|
||||
Provider string `json:"provider"`
|
||||
ChallengeMode string `json:"challenge_mode"`
|
||||
WebrootPath string `json:"webroot_path,omitempty"`
|
||||
DNSProvider string `json:"dns_provider,omitempty"`
|
||||
DNSCredentials string `json:"dns_credentials,omitempty"` // JSON string
|
||||
EABKid string `json:"eab_kid,omitempty"`
|
||||
EABHmacKey string `json:"eab_hmac_key,omitempty"`
|
||||
}
|
||||
|
||||
// WSCertDeployPayload represents a certificate deploy command from master
|
||||
type WSCertDeployPayload struct {
|
||||
Domain string `json:"domain"`
|
||||
@@ -949,20 +934,6 @@ type WSCertDeployPayload struct {
|
||||
Reload string `json:"reload"`
|
||||
}
|
||||
|
||||
// WSCertUpdatePayload represents a certificate update response to master
|
||||
type WSCertUpdatePayload struct {
|
||||
CertID int64 `json:"cert_id"`
|
||||
Domain string `json:"domain"`
|
||||
Success bool `json:"success"`
|
||||
CertPath string `json:"cert_path,omitempty"`
|
||||
KeyPath string `json:"key_path,omitempty"`
|
||||
CertPEM string `json:"cert_pem,omitempty"`
|
||||
KeyPEM string `json:"key_pem,omitempty"`
|
||||
IssueDate time.Time `json:"issue_date,omitempty"`
|
||||
ExpiryDate time.Time `json:"expiry_date,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// WSTokenUpdatePayload represents a token update from master
|
||||
type WSTokenUpdatePayload struct {
|
||||
ServerToken string `json:"server_token"`
|
||||
@@ -982,13 +953,6 @@ func (c *Client) handleMessage(conn *websocket.Conn, message []byte) {
|
||||
}
|
||||
|
||||
switch msg.Type {
|
||||
case WSMsgTypeCertRequest:
|
||||
var payload WSCertRequestPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
log.Printf("[Agent] Failed to parse cert_request payload: %v", err)
|
||||
return
|
||||
}
|
||||
go c.handleCertRequest(conn, payload)
|
||||
case WSMsgTypeCertDeploy:
|
||||
var payload WSCertDeployPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
@@ -1008,98 +972,55 @@ func (c *Client) handleMessage(conn *websocket.Conn, message []byte) {
|
||||
}
|
||||
}
|
||||
|
||||
// handleCertRequest processes a certificate request from master
|
||||
func (c *Client) handleCertRequest(conn *websocket.Conn, req WSCertRequestPayload) {
|
||||
log.Printf("[Agent] Received certificate request for domain: %s", req.Domain)
|
||||
|
||||
result := c.requestCertificate(req)
|
||||
|
||||
// Send result back to master
|
||||
payload, _ := json.Marshal(result)
|
||||
msg := map[string]interface{}{
|
||||
"type": WSMsgTypeCertUpdate,
|
||||
"payload": json.RawMessage(payload),
|
||||
}
|
||||
|
||||
c.wsMu.Lock()
|
||||
err := conn.WriteJSON(msg)
|
||||
c.wsMu.Unlock()
|
||||
|
||||
if err != nil {
|
||||
log.Printf("[Agent] Failed to send cert_update: %v", err)
|
||||
} else {
|
||||
log.Printf("[Agent] Sent cert_update for domain %s, success=%v", req.Domain, result.Success)
|
||||
}
|
||||
}
|
||||
|
||||
// requestCertificate performs the actual certificate request using ACME
|
||||
func (c *Client) requestCertificate(req WSCertRequestPayload) WSCertUpdatePayload {
|
||||
result := WSCertUpdatePayload{
|
||||
CertID: req.CertID,
|
||||
Domain: req.Domain,
|
||||
}
|
||||
|
||||
opts := []acme.ClientOption{}
|
||||
if req.ChallengeMode == "webroot" && req.WebrootPath != "" {
|
||||
opts = append(opts, acme.WithWebrootDir(req.WebrootPath))
|
||||
}
|
||||
|
||||
acmeClient := acme.NewClient(opts...)
|
||||
|
||||
// Build V2 cert request
|
||||
certReq := acme.CertRequest{
|
||||
Email: req.Email,
|
||||
Domain: req.Domain,
|
||||
Provider: req.Provider,
|
||||
ChallengeMode: req.ChallengeMode,
|
||||
WebrootPath: req.WebrootPath,
|
||||
DNSProvider: req.DNSProvider,
|
||||
EABKid: req.EABKid,
|
||||
EABHmacKey: req.EABHmacKey,
|
||||
}
|
||||
|
||||
// Parse DNS credentials from JSON string
|
||||
if req.DNSCredentials != "" {
|
||||
var creds map[string]string
|
||||
if err := json.Unmarshal([]byte(req.DNSCredentials), &creds); err == nil {
|
||||
certReq.DNSCredentials = creds
|
||||
}
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
certResult, err := acmeClient.ObtainCertificateV2(ctx, certReq)
|
||||
if err != nil {
|
||||
result.Success = false
|
||||
result.Error = err.Error()
|
||||
log.Printf("[Agent] Certificate request failed for %s: %v", req.Domain, err)
|
||||
return result
|
||||
}
|
||||
|
||||
result.Success = true
|
||||
result.CertPath = certResult.CertPath
|
||||
result.KeyPath = certResult.KeyPath
|
||||
result.CertPEM = certResult.CertPEM
|
||||
result.KeyPEM = certResult.KeyPEM
|
||||
result.IssueDate = certResult.IssueDate
|
||||
result.ExpiryDate = certResult.ExpiryDate
|
||||
|
||||
log.Printf("[Agent] Certificate obtained for %s, expires: %s", req.Domain, certResult.ExpiryDate)
|
||||
return result
|
||||
}
|
||||
|
||||
// handleCertDeploy deploys a certificate received from master
|
||||
func (c *Client) handleCertDeploy(payload WSCertDeployPayload) {
|
||||
log.Printf("[Agent] Received cert_deploy for domain: %s, target: %s", payload.Domain, payload.Reload)
|
||||
|
||||
if err := acme.Deploy(payload.CertPEM, payload.KeyPEM, payload.CertPath, payload.KeyPath, payload.Reload); err != nil {
|
||||
if err := deployCert(payload.CertPEM, payload.KeyPEM, payload.CertPath, payload.KeyPath, payload.Reload); err != nil {
|
||||
log.Printf("[Agent] cert_deploy failed for %s: %v", payload.Domain, err)
|
||||
} else {
|
||||
log.Printf("[Agent] cert_deploy succeeded for %s", payload.Domain)
|
||||
}
|
||||
}
|
||||
|
||||
func deployCert(certPEM, keyPEM, certPath, keyPath, reloadTarget string) error {
|
||||
if certPath == "" || keyPath == "" {
|
||||
return fmt.Errorf("deploy paths are required")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(certPath), 0755); err != nil {
|
||||
return fmt.Errorf("create cert dir: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(keyPath), 0755); err != nil {
|
||||
return fmt.Errorf("create key dir: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(certPath, []byte(certPEM), 0644); err != nil {
|
||||
return fmt.Errorf("write cert: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, []byte(keyPEM), 0600); err != nil {
|
||||
return fmt.Errorf("write key: %w", err)
|
||||
}
|
||||
|
||||
switch reloadTarget {
|
||||
case "nginx":
|
||||
return runCmd("nginx", "-s", "reload")
|
||||
case "xray":
|
||||
return runCmd("systemctl", "restart", "xray")
|
||||
case "both":
|
||||
if err := runCmd("nginx", "-s", "reload"); err != nil {
|
||||
return err
|
||||
}
|
||||
return runCmd("systemctl", "restart", "xray")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runCmd(name string, args ...string) error {
|
||||
if output, err := exec.Command(name, args...).CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("%s: %s: %w", name, string(output), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleTokenUpdate processes a token update from master
|
||||
func (c *Client) handleTokenUpdate(payload WSTokenUpdatePayload) {
|
||||
log.Printf("[Agent] Received token update from master, new token expires at %s", payload.ExpiresAt.Format(time.RFC3339))
|
||||
|
||||
@@ -2415,3 +2415,85 @@ func (h *ManageHandler) addAPIRoutingRule(config map[string]interface{}) {
|
||||
}
|
||||
routing["rules"] = append([]interface{}{apiRule}, rules...)
|
||||
}
|
||||
|
||||
// ================== Certificate Deploy ==================
|
||||
|
||||
// CertDeployRequest represents a certificate deploy request from master
|
||||
type CertDeployRequest struct {
|
||||
Domain string `json:"domain"`
|
||||
CertPEM string `json:"cert_pem"`
|
||||
KeyPEM string `json:"key_pem"`
|
||||
CertPath string `json:"cert_path"`
|
||||
KeyPath string `json:"key_path"`
|
||||
Reload string `json:"reload"` // nginx, xray, both, none
|
||||
}
|
||||
|
||||
// HandleCertDeploy handles POST /api/child/cert/deploy
|
||||
func (h *ManageHandler) HandleCertDeploy(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
if !h.authenticate(r) {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
var req CertDeployRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if req.CertPEM == "" || req.KeyPEM == "" || req.CertPath == "" || req.KeyPath == "" {
|
||||
writeError(w, http.StatusBadRequest, "cert_pem, key_pem, cert_path, key_path are required")
|
||||
return
|
||||
}
|
||||
|
||||
if err := deployCertFiles(req.CertPEM, req.KeyPEM, req.CertPath, req.KeyPath, req.Reload); err != nil {
|
||||
log.Printf("[CertDeploy] Failed to deploy cert for %s: %v", req.Domain, err)
|
||||
writeError(w, http.StatusInternalServerError, fmt.Sprintf("deploy failed: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[CertDeploy] Successfully deployed cert for %s to %s", req.Domain, req.CertPath)
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"success": true,
|
||||
"message": fmt.Sprintf("certificate for %s deployed", req.Domain),
|
||||
})
|
||||
}
|
||||
|
||||
func deployCertFiles(certPEM, keyPEM, certPath, keyPath, reloadTarget string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(certPath), 0755); err != nil {
|
||||
return fmt.Errorf("create cert dir: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(keyPath), 0755); err != nil {
|
||||
return fmt.Errorf("create key dir: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(certPath, []byte(certPEM), 0644); err != nil {
|
||||
return fmt.Errorf("write cert: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, []byte(keyPEM), 0600); err != nil {
|
||||
return fmt.Errorf("write key: %w", err)
|
||||
}
|
||||
|
||||
switch reloadTarget {
|
||||
case "nginx":
|
||||
return runCommand("nginx", "-s", "reload")
|
||||
case "xray":
|
||||
return runCommand("systemctl", "restart", "xray")
|
||||
case "both":
|
||||
if err := runCommand("nginx", "-s", "reload"); err != nil {
|
||||
return err
|
||||
}
|
||||
return runCommand("systemctl", "restart", "xray")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runCommand(name string, args ...string) error {
|
||||
if output, err := exec.Command(name, args...).CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("%s: %s: %w", name, string(output), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user