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
Added console certificate request Optimize the domain list and add the sender domain to automatically apply for the deployment certificate New certificates are automatically renewed
lotkfba757757505
diff --git a/core/api/domains/domains.go b/core/api/domains/domains.goindex 98418c14..094ab13f 100644--- a/core/api/domains/domains.go+++ b/core/api/domains/domains.go@@ -21,4 +21,5 @@ type IDomainsV1 interface {GetSSL(ctx context.Context, req *v1.GetSSLReq) (res *v1.GetSSLRes, err error)ApplyCert(ctx context.Context, req *v1.ApplyCertReq) (res *v1.ApplyCertRes, err error)GetCertList(ctx context.Context, req *v1.GetCertListReq) (res *v1.GetCertListRes, err error)+ ConsoleApplyCert(ctx context.Context, req *v1.ConsoleApplyCertReq) (res *v1.ConsoleApplyCertRes, err error)}diff --git a/core/api/domains/v1/ssl.go b/core/api/domains/v1/ssl.goindex 703cfd9d..695d9825 100644--- a/core/api/domains/v1/ssl.go+++ b/core/api/domains/v1/ssl.go@@ -23,3 +23,11 @@ type GetCertListReq struct {type GetCertListRes struct {api_v1.StandardRes}++type ConsoleApplyCertReq struct {+ g.Meta `path:"/ssl/console_apply_cert" tags:"SSL" method:"post" sm:"ConsoleApplyCert" in:"body"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+}+type ConsoleApplyCertRes struct {+ api_v1.StandardRes+}diff --git a/core/internal/controller/domains/domains_v1_console_apply_cert.go b/core/internal/controller/domains/domains_v1_console_apply_cert.gonew file mode 100644index 00000000..348f06e6--- /dev/null+++ b/core/internal/controller/domains/domains_v1_console_apply_cert.go@@ -0,0 +1,22 @@+package domains++import (+ "billionmail-core/api/domains/v1"+ "billionmail-core/internal/service/domains"+ "billionmail-core/internal/service/public"+ "context"+ "github.com/gogf/gf/v2/errors/gerror"+)++func (c *ControllerV1) ConsoleApplyCert(ctx context.Context, req *v1.ConsoleApplyCertReq) (res *v1.ConsoleApplyCertRes, err error) {+ res = &v1.ConsoleApplyCertRes{}++ err = domains.ApplyConsoleCert(ctx)+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed : {}", err.Error())))+ return+ }++ res.SetSuccess("Certificate applied successfully")+ return+}diff --git a/core/internal/controller/settings/settings.go b/core/internal/controller/settings/settings.goindex fb178d85..25d4df37 100644--- a/core/internal/controller/settings/settings.go+++ b/core/internal/controller/settings/settings.go@@ -14,7 +14,6 @@ import ("os""path/filepath""strconv"- "strings""time")@@ -23,35 +22,6 @@ var (projectPath = public.AbsPath("../"))-// loadEnvFile .env-func loadEnvFile() (map[string]string, error) {- content, err := os.ReadFile(envPath)- if err != nil {- return nil, err- }-- envMap := make(map[string]string)- lines := strings.Split(string(content), "\n")-- for _, line := range lines {- line = strings.TrimSpace(line)- if line == "" || strings.HasPrefix(line, "#") {- continue- }-- parts := strings.SplitN(line, "=", 2)- if len(parts) != 2 {- continue- }-- key := strings.TrimSpace(parts[0])- value := strings.Trim(strings.TrimSpace(parts[1]), `"'`)- envMap[key] = value- }-- return envMap, nil-}-// loadSSLInfofunc loadSSLInfo() (*v1.SSLConfig, error) {certPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "cert.pem"))diff --git a/core/internal/controller/settings/settings_v1_get_system_config.go b/core/internal/controller/settings/settings_v1_get_system_config.goindex acbeec44..a8de76b2 100644--- a/core/internal/controller/settings/settings_v1_get_system_config.go+++ b/core/internal/controller/settings/settings_v1_get_system_config.go@@ -10,7 +10,7 @@ import (func (c *ControllerV1) GetSystemConfig(ctx context.Context, req *v1.GetSystemConfigReq) (res *v1.GetSystemConfigRes, err error) {res = &v1.GetSystemConfigRes{}- envMap, err := loadEnvFile()+ envMap, err := public.LoadEnvFile()if err != nil {res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read environment variable file: {}", err)))return res, nildiff --git a/core/internal/controller/settings/settings_v1_set_system_config.go b/core/internal/controller/settings/settings_v1_set_system_config.goindex eeee81f7..7799914f 100644--- a/core/internal/controller/settings/settings_v1_set_system_config.go+++ b/core/internal/controller/settings/settings_v1_set_system_config.go@@ -41,7 +41,7 @@ func (c *ControllerV1) SetSystemConfig(ctx context.Context, req *v1.SetSystemCon}}- envMap, err := loadEnvFile()+ envMap, err := public.LoadEnvFile()if err != nil {res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read environment variable file: {}", err)))return res, nildiff --git a/core/internal/controller/settings/settings_v1_set_system_config_key.go b/core/internal/controller/settings/settings_v1_set_system_config_key.goindex 65f53890..8414007d 100644--- a/core/internal/controller/settings/settings_v1_set_system_config_key.go+++ b/core/internal/controller/settings/settings_v1_set_system_config_key.go@@ -22,7 +22,7 @@ func (c *ControllerV1) SetSystemConfigKey(ctx context.Context, req *v1.SetSystem}// 1. Read the current .env file content- envMap, err := loadEnvFile()+ envMap, err := public.LoadEnvFile()if err != nil {res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read environment variable file: {}", err)))return res, nildiff --git a/core/internal/service/domains/ssl.go b/core/internal/service/domains/ssl.goindex 6e83ac1c..63a30854 100644--- a/core/internal/service/domains/ssl.go+++ b/core/internal/service/domains/ssl.go@@ -1,6 +1,7 @@package domainsimport (+ "billionmail-core/api/domains/v1""billionmail-core/internal/consts""billionmail-core/internal/model""billionmail-core/internal/model/entity"@@ -8,9 +9,13 @@ import (docker "billionmail-core/internal/service/dockerapi""billionmail-core/internal/service/mail_service""billionmail-core/internal/service/public"+ "billionmail-core/internal/service/rbac""context""encoding/json"+ "fmt"+ "github.com/gogf/gf/v2/errors/gerror""github.com/gogf/gf/v2/frame/g"+ "github.com/gogf/gf/v2/util/gconv""net/url""path/filepath""time"@@ -144,3 +149,214 @@ func ApplyCertToService(domain, crtPem, keyPem string) (err error) {return}++func ApplyCertToConsole(crtPem, keyPem string) (err error) {++ _, err = public.WriteFile(public.AbsPath(filepath.Join(consts.SSL_PATH, "cert.pem")), crtPem)++ if err != nil {+ return err+ }++ _, err = public.WriteFile(public.AbsPath(filepath.Join(consts.SSL_PATH, "key.pem")), keyPem)++ if err != nil {+ return err+ }++ // Reload server ssl+ go func() {+ time.Sleep(time.Millisecond * 500)++ var dk *docker.DockerAPI+ dk, err = docker.NewDockerAPI()++ if err != nil {+ g.Log().Warning(context.Background(), "Get docker api instance failed")+ return+ }++ defer dk.Close()++ err = dk.RestartContainerByName(context.Background(), "billionmail-core-billionmail-1")+ }()++ return+}++func GetConsoleSSLInfo() (v1.CertInfo, error) {+ certPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "cert.pem"))+ keyPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "key.pem"))+ certInfo := v1.CertInfo{}+ if !public.FileExists(certPath) || !public.FileExists(keyPath) {+ return certInfo, nil+ }+ crtPem, err := public.ReadFile(certPath)+ if err != nil {+ return certInfo, err+ }+ err = gconv.Struct(acme.GetCertInfo(crtPem), &certInfo)+ if err == nil {+ certInfo.CertPem = crtPem+ certInfo.KeyPem, _ = public.ReadFile(keyPath)+ }+ return certInfo, nil+}++// ApplyConsoleCert Requesting a Console Certificate+func ApplyConsoleCert(ctx context.Context) error {+ // 取hostname+ envMap, err := public.LoadEnvFile()+ if err != nil {+ return err+ }+ hostname := envMap["BILLIONMAIL_HOSTNAME"]++ if hostname == "" {+ return gerror.New("BILLIONMAIL_HOSTNAME environment variable is not set")+ }+ mailDomain := public.FormatMX(hostname)++ // Check for the existence of a certificate+ sql := fmt.Sprintf("dns::jsonb ? '%s' AND status = 1 AND endtime > %d", mailDomain, time.Now().Unix())+ crt := &entity.Letsencrypt{}+ err = g.DB().Model("letsencrypts").+ Where(sql).+ Order("endtime desc").+ Limit(1).Scan(crt)++ if err != nil {+ //g.Log().Warning(ctx, "letsencrypts query error:", err)+ return err+ }+ if crt == nil || crt.Certificate == "" {+ g.Log().Debug(ctx, "No existing certificate found:", hostname)+ } else {+ if crt.Status == 1 && crt.EndTime > time.Now().Unix() {+ err = ApplyCertToConsole(crt.Certificate, crt.PrivateKey)+ if err != nil {+ return gerror.Newf("Failed to apply existing certificate to console: %v", err)+ }+ return nil+ }++ }++ accountInfo, accErr := rbac.GetCurrentAccount(ctx)+ if accErr != nil {+ return accErr+ }++ // Check that the hostname a record exists+ Arecords, _ := GetARecord(hostname, false)++ if Arecords.Host == "" || Arecords.Value == "" {+ return gerror.Newf("A Record does not exist, please check DNS Settings: %s", hostname)+ }++ certificate, privateKey, applyErr := acme.ApplySSLWithExistingServer(ctx, []string{hostname}, accountInfo.Email, "http", "", nil, public.AbsPath(consts.SSL_PATH))+ if applyErr != nil {+ //g.Log().Error(ctx, "Failed to request console certificate: ", applyErr)+ return applyErr+ }++ if certificate == "" || privateKey == "" {+ return gerror.New("The content of the application certificate is empty")+ }+ dnsNames := "[]"+ notAfter := "0000-00-00"+ notBefore := "0000-00-00"+ endTime := 0+ status := -1+ subject := ""++ if certificate != "" {+ certInfo := acme.GetCertInfo(certificate)+ notAfter = certInfo.NotAfter+ notBefore = certInfo.NotBefore+ subject = certInfo.Subject+ endTime = certInfo.Endtime+ dnsNamesBytes, err := json.Marshal([]string{mailDomain, hostname})+ if err == nil {+ dnsNames = string(dnsNamesBytes)+ }+ status = 1+ }++ // get the progress of the certificate application+ progress := acme.GetAcmeLogBody(ctx)+ pdata := g.Map{+ "account_id": accountInfo.AccountId,+ "certificate": certificate,+ "private_key": privateKey,+ "error_info": "",+ "progress": progress,+ "status": status,+ "not_after": notAfter,+ "not_before": notBefore,+ "dns": dnsNames,+ "endtime": endTime,+ "subject": subject,+ }++ // Save the certificate and key to the database+ _, err = g.DB().Model("letsencrypts").Insert(pdata)++ if err != nil {+ return gerror.Newf("Failed to save certificate to database: %v", err)+ }++ if err := ApplyCertToConsole(certificate, privateKey); err != nil {+ return err+ }+ return nil+}++// Auto-renew SSL certificate+func AutoRenewSSL(ctx context.Context) {+ // Renew console SSL certificate+ certInfo, err := GetConsoleSSLInfo()+ if err == nil && certInfo.Endtime > 0 {+ remain := certInfo.Endtime - int(time.Now().Unix())+ g.Log().Debug(ctx, "Remaining time for console certificate: ", remain, " seconds")+ if remain < 3*24*3600 {+ err = ApplyConsoleCert(ctx)+ if err != nil {+ g.Log().Warningf(ctx, "Console certificate is about to expire, auto-renewal failed: %v", err)+ } else {+ g.Log().Info(ctx, "Console certificate is about to expire, auto-renewal succeeded")+ }+ }+ }++ var domainList []string+ rows, err := g.DB().Model("domains").Fields("domain").All()+ if err == nil {+ for _, row := range rows {+ domain := row["domain"].String()+ if domain != "" {+ domainList = append(domainList, domain)+ }+ }+ }+ g.Log().Debug(ctx, "List of domains that need renewal: ", domainList)+ for _, domain := range domainList {+ certInfo, err := mail_service.NewCertificate().GetSSLInfo(domain)+ if err == nil && certInfo.Endtime > 0 {+ remain := certInfo.Endtime - int(time.Now().Unix())+ g.Log().Debug(ctx, "Remaining time for domain certificate: ", remain, " seconds", domain)+ if remain < 3*24*3600 {+ g.Log().Info(ctx, "Domain certificate is about to expire, auto-renewing: ", domain)+ accountInfo, accErr := rbac.GetCurrentAccount(ctx)+ if accErr == nil {+ certErr := ApplyLetsEncryptCertWithHttp(ctx, domain, accountInfo)+ if certErr != nil {+ g.Log().Warningf(ctx, "Domain name [%s] added successfully, but auto-request certificate failed: %v", domain, certErr)+ }+ }+ }+ }+ // Skip if no certificate exists (endtime=0)+ }++}diff --git a/core/internal/service/public/common.go b/core/internal/service/public/common.goindex 2cb7ebc3..37e269b2 100644--- a/core/internal/service/public/common.go+++ b/core/internal/service/public/common.go@@ -2574,3 +2574,33 @@ func AddUnsubscribeButton(content string) string {func FormatMX(domain string) string {return "mail." + strings.TrimPrefix(domain, "mail.")}++// loadEnvFile .env+func LoadEnvFile() (map[string]string, error) {+ envPath := AbsPath("../.env")+ content, err := os.ReadFile(envPath)+ if err != nil {+ return nil, err+ }++ envMap := make(map[string]string)+ lines := strings.Split(string(content), "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ if line == "" || strings.HasPrefix(line, "#") {+ continue+ }++ parts := strings.SplitN(line, "=", 2)+ if len(parts) != 2 {+ continue+ }++ key := strings.TrimSpace(parts[0])+ value := strings.Trim(strings.TrimSpace(parts[1]), `"'`)+ envMap[key] = value+ }++ return envMap, nil+}