init
This commit is contained in:
@@ -32,6 +32,19 @@ type CertResult struct {
|
||||
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
|
||||
@@ -54,22 +67,18 @@ type Client struct {
|
||||
// ClientOption configures the Client.
|
||||
type ClientOption func(*Client)
|
||||
|
||||
// WithCertDir sets the certificate storage directory.
|
||||
func WithCertDir(dir string) ClientOption {
|
||||
return func(c *Client) { c.certDir = dir }
|
||||
}
|
||||
|
||||
// WithStaging enables the Let's Encrypt staging environment.
|
||||
func WithStaging(staging bool) ClientOption {
|
||||
return func(c *Client) { c.staging = staging }
|
||||
}
|
||||
|
||||
// WithHTTPPort sets the port for HTTP-01 challenge (default: ":80").
|
||||
func WithHTTPPort(port string) ClientOption {
|
||||
return func(c *Client) { c.httpPort = port }
|
||||
}
|
||||
|
||||
// WithWebrootDir sets the webroot directory for webroot challenge mode.
|
||||
func WithWebrootDir(dir string) ClientOption {
|
||||
return func(c *Client) { c.webrootDir = dir }
|
||||
}
|
||||
@@ -87,32 +96,62 @@ func NewClient(opts ...ClientOption) *Client {
|
||||
return c
|
||||
}
|
||||
|
||||
// ObtainCertificate requests a new certificate for the given domain.
|
||||
// ObtainCertificate requests a new certificate (backward-compatible HTTP-01 only).
|
||||
func (c *Client) ObtainCertificate(ctx context.Context, email, domain string, useWebroot bool) (*CertResult, error) {
|
||||
if email == "" {
|
||||
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 domain == "" {
|
||||
if req.Domain == "" {
|
||||
return nil, errors.New("domain is required")
|
||||
}
|
||||
|
||||
// Generate a new private key for the user
|
||||
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: email,
|
||||
key: privateKey,
|
||||
}
|
||||
user := &User{Email: req.Email, key: privateKey}
|
||||
|
||||
config := lego.NewConfig(user)
|
||||
if c.staging {
|
||||
config.CADirURL = lego.LEDirectoryStaging
|
||||
} else {
|
||||
config.CADirURL = lego.LEDirectoryProduction
|
||||
provider := req.Provider
|
||||
if provider == "" {
|
||||
provider = CALetsEncrypt
|
||||
}
|
||||
config.CADirURL = ResolveCADirectoryURL(provider, c.staging)
|
||||
config.Certificate.KeyType = certcrypto.EC256
|
||||
|
||||
client, err := lego.NewClient(config)
|
||||
@@ -120,52 +159,93 @@ func (c *Client) ObtainCertificate(ctx context.Context, email, domain string, us
|
||||
return nil, fmt.Errorf("create lego client: %w", err)
|
||||
}
|
||||
|
||||
// Set up HTTP-01 challenge provider
|
||||
if useWebroot && c.webrootDir != "" {
|
||||
// Webroot mode: write challenge files to the specified directory
|
||||
provider, err := NewWebrootProvider(c.webrootDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create webroot provider: %w", err)
|
||||
switch req.ChallengeMode {
|
||||
case "dns":
|
||||
if err := c.setupDNSChallenge(client, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := client.Challenge.SetHTTP01Provider(provider); err != nil {
|
||||
return nil, fmt.Errorf("set webroot provider: %w", err)
|
||||
case "webroot":
|
||||
if err := c.setupWebrootChallenge(client, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// Standalone mode: lego starts its own HTTP server
|
||||
provider := http01.NewProviderServer("", c.httpPort)
|
||||
if err := client.Challenge.SetHTTP01Provider(provider); err != nil {
|
||||
default:
|
||||
p := http01.NewProviderServer("", c.httpPort)
|
||||
if err := client.Challenge.SetHTTP01Provider(p); err != nil {
|
||||
return nil, fmt.Errorf("set http01 provider: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Register the user
|
||||
reg, err := client.Registration.Register(registration.RegisterOptions{
|
||||
TermsOfServiceAgreed: true,
|
||||
})
|
||||
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 nil, fmt.Errorf("register with ACME: %w", err)
|
||||
}
|
||||
user.Registration = reg
|
||||
|
||||
// Request the certificate
|
||||
request := certificate.ObtainRequest{
|
||||
Domains: []string{domain},
|
||||
Bundle: true,
|
||||
return fmt.Errorf("create DNS provider %s: %w", req.DNSProvider, err)
|
||||
}
|
||||
|
||||
certificates, err := client.Certificate.Obtain(request)
|
||||
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 nil, fmt.Errorf("obtain certificate: %w", err)
|
||||
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
|
||||
}
|
||||
|
||||
// Parse the certificate to get expiry date
|
||||
expiryDate, issueDate, err := parseCertificateDates(certificates.Certificate)
|
||||
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)
|
||||
}
|
||||
|
||||
// Save the certificate to disk
|
||||
certPath, keyPath, err := c.saveCertificate(domain, certificates.Certificate, certificates.PrivateKey)
|
||||
certPath, keyPath, err := c.saveCertificate(domain, certPEMBytes, keyPEMBytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("save certificate: %w", err)
|
||||
}
|
||||
@@ -174,15 +254,14 @@ func (c *Client) ObtainCertificate(ctx context.Context, email, domain string, us
|
||||
Domain: domain,
|
||||
CertPath: certPath,
|
||||
KeyPath: keyPath,
|
||||
CertPEM: string(certificates.Certificate),
|
||||
KeyPEM: string(certificates.PrivateKey),
|
||||
CertPEM: string(certPEMBytes),
|
||||
KeyPEM: string(keyPEMBytes),
|
||||
IssueDate: issueDate,
|
||||
ExpiryDate: expiryDate,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) saveCertificate(domain string, certPEM, keyPEM []byte) (string, string, error) {
|
||||
// Ensure directory exists
|
||||
domainDir := filepath.Join(c.certDir, domain)
|
||||
if err := os.MkdirAll(domainDir, 0700); err != nil {
|
||||
return "", "", fmt.Errorf("create cert directory: %w", err)
|
||||
@@ -191,12 +270,9 @@ func (c *Client) saveCertificate(domain string, certPEM, keyPEM []byte) (string,
|
||||
certPath := filepath.Join(domainDir, "fullchain.pem")
|
||||
keyPath := filepath.Join(domainDir, "privkey.pem")
|
||||
|
||||
// Write certificate
|
||||
if err := os.WriteFile(certPath, certPEM, 0644); err != nil {
|
||||
return "", "", fmt.Errorf("write certificate: %w", err)
|
||||
}
|
||||
|
||||
// Write private key with restrictive permissions
|
||||
if err := os.WriteFile(keyPath, keyPEM, 0600); err != nil {
|
||||
return "", "", fmt.Errorf("write private key: %w", err)
|
||||
}
|
||||
|
||||
68
internal/acme/deployer.go
Normal file
68
internal/acme/deployer.go
Normal file
@@ -0,0 +1,68 @@
|
||||
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
|
||||
}
|
||||
100
internal/acme/dns_providers.go
Normal file
100
internal/acme/dns_providers.go
Normal file
@@ -0,0 +1,100 @@
|
||||
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]
|
||||
}
|
||||
@@ -71,6 +71,31 @@ func NewClient(cfg *config.Config) *Client {
|
||||
}
|
||||
}
|
||||
|
||||
// wsHeaders returns HTTP headers for WebSocket handshake
|
||||
func (c *Client) wsHeaders() http.Header {
|
||||
h := http.Header{}
|
||||
h.Set("User-Agent", config.AgentUserAgent)
|
||||
return h
|
||||
}
|
||||
|
||||
// newRequest creates an HTTP request with standard headers (Content-Type, Authorization, User-Agent)
|
||||
func (c *Client) newRequest(ctx context.Context, method, urlStr string, body []byte) (*http.Request, error) {
|
||||
var req *http.Request
|
||||
var err error
|
||||
if body != nil {
|
||||
req, err = http.NewRequestWithContext(ctx, method, urlStr, bytes.NewReader(body))
|
||||
} else {
|
||||
req, err = http.NewRequestWithContext(ctx, method, urlStr, nil)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.config.Token)
|
||||
req.Header.Set("User-Agent", config.AgentUserAgent)
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// Start starts the agent client with automatic mode selection
|
||||
func (c *Client) Start(ctx context.Context) {
|
||||
log.Printf("[Agent] Starting in %s mode", c.config.ConnectionMode)
|
||||
@@ -234,7 +259,7 @@ func (c *Client) connectAndRun(ctx context.Context) error {
|
||||
HandshakeTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
conn, _, err := dialer.DialContext(ctx, u.String(), nil)
|
||||
conn, _, err := dialer.DialContext(ctx, u.String(), c.wsHeaders())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -529,7 +554,7 @@ func (c *Client) tryWebSocketOnce(ctx context.Context) error {
|
||||
HandshakeTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
conn, _, err := dialer.DialContext(ctx, u.String(), nil)
|
||||
conn, _, err := dialer.DialContext(ctx, u.String(), c.wsHeaders())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -545,12 +570,10 @@ func (c *Client) tryHTTPOnce(ctx context.Context) bool {
|
||||
}
|
||||
u.Path = "/api/remote/heartbeat"
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader([]byte("{}")))
|
||||
req, err := c.newRequest(ctx, http.MethodPost, u.String(), []byte("{}"))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.config.Token)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -636,12 +659,10 @@ func (c *Client) sendTrafficHTTP(ctx context.Context) error {
|
||||
}
|
||||
u.Path = "/api/remote/traffic"
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(payload))
|
||||
req, err := c.newRequest(ctx, http.MethodPost, u.String(), payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.config.Token)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -674,12 +695,10 @@ func (c *Client) sendSpeedHTTP(ctx context.Context) error {
|
||||
}
|
||||
u.Path = "/api/remote/speed"
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(payload))
|
||||
req, err := c.newRequest(ctx, http.MethodPost, u.String(), payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.config.Token)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -711,12 +730,10 @@ func (c *Client) sendHeartbeatHTTP(ctx context.Context) error {
|
||||
}
|
||||
u.Path = "/api/remote/heartbeat"
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(payload))
|
||||
req, err := c.newRequest(ctx, http.MethodPost, u.String(), payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.config.Token)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -904,17 +921,32 @@ func (e *AuthError) IsTokenInvalid() bool {
|
||||
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"`
|
||||
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"`
|
||||
CertPEM string `json:"cert_pem"`
|
||||
KeyPEM string `json:"key_pem"`
|
||||
CertPath string `json:"cert_path"`
|
||||
KeyPath string `json:"key_path"`
|
||||
Reload string `json:"reload"`
|
||||
}
|
||||
|
||||
// WSCertUpdatePayload represents a certificate update response to master
|
||||
@@ -957,6 +989,13 @@ func (c *Client) handleMessage(conn *websocket.Conn, message []byte) {
|
||||
return
|
||||
}
|
||||
go c.handleCertRequest(conn, payload)
|
||||
case WSMsgTypeCertDeploy:
|
||||
var payload WSCertDeployPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
log.Printf("[Agent] Failed to parse cert_deploy payload: %v", err)
|
||||
return
|
||||
}
|
||||
go c.handleCertDeploy(payload)
|
||||
case WSMsgTypeTokenUpdate:
|
||||
var payload WSTokenUpdatePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
@@ -1000,7 +1039,6 @@ func (c *Client) requestCertificate(req WSCertRequestPayload) WSCertUpdatePayloa
|
||||
Domain: req.Domain,
|
||||
}
|
||||
|
||||
// Create ACME client with appropriate options
|
||||
opts := []acme.ClientOption{}
|
||||
if req.ChallengeMode == "webroot" && req.WebrootPath != "" {
|
||||
opts = append(opts, acme.WithWebrootDir(req.WebrootPath))
|
||||
@@ -1008,14 +1046,30 @@ func (c *Client) requestCertificate(req WSCertRequestPayload) WSCertUpdatePayloa
|
||||
|
||||
acmeClient := acme.NewClient(opts...)
|
||||
|
||||
// Determine if we should use webroot mode
|
||||
useWebroot := req.ChallengeMode == "webroot" && req.WebrootPath != ""
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// Request the certificate
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
certResult, err := acmeClient.ObtainCertificate(ctx, req.Email, req.Domain, useWebroot)
|
||||
certResult, err := acmeClient.ObtainCertificateV2(ctx, certReq)
|
||||
if err != nil {
|
||||
result.Success = false
|
||||
result.Error = err.Error()
|
||||
@@ -1035,6 +1089,17 @@ func (c *Client) requestCertificate(req WSCertRequestPayload) WSCertUpdatePayloa
|
||||
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 {
|
||||
log.Printf("[Agent] cert_deploy failed for %s: %v", payload.Domain, err)
|
||||
} else {
|
||||
log.Printf("[Agent] cert_deploy succeeded for %s", payload.Domain)
|
||||
}
|
||||
}
|
||||
|
||||
// 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))
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const AgentUserAgent = "miaomiaowux/0.1"
|
||||
|
||||
// Config holds the agent configuration
|
||||
type Config struct {
|
||||
MasterURL string `yaml:"master_url"`
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"mmw-agent/internal/agent"
|
||||
"mmw-agent/internal/config"
|
||||
)
|
||||
|
||||
// APIHandler handles API requests from the master server (for pull mode)
|
||||
@@ -86,8 +87,12 @@ func (h *APIHandler) ServeSpeedHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// authenticate checks if the request is authorized
|
||||
// authenticate checks if the request is authorized (token + User-Agent)
|
||||
func (h *APIHandler) authenticate(r *http.Request) bool {
|
||||
if r.Header.Get("User-Agent") != config.AgentUserAgent {
|
||||
return false
|
||||
}
|
||||
|
||||
if h.configToken == "" {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mmw-agent/internal/config"
|
||||
"mmw-agent/internal/xrpc"
|
||||
|
||||
"github.com/xtls/xray-core/app/proxyman/command"
|
||||
@@ -31,8 +32,12 @@ func NewManageHandler(configToken string) *ManageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// authenticate checks if the request is authorized
|
||||
// authenticate checks if the request is authorized (token + User-Agent)
|
||||
func (h *ManageHandler) authenticate(r *http.Request) bool {
|
||||
if r.Header.Get("User-Agent") != config.AgentUserAgent {
|
||||
return false
|
||||
}
|
||||
|
||||
if h.configToken == "" {
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user