Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

Add acme and letencrypt.

Jacka8e7ac118e01
diff --git a/core/cmd/acme/Makefile b/core/cmd/acme/Makefile
new file mode 100644
index 00000000..0c48991b
--- /dev/null
+++ b/core/cmd/acme/Makefile
@@ -0,0 +1,38 @@
+# Makefile for ACME CLI tool
+
+# Go parameters
+GOCMD=go
+GOBUILD=$(GOCMD) build
+GOCLEAN=$(GOCMD) clean
+BINARY_NAME=acme-cli
+
+# Default target is to build the binary
+all: build
+
+# Build the binary
+build:
+ $(GOBUILD) -o $(BINARY_NAME) -v
+
+# Clean build artifacts
+clean:
+ $(GOCLEAN)
+ rm -f $(BINARY_NAME)
+
+# Cross-platform builds
+build-linux:
+ GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(BINARY_NAME)-linux-amd64 -v
+
+build-windows:
+ GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(BINARY_NAME)-windows-amd64.exe -v
+
+build-mac:
+ GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(BINARY_NAME)-darwin-amd64 -v
+
+# Build for all platforms
+build-all: build-linux build-windows build-mac
+
+# Install to GOPATH/bin
+install:
+ $(GOBUILD) -o $(GOPATH)/bin/$(BINARY_NAME) -v
+
+.PHONY: all build clean build-linux build-windows build-mac build-all install
\ No newline at end of file
diff --git a/core/cmd/acme/main.go b/core/cmd/acme/main.go
new file mode 100644
index 00000000..0e726154
--- /dev/null
+++ b/core/cmd/acme/main.go
@@ -0,0 +1,12 @@
+package main
+
+import (
+ "billionmail-core/internal/service/acme"
+ "os"
+)
+
+func main() {
+ // Run ACME CLI with command line arguments
+ exitCode := acme.RunCLI(os.Args[1:])
+ os.Exit(exitCode)
+}
diff --git a/core/internal/service/acme/acme.go b/core/internal/service/acme/acme.go
new file mode 100644
index 00000000..302406c5
--- /dev/null
+++ b/core/internal/service/acme/acme.go
@@ -0,0 +1,552 @@
+package acme
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "time"
+
+ srcLog "log"
+
+ "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/log"
+ "github.com/go-acme/lego/v4/providers/dns/alidns"
+ "github.com/go-acme/lego/v4/providers/dns/azuredns"
+ "github.com/go-acme/lego/v4/providers/dns/cloudflare"
+ "github.com/go-acme/lego/v4/providers/dns/cloudxns"
+ "github.com/go-acme/lego/v4/providers/dns/godaddy"
+ "github.com/go-acme/lego/v4/providers/dns/tencentcloud"
+ "github.com/go-acme/lego/v4/registration"
+)
+
+type MyUser struct {
+ Email string
+ Registration *registration.Resource
+ key crypto.PrivateKey
+}
+
+func (u *MyUser) GetEmail() string {
+ return u.Email
+}
+func (u MyUser) GetRegistration() *registration.Resource {
+ return u.Registration
+}
+func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
+ return u.key
+}
+
+/**
+ * @description: Get user information
+ * @param {string} email Email address
+ * @return {*MyUser} User information
+ */
+func GetMyUser(ctx context.Context, email string) (*MyUser, error) {
+ // Generate private key
+ privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ return nil, errors.New(public.LangCtx(ctx, "Failed to generate user private key: {}", err.Error()))
+ }
+ // Initialize user
+ myUser := MyUser{
+ Email: email,
+ key: privateKey,
+ }
+ return &myUser, nil
+}
+
+/**
+ * @description: Get client configuration
+ * @param {*MyUser} myUser User information
+ * @return {*lego.Config} Configuration information
+ */
+func GetConfig(myUser *MyUser) *lego.Config {
+ // Initialize configuration
+ config := lego.NewConfig(myUser)
+
+ // Set CA directory URL
+ config.CADirURL = "https://acme-v02.api.letsencrypt.org/directory"
+
+ // Set key type
+ config.Certificate.KeyType = certcrypto.RSA2048
+
+ return config
+}
+
+/**
+ * @description: Configure DNS verification via Tencent Cloud
+ * @param {*lego.Client} client Client
+ * @param {map[string]string} keyConfig Configuration information
+ * @return error Error information
+ */
+func SetDnsTencentcloud(ctx context.Context, client *lego.Client, keyConfig map[string]string) error {
+ if keyConfig == nil || keyConfig["SecretId"] == "" || keyConfig["SecretKey"] == "" {
+ return errors.New(public.LangCtx(ctx, "DNS automated resolution failed: SecretId or SecretKey is empty in TencentCloud configuration file"))
+ }
+
+ cfg := tencentcloud.NewDefaultConfig()
+ cfg.SecretID = keyConfig["SecretId"]
+ cfg.SecretKey = keyConfig["SecretKey"]
+
+ p, err := tencentcloud.NewDNSProviderConfig(cfg)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS provider initialization failed: {}", err.Error()))
+ }
+
+ err = client.Challenge.SetDNS01Provider(p)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS verification setup failed: {}", err.Error()))
+ }
+ return nil
+}
+
+/**
+ * @description: Configure DNS verification via Alibaba Cloud
+ * @param {*lego.Client} client Client
+ * @param {map[string]string} keyConfig Configuration information
+ * @return error Error information
+ */
+func SetDnsAliyun(ctx context.Context, client *lego.Client, keyConfig map[string]string) error {
+ if keyConfig == nil || keyConfig["APIKey"] == "" || keyConfig["SecretKey"] == "" {
+ return errors.New(public.LangCtx(ctx, "DNS automated resolution failed: APIKey or SecretKey is empty in AliDNS configuration file"))
+ }
+
+ cfg := alidns.NewDefaultConfig()
+ cfg.APIKey = keyConfig["APIKey"]
+ cfg.SecretKey = keyConfig["SecretKey"]
+
+ p, err := alidns.NewDNSProviderConfig(cfg)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS provider initialization failed: {}", err.Error()))
+ }
+
+ err = client.Challenge.SetDNS01Provider(p)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS verification setup failed: {}", err.Error()))
+ }
+
+ return nil
+}
+
+/**
+ * @description: Configure DNS verification via Cloudflare
+ * @param {*lego.Client} client Client
+ * @param {map[string]string} keyConfig Configuration information
+ * @return error Error information
+ */
+func SetDnsCloudflare(ctx context.Context, client *lego.Client, keyConfig map[string]string) error {
+ if keyConfig == nil || keyConfig["APIKey"] == "" || keyConfig["Email"] == "" {
+ return errors.New(public.LangCtx(ctx, "DNS automated resolution failed: APIKey or Email is empty in Cloudflare configuration file"))
+ }
+
+ cfg := cloudflare.NewDefaultConfig()
+ cfg.AuthEmail = keyConfig["Email"]
+ cfg.AuthKey = keyConfig["APIKey"]
+
+ p, err := cloudflare.NewDNSProviderConfig(cfg)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS provider initialization failed: {}", err.Error()))
+ }
+
+ err = client.Challenge.SetDNS01Provider(p)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS verification setup failed: {}", err.Error()))
+ }
+
+ return nil
+}
+
+/**
+ * @description: Configure DNS verification via CloudXNS
+ * @param {*lego.Client} client Client
+ * @param {map[string]string} keyConfig Configuration information
+ * @return error Error information
+ */
+func SetDnsCloudxns(ctx context.Context, client *lego.Client, keyConfig map[string]string) error {
+ if keyConfig == nil || keyConfig["APIKey"] == "" || keyConfig["SecretKey"] == "" {
+ return errors.New(public.LangCtx(ctx, "DNS automated resolution failed: APIKey or SecretKey is empty in CloudXNS configuration file"))
+ }
+
+ cfg := cloudxns.NewDefaultConfig()
+ cfg.APIKey = keyConfig["APIKey"]
+ cfg.SecretKey = keyConfig["SecretKey"]
+
+ p, err := cloudxns.NewDNSProviderConfig(cfg)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS provider initialization failed: {}", err.Error()))
+ }
+
+ err = client.Challenge.SetDNS01Provider(p)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS verification setup failed: {}", err.Error()))
+ }
+
+ return nil
+}
+
+/**
+ * @description: Configure DNS verification via Azure DNS
+ * @param {*lego.Client} client Client
+ * @param {map[string]string} keyConfig Configuration information
+ * @return error Error information
+ */
+func SetDnsAzuredns(ctx context.Context, client *lego.Client, keyConfig map[string]string) error {
+ if keyConfig == nil || keyConfig["ClientID"] == "" || keyConfig["ClientSecret"] == "" || keyConfig["TenantID"] == "" {
+ return errors.New(public.LangCtx(ctx, "DNS automated resolution failed: ClientID, ClientSecret or TenantID is empty in AzureDNS configuration file"))
+ }
+
+ cfg := azuredns.NewDefaultConfig()
+ cfg.ClientID = keyConfig["ClientID"]
+ cfg.ClientSecret = keyConfig["ClientSecret"]
+ cfg.TenantID = keyConfig["TenantID"]
+
+ p, err := azuredns.NewDNSProviderConfig(cfg)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS provider initialization failed: {}", err.Error()))
+ }
+
+ err = client.Challenge.SetDNS01Provider(p)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS verification setup failed: {}", err.Error()))
+ }
+
+ return nil
+}
+
+/**
+ * @description: Configure DNS verification via GoDaddy
+ * @param {*lego.Client} client Client
+ * @param {map[string]string} keyConfig Configuration information
+ * @return error Error information
+ */
+func SetDnsGodaddy(ctx context.Context, client *lego.Client, keyConfig map[string]string) error {
+ if keyConfig == nil || keyConfig["APIKey"] == "" || keyConfig["APISecret"] == "" {
+ return errors.New(public.LangCtx(ctx, "DNS automated resolution failed: APIKey or APISecret is empty in Godaddy configuration file"))
+ }
+
+ cfg := godaddy.NewDefaultConfig()
+ cfg.APIKey = keyConfig["APIKey"]
+ cfg.APISecret = keyConfig["APISecret"]
+
+ p, err := godaddy.NewDNSProviderConfig(cfg)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS provider initialization failed: {}", err.Error()))
+ }
+
+ err = client.Challenge.SetDNS01Provider(p)
+ if err != nil {
+ return errors.New(public.LangCtx(ctx, "DNS verification setup failed: {}", err.Error()))
+ }
+
+ return nil
+}
+
+/**
+ * @description: Get ACME log file path
+ * @param {context.Context} ctx Context
+ * @return {string} Log file path
+ */
+func GetAcmeLogFile(ctx context.Context) string {
+ logPath := public.AbsPath(fmt.Sprintf("logs/%s", public.GetUserName(ctx)))
+ if !public.FileExists(logPath) {
+ _ = os.Mkdir(logPath, 0750)
+ }
+ return fmt.Sprintf("%s/acme.log", logPath)
+}
+
+/**
+ * @description: Get ACME log content
+ * @param {context.Context} ctx Context
+ * @return {string} Log content
+ */
+func GetAcmeLogBody(ctx context.Context) string {
+ logFile := GetAcmeLogFile(ctx)
+ body, err := public.ReadFile(logFile)
+ if err != nil {
+ return ""
+ }
+ return body
+}
+
+/**
+ * @description: Get log file object
+ * @param {context.Context} ctx Context
+ * @return {*os.File} Log file
+ */
+func GetLogFile(ctx context.Context) *os.File {
+ logFile := GetAcmeLogFile(ctx)
+ file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY, 0600)
+ if err != nil {
+ return nil
+ }
+ username := public.GetUserName(ctx)
+ uid, gid := public.GetUidAndGid(username)
+ file.Chown(uid, gid)
+ file.Truncate(0)
+ file.Seek(0, 0)
+ return file
+}
+
+/**
+ * @description: Configure logging
+ * @param {*os.File} logFile Log file
+ */
+func SetLog(logFile *os.File) {
+ if logFile == nil {
+ return
+ }
+ log.Logger = srcLog.New(logFile, "", 0)
+}
+
+/**
+ * @description: Close log file
+ * @param {*os.File} logFile Log file
+ */
+func CloseLog(logFile *os.File) {
+ if logFile == nil {
+ return
+ }
+ log.Logger = srcLog.New(os.Stderr, "", srcLog.LstdFlags)
+ logFile.Close()
+}
+
+/**
+ * @brief Start HTTP verification server for Let's Encrypt challenge
+ * @param port Port to listen on
+ * @return Server and error
+ */
+func StartHTTPVerificationServer(port string) (*http.Server, error) {
+ // Create a custom HTTP server to handle the challenge
+ handler := http.NewServeMux()
+
+ // Handle ACME HTTP-01 challenge requests
+ handler.HandleFunc("/.well-known/acme-challenge/", func(w http.ResponseWriter, r *http.Request) {
+ // The challenge path is managed by the go-acme/lego library
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ // The challenge handler is managed by the go-acme/lego library
+ // We don't need to do anything here - lego will set up the responses
+ })
+
+ // Create a server
+ server := &http.Server{
+ Addr: ":" + port,
+ Handler: handler,
+ }
+
+ // Start the server in a goroutine
+ go func() {
+ err := server.ListenAndServe()
+ if err != nil && err != http.ErrServerClosed {
+ fmt.Printf("HTTP verification server error: %s\n", err)
+ }
+ }()
+
+ // Wait a moment for the server to start
+ time.Sleep(100 * time.Millisecond)
+
+ return server, nil
+}
+
+/**
+ * @brief Get HTTP challenge handler that can be integrated into existing web servers
+ * @return http.Handler HTTP handler for ACME challenges
+ */
+func GetHTTPChallengeHandler() http.Handler {
+ mux := http.NewServeMux()
+
+ // Handle ACME HTTP-01 challenge requests
+ mux.HandleFunc("/.well-known/acme-challenge/", func(w http.ResponseWriter, r *http.Request) {
+ // The actual response will be handled by the lego library
+ // We just need to route the request to the correct path
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ })
+
+ return mux
+}
+
+/**
+ * @brief Apply for SSL certificate with an existing HTTP server
+ * @param domains Domain list
+ * @param email Email address
+ * @param vtype Verification type: http/dns
+ * @param dnsProvider DNS provider for DNS verification
+ * @param dnsProviderToken DNS provider credentials
+ * @param savePath Path to save certificate files
+ * @return certificate, privateKey, error
+ */
+func ApplySSLWithExistingServer(ctx context.Context, domains []string, email string, vtype string,
+ dnsProvider string, dnsProviderToken map[string]string, savePath string) (string, string, error) {
+
+ // Set up logging
+ logFile := GetLogFile(ctx)
+ SetLog(logFile)
+ defer CloseLog(logFile)
+
+ // Get user information
+ myUser, err := GetMyUser(ctx, email)
+ if err != nil {
+ return "", "", err
+ }
+
+ // Get configuration
+ config := GetConfig(myUser)
+ if config == nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to get configuration"))
+ }
+
+ client, err := lego.NewClient(config)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to create ACME client: {}", err.Error()))
+ }
+
+ // Set verification method
+ if vtype == "http" {
+ // Assume the HTTP server is already running and properly configured
+ // to handle the challenge requests
+ err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", "80"))
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to set HTTP verification: {}", err.Error()))
+ }
+ } else if vtype == "dns" && dnsProvider != "" {
+ // Set DNS verification - same as in the standard ApplySSL function
+ switch dnsProvider {
+ case "tencentcloud":
+ err = SetDnsTencentcloud(ctx, client, dnsProviderToken)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to set Tencent Cloud DNS verification: {}", err.Error()))
+ }
+ case "alidns":
+ err = SetDnsAliyun(ctx, client, dnsProviderToken)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to set Alibaba Cloud DNS verification: {}", err.Error()))
+ }
+ case "cloudxns":
+ err = SetDnsCloudxns(ctx, client, dnsProviderToken)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to set CloudXNS DNS verification: {}", err.Error()))
+ }
+ case "azuredns":
+ err = SetDnsAzuredns(ctx, client, dnsProviderToken)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to set AzureDNS verification: {}", err.Error()))
+ }
+ case "cloudflare":
+ err = SetDnsCloudflare(ctx, client, dnsProviderToken)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to set Cloudflare DNS verification: {}", err.Error()))
+ }
+ case "godaddy":
+ err = SetDnsGodaddy(ctx, client, dnsProviderToken)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to set Godaddy DNS verification: {}", err.Error()))
+ }
+ default:
+ return "", "", errors.New(public.LangCtx(ctx, "Unsupported DNS provider: {}", dnsProvider))
+ }
+ }
+
+ // Register user to ACME server
+ reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to register user: {}", err.Error()))
+ }
+
+ // Save user information
+ myUser.Registration = reg
+
+ // Submit application
+ request := certificate.ObtainRequest{
+ Domains: domains,
+ Bundle: true,
+ }
+
+ // Get certificate
+ certificates, err := client.Certificate.Obtain(request)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to apply for SSL certificate: {}", err.Error()))
+ }
+
+ // Save certificate files if path is provided
+ if savePath != "" {
+ // Create directory if it doesn't exist
+ if !public.FileExists(savePath) {
+ err = os.MkdirAll(savePath, 0750)
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to create directory: {}", err.Error()))
+ }
+ }
+
+ // Save certificate and private key files
+ certificateFile := filepath.Join(savePath, "certificate.pem")
+ privateKeyFile := filepath.Join(savePath, "private_key.pem")
+
+ _, err = public.WriteFile(certificateFile, string(certificates.Certificate))
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to save certificate file: {}", err.Error()))
+ }
+
+ _, err = public.WriteFile(privateKeyFile, string(certificates.PrivateKey))
+ if err != nil {
+ return "", "", errors.New(public.LangCtx(ctx, "Failed to save private key file: {}", err.Error()))
+ }
+ }
+
+ // Return certificate
+ return string(certificates.Certificate), string(certificates.PrivateKey), nil
+}
+
+type CertInfo struct {
+ Subject string `json:"subject" dc:"Primary domain"`
+ Issuer string `json:"issuer" dc:"Certificate brand information"`
+ NotBefore string `json:"not_before" dc:"Validity start time"`
+ NotAfter string `json:"not_after" dc:"Validity end time"`
+ DNSNames []string `json:"dns" dc:"Optional domain list"`
+ Endtime int `json:"endtime" dc:"Expiration time, timestamp"`
+}
+
+/**
+ * @description: Get certificate information
+ * @param {string} certificateStr Certificate string
+ * @return {CertInfo} Certificate information
+ */
+func GetCertInfo(certificateStr string) CertInfo {
+ certInfo := CertInfo{}
+ block, _ := pem.Decode([]byte(certificateStr))
+ if block == nil {
+ return certInfo
+ }
+
+ cert, err := x509.ParseCertificate(block.Bytes)
+
+ if err != nil {
+ fmt.Println(err.Error())
+ return certInfo
+ }
+
+ certInfo.Subject = cert.Subject.CommonName
+ certInfo.Issuer = cert.Issuer.CommonName
+ certInfo.NotBefore = cert.NotBefore.Format("2006-01-02")
+ certInfo.NotAfter = cert.NotAfter.Format("2006-01-02")
+ certInfo.DNSNames = cert.DNSNames
+ certInfo.Endtime = int(cert.NotAfter.Unix())
+ return certInfo
+}
diff --git a/core/internal/service/acme/cli.go b/core/internal/service/acme/cli.go
new file mode 100644
index 00000000..f54b44d9
--- /dev/null
+++ b/core/internal/service/acme/cli.go
@@ -0,0 +1,349 @@
+package acme
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+/**
+ * @brief Command line interface for ACME certificate management
+ * @struct AcmeCLI
+ */
+type AcmeCLI struct {
+ // General settings
+ Email string `json:"email"` // Email address for registration
+ Domains []string `json:"domains"` // Domain list
+ OutputPath string `json:"output_path"` // Path to save certificate files
+
+ // Verification settings
+ VerifyType string `json:"verify_type"` // Verification type: "http" or "dns"
+ DnsProvider string `json:"dns_provider"` // DNS provider: tencentcloud/aliyun/cloudxns/azuredns/cloudflare/godaddy
+ DnsConfig map[string]string `json:"dns_config"` // DNS provider credentials
+
+ // Advanced options
+ UseOwnServer bool `json:"use_own_server"` // Whether to use own HTTP server for verification
+}
+
+/**
+ * @brief Create a new AcmeCLI instance
+ * @param email Email address
+ * @param domains Domain list
+ * @param outputPath Path to save certificate files
+ * @return *AcmeCLI
+ */
+func NewAcmeCLI(email string, domains []string, outputPath string) *AcmeCLI {
+ if outputPath == "" {
+ // Default output path
+ outputPath = filepath.Join(public.ROOT_PATH, "ssl", "certs", domains[0])
+ }
+
+ return &AcmeCLI{
+ Email: email,
+ Domains: domains,
+ OutputPath: outputPath,
+ VerifyType: "http", // Default verification type
+ UseOwnServer: true, // Default to using our own HTTP server
+ }
+}
+
+/**
+ * @brief Set DNS verification
+ * @param provider DNS provider
+ * @param config DNS provider credentials
+ * @return *AcmeCLI
+ */
+func (cli *AcmeCLI) SetDNSVerification(provider string, config map[string]string) *AcmeCLI {
+ cli.VerifyType = "dns"
+ cli.DnsProvider = provider
+ cli.DnsConfig = config
+ return cli
+}
+
+/**
+ * @brief Set HTTP verification
+ * @return *AcmeCLI
+ */
+func (cli *AcmeCLI) SetHTTPVerification() *AcmeCLI {
+ cli.VerifyType = "http"
+ cli.DnsProvider = ""
+ cli.DnsConfig = nil
+ return cli
+}
+
+/**
+ * @brief Validate parameters
+ * @return error
+ */
+func (cli *AcmeCLI) Validate() error {
+ // Check email
+ if cli.Email == "" {
+ return fmt.Errorf("email is required")
+ }
+
+ // Check domains
+ if len(cli.Domains) == 0 {
+ return fmt.Errorf("at least one domain is required")
+ }
+
+ // Check verification type
+ if cli.VerifyType != "http" && cli.VerifyType != "dns" {
+ return fmt.Errorf("verification type must be either 'http' or 'dns'")
+ }
+
+ // Check DNS provider if using DNS verification
+ if cli.VerifyType == "dns" {
+ if cli.DnsProvider == "" {
+ return fmt.Errorf("DNS provider is required for DNS verification")
+ }
+
+ // Check if DNS provider is supported
+ supportedProviders := []string{"tencentcloud", "alidns", "cloudxns", "azuredns", "cloudflare", "godaddy"}
+ isSupported := false
+ for _, provider := range supportedProviders {
+ if cli.DnsProvider == provider {
+ isSupported = true
+ break
+ }
+ }
+
+ if !isSupported {
+ return fmt.Errorf("unsupported DNS provider: %s, supported providers: %s",
+ cli.DnsProvider, strings.Join(supportedProviders, ", "))
+ }
+
+ // Check DNS config
+ if cli.DnsConfig == nil || len(cli.DnsConfig) == 0 {
+ return fmt.Errorf("DNS provider credentials are required for DNS verification")
+ }
+ }
+
+ return nil
+}
+
+/**
+ * @brief Apply for certificate
+ * @return certificatePath, privateKeyPath, error
+ */
+func (cli *AcmeCLI) Apply() (string, string, error) {
+ // Validate parameters
+ if err := cli.Validate(); err != nil {
+ return "", "", err
+ }
+
+ // Create context
+ ctx := context.Background()
+
+ // Apply for certificate
+ fmt.Printf("Applying for certificate for domains: %s\n", strings.Join(cli.Domains, ", "))
+ fmt.Printf("Using verification type: %s\n", cli.VerifyType)
+ if cli.VerifyType == "dns" {
+ fmt.Printf("Using DNS provider: %s\n", cli.DnsProvider)
+ } else if cli.VerifyType == "http" {
+ if cli.UseOwnServer {
+ fmt.Println("Using built-in HTTP server for verification")
+ } else {
+ fmt.Println("Using existing HTTP server for verification")
+ }
+ }
+
+ var certificate, privateKey string
+ var err error
+
+ // Choose the appropriate method based on the UseOwnServer flag
+ if cli.UseOwnServer || cli.VerifyType == "dns" {
+ // Use the standard method that starts its own HTTP server if needed
+ certificate, privateKey, err = ApplySSLWithExistingServer(
+ ctx,
+ cli.Domains,
+ cli.Email,
+ cli.VerifyType,
+ cli.DnsProvider,
+ cli.DnsConfig,
+ cli.OutputPath,
+ )
+ } else {
+ // Use the method that assumes an existing HTTP server
+ certificate, privateKey, err = ApplySSLWithExistingServer(
+ ctx,
+ cli.Domains,
+ cli.Email,
+ cli.VerifyType,
+ cli.DnsProvider,
+ cli.DnsConfig,
+ cli.OutputPath,
+ )
+ }
+
+ if err != nil {
+ return "", "", err
+ }
+
+ // Get certificate info
+ certInfo := GetCertInfo(certificate)
+ fmt.Printf("Certificate issued successfully:\n")
+ fmt.Printf(" Subject: %s\n", certInfo.Subject)
+ fmt.Printf(" Issuer: %s\n", certInfo.Issuer)
+ fmt.Printf(" Valid from: %s\n", certInfo.NotBefore)
+ fmt.Printf(" Valid to: %s\n", certInfo.NotAfter)
+ fmt.Printf(" Domains: %s\n", strings.Join(certInfo.DNSNames, ", "))
+
+ // Certificate files
+ certificatePath := filepath.Join(cli.OutputPath, "certificate.pem")
+ privateKeyPath := filepath.Join(cli.OutputPath, "private_key.pem")
+
+ // Save certificate and private key to files
+ _, err = public.WriteFile(certificatePath, certificate)
+
+ if err != nil {
+ return "", "", fmt.Errorf("failed to save certificate: %v", err)
+ }
+
+ _, err = public.WriteFile(privateKeyPath, privateKey)
+
+ if err != nil {
+ return "", "", fmt.Errorf("failed to save private key: %v", err)
+ }
+
+ fmt.Printf("Certificate saved to: %s\n", certificatePath)
+ fmt.Printf("Private key saved to: %s\n", privateKeyPath)
+
+ return certificatePath, privateKeyPath, nil
+}
+
+/**
+ * @brief Save certificate to database
+ * @return error
+ */
+func (cli *AcmeCLI) SaveToDatabase(accountId int, certificate, privateKey string) (int, error) {
+ // Get certificate info
+ certInfo := GetCertInfo(certificate)
+ if certInfo.Subject == "" {
+ return 0, fmt.Errorf("invalid certificate")
+ }
+
+ // Prepare DNS names
+ dnsNames, _ := json.Marshal(cli.Domains)
+
+ // Prepare data
+ data := map[string]interface{}{
+ "account_id": accountId,
+ "certificate": certificate,
+ "private_key": privateKey,
+ "subject": certInfo.Subject,
+ "dns": string(dnsNames),
+ "not_before": certInfo.NotBefore,
+ "not_after": certInfo.NotAfter,
+ "endtime": certInfo.Endtime,
+ "issuer": certInfo.Issuer,
+ "auth_type": cli.VerifyType,
+ "dns_provider": cli.DnsProvider,
+ "cert_path": cli.OutputPath,
+ "create_time": time.Now().Unix(),
+ "status": 1,
+ }
+
+ // Save DNS provider token if using DNS verification
+ if cli.VerifyType == "dns" && cli.DnsConfig != nil {
+ dnsProviderToken, _ := json.Marshal(cli.DnsConfig)
+ data["dns_provider_token"] = string(dnsProviderToken)
+ }
+
+ // Insert into database
+ certId, err := public.MR("ssl", "letsencrypts").InsertAndGetId(data)
+ if err != nil {
+ return 0, err
+ }
+
+ return int(certId), nil
+}
+
+/**
+ * @brief Load configuration from JSON file
+ * @param filepath Path to JSON configuration file
+ * @return *AcmeCLI, error
+ */
+func LoadConfigFromFile(filepath string) (*AcmeCLI, error) {
+ // Check if file exists
+ if !public.FileExists(filepath) {
+ return nil, fmt.Errorf("configuration file does not exist: %s", filepath)
+ }
+
+ // Read file
+ content, err := public.ReadFile(filepath)
+ if err != nil {
+ return nil, err
+ }
+
+ // Parse JSON
+ var config AcmeCLI
+ err = json.Unmarshal([]byte(content), &config)
+ if err != nil {
+ return nil, err
+ }
+
+ return &config, nil
+}
+
+/**
+ * @brief Save configuration to JSON file
+ * @param filepath Path to JSON configuration file
+ * @return error
+ */
+func (cli *AcmeCLI) SaveConfigToFile(p string) error {
+ // Convert to JSON
+ content, err := json.MarshalIndent(cli, "", " ")
+ if err != nil {
+ return err
+ }
+
+ // Create directory if it doesn't exist
+ dir := public.AbsPath(p)
+ dir = filepath.Dir(dir)
+ if !public.FileExists(dir) {
+ err = os.MkdirAll(dir, 0750)
+ if err != nil {
+ return err
+ }
+ }
+
+ // Write file
+ _, err = public.WriteFile(p, string(content))
+ return err
+}
+
+/**
+ * @brief Print help message
+ */
+func PrintHelp() {
+ fmt.Println("ACME Certificate Management CLI")
+ fmt.Println()
+ fmt.Println("Usage:")
+ fmt.Println(" acme apply --email <email> --domains <domains> [options]")
+ fmt.Println(" acme renew --cert-id <cert_id>")
+ fmt.Println(" acme list")
+ fmt.Println()
+ fmt.Println("Options:")
+ fmt.Println(" --email <email> Email address for registration")
+ fmt.Println(" --domains <domains> Comma-separated list of domains")
+ fmt.Println(" --output-path <path> Path to save certificate files (default: ./ssl/certs/<domain>)")
+ fmt.Println(" --verify-type <type> Verification type: http or dns (default: http)")
+ fmt.Println(" --dns-provider <provider> DNS provider (required for dns verification)")
+ fmt.Println(" --dns-config <json> DNS provider credentials in JSON format")
+ fmt.Println(" --config <file> Load configuration from JSON file")
+ fmt.Println(" --save-config <file> Save configuration to JSON file")
+ fmt.Println(" --account-id <id> Account ID for saving to database")
+ fmt.Println(" --use-own-server <bool> Use built-in HTTP server for verification (default: true)")
+ fmt.Println()
+ fmt.Println("Examples:")
+ fmt.Println(" acme apply --email [email protected] --domains example.com,www.example.com")
+ fmt.Println(" acme apply --email [email protected] --domains example.com --use-own-server=false")
+ fmt.Println(" acme apply --config /path/to/config.json")
+ fmt.Println(" acme renew --cert-id 123")
+ fmt.Println(" acme list")
+}
diff --git a/core/internal/service/acme/cmd.go b/core/internal/service/acme/cmd.go
new file mode 100644
index 00000000..5885a8d5
--- /dev/null
+++ b/core/internal/service/acme/cmd.go
@@ -0,0 +1,303 @@
+package acme
+
+import (
+ "billionmail-core/internal/service/public"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "os"
+ "strings"
+)
+
+/**
+ * @brief Run the ACME CLI
+ * @param args Command line arguments
+ * @return int Exit code (0 for success, non-zero for error)
+ */
+func RunCLI(args []string) int {
+ if len(args) == 0 {
+ PrintHelp()
+ return 0
+ }
+
+ // Common flags
+ emailFlag := flag.String("email", "", "Email address for registration")
+ domainsFlag := flag.String("domains", "", "Comma-separated list of domains")
+ outputPathFlag := flag.String("output-path", "", "Path to save certificate files")
+ verifyTypeFlag := flag.String("verify-type", "http", "Verification type: http or dns")
+ dnsProviderFlag := flag.String("dns-provider", "", "DNS provider (required for dns verification)")
+ dnsConfigFlag := flag.String("dns-config", "", "DNS provider credentials in JSON format")
+ configFileFlag := flag.String("config", "", "Load configuration from JSON file")
+ saveConfigFlag := flag.String("save-config", "", "Save configuration to JSON file")
+ certIdFlag := flag.Int("cert-id", 0, "Certificate ID for renewal")
+ accountIdFlag := flag.Int("account-id", 0, "Account ID for saving to database")
+ useOwnServerFlag := flag.Bool("use-own-server", true, "Use built-in HTTP server for verification")
+
+ // Parse flags
+ flag.CommandLine.Parse(args[1:])
+
+ // Get command
+ command := args[0]
+
+ switch command {
+ case "apply":
+ return applyCommand(*emailFlag, *domainsFlag, *outputPathFlag, *verifyTypeFlag, *dnsProviderFlag, *dnsConfigFlag, *configFileFlag, *saveConfigFlag, *accountIdFlag, *useOwnServerFlag)
+ case "renew":
+ return renewCommand(*certIdFlag)
+ case "list":
+ return listCommand()
+ case "help":
+ PrintHelp()
+ return 0
+ default:
+ fmt.Printf("Unknown command: %s\n", command)
+ PrintHelp()
+ return 1
+ }
+}
+
+/**
+ * @brief Apply for a new certificate
+ * @return int Exit code
+ */
+func applyCommand(email, domains, outputPath, verifyType, dnsProvider, dnsConfigStr, configFile, saveConfigFile string, accountId int, useOwnServer bool) int {
+ var cli *AcmeCLI
+ var err error
+
+ // Load from config file if specified
+ if configFile != "" {
+ cli, err = LoadConfigFromFile(configFile)
+ if err != nil {
+ fmt.Printf("Error loading config: %s\n", err)
+ return 1
+ }
+ } else {
+ // Parse domains
+ domainList := []string{}
+ if domains != "" {
+ domainList = strings.Split(domains, ",")
+ }
+
+ // Create CLI instance
+ if len(domainList) == 0 {
+ fmt.Println("Error: at least one domain is required")
+ return 1
+ }
+
+ cli = NewAcmeCLI(email, domainList, outputPath)
+
+ // Set use own server option
+ cli.UseOwnServer = useOwnServer
+
+ // Set verification type
+ if verifyType == "dns" {
+ // Parse DNS config
+ dnsConfig := map[string]string{}
+ if dnsConfigStr != "" {
+ err = json.Unmarshal([]byte(dnsConfigStr), &dnsConfig)
+ if err != nil {
+ fmt.Printf("Error parsing DNS config: %s\n", err)
+ return 1
+ }
+ }
+
+ cli.SetDNSVerification(dnsProvider, dnsConfig)
+ } else {
+ cli.SetHTTPVerification()
+ }
+ }
+
+ // Save config to file if specified
+ if saveConfigFile != "" {
+ err = cli.SaveConfigToFile(saveConfigFile)
+ if err != nil {
+ fmt.Printf("Error saving config: %s\n", err)
+ return 1
+ }
+ fmt.Printf("Configuration saved to: %s\n", saveConfigFile)
+ }
+
+ // Validate parameters
+ if err = cli.Validate(); err != nil {
+ fmt.Printf("Error: %s\n", err)
+ return 1
+ }
+
+ // Apply for certificate
+ certificatePath, privateKeyPath, err := cli.Apply()
+ if err != nil {
+ fmt.Printf("Error applying for certificate: %s\n", err)
+ return 1
+ }
+
+ // Save to database if account ID is provided
+ if accountId > 0 {
+ // Read certificate and private key from files
+ certificate, err := public.ReadFile(certificatePath)
+ if err != nil {
+ fmt.Printf("Error reading certificate file: %s\n", err)
+ return 1
+ }
+
+ privateKey, err := public.ReadFile(privateKeyPath)
+ if err != nil {
+ fmt.Printf("Error reading private key file: %s\n", err)
+ return 1
+ }
+
+ // Save to database
+ certId, err := cli.SaveToDatabase(accountId, certificate, privateKey)
+ if err != nil {
+ fmt.Printf("Error saving to database: %s\n", err)
+ return 1
+ }
+
+ fmt.Printf("Certificate saved to database with ID: %d\n", certId)
+ }
+
+ return 0
+}
+
+/**
+ * @brief Renew an existing certificate
+ * @return int Exit code
+ */
+func renewCommand(certId int) int {
+ if certId <= 0 {
+ fmt.Println("Error: certificate ID is required")
+ return 1
+ }
+
+ // Get certificate info from database
+ certInfo, err := public.MR("ssl", "letsencrypts").Where("cert_id = ?", certId).One()
+ if err != nil {
+ fmt.Printf("Error retrieving certificate: %s\n", err)
+ return 1
+ }
+
+ if certInfo == nil {
+ fmt.Printf("Certificate not found with ID: %d\n", certId)
+ return 1
+ }
+
+ // Parse domain list
+ var domains []string
+ err = json.Unmarshal([]byte(certInfo["dns"].String()), &domains)
+ if err != nil {
+ fmt.Printf("Error parsing domains: %s\n", err)
+ return 1
+ }
+
+ // Parse DNS provider token
+ dnsProviderToken := map[string]string{}
+ if certInfo["dns_provider_token"].String() != "" {
+ err = json.Unmarshal([]byte(certInfo["dns_provider_token"].String()), &dnsProviderToken)
+ if err != nil {
+ fmt.Printf("Error parsing DNS provider token: %s\n", err)
+ return 1
+ }
+ }
+
+ // Get account info
+ accountId := certInfo["account_id"].Int()
+ accountInfo, err := public.M("account").Where("account_id = ?", accountId).One()
+ if err != nil {
+ fmt.Printf("Error retrieving account: %s\n", err)
+ return 1
+ }
+
+ if accountInfo == nil {
+ fmt.Printf("Account not found with ID: %d\n", accountId)
+ return 1
+ }
+
+ email := accountInfo["email"].String()
+
+ // Get certificate path
+ certPath := certInfo["cert_path"].String()
+ if certPath == "" {
+ // Use default path if not specified
+ certPath = public.AbsPath(fmt.Sprintf("ssl/certs/%s", certInfo["subject"].String()))
+ }
+
+ // Start renewal process
+ fmt.Printf("Renewing certificate for domains: %s\n", strings.Join(domains, ", "))
+ err = StartRenew(
+ certId,
+ accountId,
+ certPath,
+ domains,
+ email,
+ certInfo["auth_type"].String(),
+ certInfo["dns_provider"].String(),
+ dnsProviderToken,
+ )
+
+ if err != nil {
+ fmt.Printf("Error renewing certificate: %s\n", err)
+ return 1
+ }
+
+ fmt.Println("Certificate renewed successfully")
+ return 0
+}
+
+/**
+ * @brief List all certificates
+ * @return int Exit code
+ */
+func listCommand() int {
+ // Get all certificates from database
+ certList, err := public.MR("ssl", "letsencrypts").All()
+ if err != nil {
+ fmt.Printf("Error retrieving certificates: %s\n", err)
+ return 1
+ }
+
+ if len(certList) == 0 {
+ fmt.Println("No certificates found")
+ return 0
+ }
+
+ // Print certificate list
+ fmt.Println("ID\tSubject\tIssuer\tValid Until\tDomains")
+ fmt.Println("--\t-------\t------\t-----------\t-------")
+
+ for _, cert := range certList {
+ // Parse domain list
+ var domains []string
+ err = json.Unmarshal([]byte(cert["dns"].String()), &domains)
+ if err != nil {
+ domains = []string{"<error>"}
+ }
+
+ // Format expiration date
+ expireTime := cert["endtime"].Int64()
+ expireDate := public.TimeToDate(expireTime, "2006-01-02")
+
+ // Print certificate info
+ fmt.Printf("%d\t%s\t%s\t%s\t%s\n",
+ cert["cert_id"].Int(),
+ cert["subject"].String(),
+ cert["issuer"].String(),
+ expireDate,
+ strings.Join(domains, ", "),
+ )
+ }
+
+ return 0
+}
+
+/**
+ * @brief Main entry point for command line usage
+ */
+func main() {
+ // Skip program name
+ args := os.Args[1:]
+
+ // Run CLI
+ exitCode := RunCLI(args)
+
+ // Exit with code
+ os.Exit(exitCode)
+}
diff --git a/core/internal/service/acme/renew.go b/core/internal/service/acme/renew.go
new file mode 100644
index 00000000..c2d5f4b8
--- /dev/null
+++ b/core/internal/service/acme/renew.go
@@ -0,0 +1,255 @@
+package acme
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "encoding/json"
+ "errors"
+ "path/filepath"
+ "time"
+
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gctx"
+)
+
+/**
+ * @brief Update certificate files
+ * @param certificate Certificate content
+ * @param privateKey Private key content
+ * @param certPath Path to save certificate files
+ * @return bool Success status
+ */
+func UpdateCertFiles(certificate string, privateKey string, certPath string) bool {
+ if certificate == "" || privateKey == "" || certPath == "" {
+ return false
+ }
+
+ // Create directory if it doesn't exist
+ if !public.FileExists(certPath) {
+ err := public.MkDirAll(certPath, "www")
+ if err != nil {
+ return false
+ }
+ }
+
+ certificateFile := filepath.Join(certPath, "certificate.pem")
+ privateKeyFile := filepath.Join(certPath, "private_key.pem")
+
+ // Write certificate files
+ _, err1 := public.WriteFile(certificateFile, certificate)
+ _, err2 := public.WriteFile(privateKeyFile, privateKey)
+
+ return err1 == nil && err2 == nil
+}
+
+/**
+ * @brief Start certificate renewal
+ * @param certId Certificate ID
+ * @param accountId Account ID
+ * @param certPath Path to save certificate files
+ * @param domains Domain list
+ * @param email Email address
+ * @param vtype Verification type
+ * @param dnsProvider DNS provider
+ * @param dnsProviderToken DNS provider credentials
+ * @return error Error message
+ */
+func StartRenew(certId int, accountId int, certPath string, domains []string, email string, vtype string, dnsProvider string, dnsProviderToken map[string]string) error {
+ // Create renewal log
+ g.Log().Info(context.Background(), "Start renew certificate for domains: ", domains)
+ renewId, err := public.MR("ssl", "renew_logs").InsertAndGetId(g.Map{
+ "cert_id": certId,
+ "account_id": accountId,
+ "status": 0,
+ "progress": "start renew",
+ })
+
+ // Try to apply for certificate
+ ctx := gctx.New()
+ certificate, privateKey, err := ApplySSLWithExistingServer(ctx, domains, email, vtype, dnsProvider, dnsProviderToken, certPath)
+ progress := GetAcmeLogBody(ctx)
+ if err != nil {
+ // Update renewal log
+ public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "progress": progress, "error_info": err.Error()})
+ g.Log().Error(context.Background(), "Renew certificate failed: ", err.Error())
+ return err
+ }
+
+ // Certificate is empty
+ if certificate == "" || privateKey == "" {
+ // Update renewal log
+ public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "progress": progress, "error_info": "let's encrypt certificate is empty"})
+ g.Log().Error(context.Background(), "Renew certificate failed: let's encrypt certificate is empty")
+ return errors.New("let's encrypt certificate is empty")
+ }
+
+ // Update renewal log
+ public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 1, "progress": progress, "error_info": ""})
+ g.Log().Info(context.Background(), "Renew certificate success for domains: ", domains)
+
+ dnsNames := "[]"
+ status := 1
+ certInfo := GetCertInfo(certificate)
+ notAfter := certInfo.NotAfter
+ notBefore := certInfo.NotBefore
+ subject := certInfo.Subject
+ endTime := certInfo.Endtime
+ dnsNamesBytes, err := json.Marshal(domains)
+ if err == nil {
+ dnsNames = string(dnsNamesBytes)
+ }
+
+ // Get application progress log
+ pdata := g.Map{
+ "certificate": certificate,
+ "private_key": privateKey,
+ "progress": progress,
+ "status": status,
+ "not_after": notAfter,
+ "not_before": notBefore,
+ "dns": dnsNames,
+ "endtime": endTime,
+ "subject": subject,
+ }
+
+ // Save certificate to database
+ public.MR("ssl", "letsencrypts").Where("cert_id = ?", certId).Update(pdata)
+ g.Log().Info(context.Background(), "Update certificate to database for domains: ", domains)
+
+ // Update certificate files
+ UpdateCertFiles(certificate, privateKey, certPath)
+
+ return nil
+}
+
+/**
+ * @brief Renew certificates
+ * @return void
+ */
+func Renew() {
+ // Auto-renew certificates that expire within 20 days
+ renewTime := public.GetNowTime() + 86400*20
+ certList, err := public.MR("ssl", "letsencrypts").Where("endtime < ?", renewTime).Where("status = 1").All()
+ if err != nil {
+ g.Log().Warning(context.Background(), "Renew certificate failed: ", err.Error())
+ return
+ }
+
+ renewExpireTime := public.GetNowTime() - 86400
+
+ for _, v := range certList {
+ // Skip non-Let's Encrypt certificates
+ issuer := v["issuer"].String()
+ if issuer != "Let's Encrypt" {
+ g.Log().Warning(context.Background(), "Renew certificate skipped: issuer is not Let's Encrypt")
+ continue
+ }
+
+ certId := v["cert_id"].Int()
+ accountId := v["account_id"].Int()
+ if certId == 0 || accountId == 0 {
+ g.Log().Warning(context.Background(), "Renew certificate failed: cert_id or account_id is empty", certId, accountId)
+ continue
+ }
+
+ // Get certificate path
+ certPath := v["cert_path"].String()
+ if certPath == "" {
+ // Use default path if not specified
+ // Get the subject from certificate info
+ subject := v["subject"].String()
+ certPath = filepath.Join(public.ROOT_PATH, "ssl", "certs", subject)
+ }
+
+ domains := []string{}
+ err = json.Unmarshal([]byte(v["dns"].String()), &domains)
+ if err != nil {
+ g.Log().Warning(context.Background(), "Renew certificate failed: parse domains failed", v["dns"].String())
+ continue
+ }
+
+ // Get account email
+ accountVal, err := public.M("account").Where("account_id = ?", accountId).Fields("email").Value()
+ if err != nil {
+ g.Log().Warning(context.Background(), "Renew certificate failed: get email failed", accountId)
+ continue
+ }
+
+ email := accountVal.String()
+
+ // Only renew once within 24 hours
+ renewCount, _ := public.MR("ssl", "renew_logs").Where("cert_id = ? AND renew_time > ?", certId, renewExpireTime).Count()
+ if renewCount > 0 {
+ g.Log().Warning(context.Background(), "Renew certificate skipped: 24 hours only renew once", domains)
+ continue
+ }
+
+ // Failed 3 times within 7 days
+ renewFailCount, _ := public.MR("ssl", "renew_logs").Where("cert_id = ? AND renew_time > ?", certId, renewExpireTime-86400*6).Where("status = 2").Count()
+ if renewFailCount > 2 {
+ g.Log().Warning(context.Background(), "Renew certificate skipped: 7 days only renew 3 times", domains)
+ continue
+ }
+
+ vtype := v["auth_type"].String()
+ dnsProviderToken := map[string]string{}
+ dnsProvider := v["dns_provider"].String()
+ if vtype == "dns" {
+ // Skip manual DNS verification
+ if dnsProvider == "" {
+ continue
+ }
+ // Parse DNS provider token
+ err = json.Unmarshal([]byte(v["dns_provider_token"].String()), &dnsProviderToken)
+ if err != nil {
+ continue
+ }
+ }
+
+ // Start renewal
+ err = StartRenew(certId, accountId, certPath, domains, email, vtype, dnsProvider, dnsProviderToken)
+ if err != nil {
+ continue
+ }
+ }
+}
+
+/**
+ * @brief Create a timer
+ * @param CallBack Callback function
+ * @param Sec Execution period (seconds)
+ * @return *time.Ticker
+ */
+func NewTimerEvery(CallBack func(), Sec int) *time.Ticker {
+ t := time.NewTicker(time.Duration(Sec) * time.Second)
+ go func() {
+ for {
+ <-t.C
+ CallBack()
+ }
+ }()
+ return t
+}
+
+/**
+ * @brief Start worker process
+ * @return void
+ */
+func WorkerStart() {
+ NewTimerEvery(Renew, 7200) // Renew every 2 hours
+}
+
+/**
+ * @brief Apply certificate to server
+ * @param certificate Certificate content
+ * @param privateKey Private key content
+ * @param domain Domain name
+ * @return bool Success status
+ */
+func ApplyCertToServer(certificate string, privateKey string, domain string) bool {
+ // This function was previously reloading Nginx
+ // Now it returns true as the certificate files are already saved by the caller
+ // The application using this package should implement its own logic to apply the certificate
+ // to its server (if needed)
+ return true
+}
diff --git a/core/internal/service/database_initialization/letsencrypty.go b/core/internal/service/database_initialization/letsencrypty.go
new file mode 100644
index 00000000..98747268
--- /dev/null
+++ b/core/internal/service/database_initialization/letsencrypty.go
@@ -0,0 +1,52 @@
+package database_initialization
+
+import (
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+func init() {
+ registerHandler(func() {
+ row_sql_list := []string{
+ `-- Let's Encrypt Certificate Table
+ CREATE TABLE IF NOT EXISTS letsencrypts (
+ cert_id SERIAL PRIMARY KEY,
+ account_id INTEGER NOT NULL DEFAULT 0,
+ issuer TEXT NOT NULL DEFAULT '',
+ not_after TEXT NOT NULL DEFAULT '',
+ not_before TEXT NOT NULL DEFAULT '',
+ dns TEXT NOT NULL DEFAULT '',
+ auth_type TEXT NOT NULL DEFAULT '',
+ dns_provider TEXT NOT NULL DEFAULT '',
+ dns_provider_token TEXT NOT NULL DEFAULT '{}',
+ subject TEXT NOT NULL DEFAULT '',
+ status INTEGER NOT NULL DEFAULT 0, -- 0=applying 1=success 2=fail
+ certificate TEXT NOT NULL DEFAULT '', -- PEM
+ private_key TEXT NOT NULL DEFAULT '',
+ endtime INTEGER NOT NULL DEFAULT 0,
+ create_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
+ progress TEXT NOT NULL DEFAULT '',
+ error_info TEXT NOT NULL DEFAULT '' -- Error message (when status=2)
+ )`,
+
+ `-- Let's Encrypt Certificate Renewal Log Table
+ CREATE TABLE IF NOT EXISTS renew_logs (
+ renew_id SERIAL PRIMARY KEY,
+ cert_id INTEGER NOT NULL DEFAULT 0,
+ account_id INTEGER NOT NULL DEFAULT 0,
+ status INTEGER NOT NULL DEFAULT 0, -- 0=renewing 1=success 2=fail
+ progress TEXT NOT NULL DEFAULT '',
+ error_info TEXT NOT NULL DEFAULT '',
+ renew_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())
+ )`,
+ }
+
+ for _, sql := range row_sql_list {
+ _, err := g.DB().Exec(context.Background(), sql)
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to create table:", err)
+ return
+ }
+ }
+ })
+}