完善证书管理与邮件通知流程

This commit is contained in:
xuans committed 2026-08-28 15:23:23 +08:00
1 parent c74372284a
commit b2833b761d
60 files changed
+7340 -254

No files matched your search

+649
View File
@@ -0,0 +1,649 @@
package cli
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"git.pcux.cn/xuans/Scert/backend/internal/app"
"git.pcux.cn/xuans/Scert/backend/internal/config"
)
func newCertificateCommand() *cobra.Command {
command := &cobra.Command{Use: "certificate", Short: "查询和校验证书"}
command.AddCommand(newCertificateListCommand(), newCertificateShowCommand(), newCertificateValidateCommand())
return command
}
func newCertificateListCommand() *cobra.Command {
return &cobra.Command{
Use: "list",
Short: "查看证书列表",
RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApp(cmd.Context())
if err != nil {
return err
}
defer service.Close()
items, err := service.Repository.List(cmd.Context())
if err != nil {
return err
}
result := make([]map[string]any, 0, len(items))
for _, item := range items {
entry := map[string]any{"domain": item}
current, currentErr := service.Certificates.Current(cmd.Context(), item.ID)
if currentErr != nil {
entry["certificate_error"] = currentErr.Error()
} else {
entry["certificate"] = current
}
result = append(result, entry)
}
return printJSON(cmd, result)
},
}
}
func newCertificateShowCommand() *cobra.Command {
var id string
command := &cobra.Command{
Use: "show",
Short: "查看当前证书详情",
RunE: func(cmd *cobra.Command, args []string) error {
if strings.TrimSpace(id) == "" {
return errors.New("域名 ID 不能为空")
}
service, err := openApp(cmd.Context())
if err != nil {
return err
}
defer service.Close()
result, err := service.Certificates.Current(cmd.Context(), id)
if err != nil {
return err
}
return printJSON(cmd, result)
},
}
command.Flags().StringVar(&id, "id", "", "域名 ID")
_ = command.MarkFlagRequired("id")
return command
}
func newCertificateValidateCommand() *cobra.Command {
var id string
command := &cobra.Command{
Use: "validate",
Short: "校验当前证书",
RunE: func(cmd *cobra.Command, args []string) error {
if strings.TrimSpace(id) == "" {
return errors.New("域名 ID 不能为空")
}
service, err := openApp(cmd.Context())
if err != nil {
return err
}
defer service.Close()
result, err := service.Certificates.ValidateCurrent(cmd.Context(), id)
if err != nil {
return err
}
return printJSON(cmd, map[string]any{"valid": true, "certificate": result})
},
}
command.Flags().StringVar(&id, "id", "", "域名 ID")
_ = command.MarkFlagRequired("id")
return command
}
func newRenewCommand() *cobra.Command {
var id string
command := &cobra.Command{
Use: "renew",
Short: "执行自动续期检查或续期指定域名",
RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApp(cmd.Context())
if err != nil {
return err
}
defer service.Close()
if strings.TrimSpace(id) != "" {
result, err := service.Workflow.IssueWithReport(cmd.Context(), id)
if err != nil {
return err
}
return printJSON(cmd, result)
}
if service.Renewal == nil {
return errors.New("自动续期服务未初始化")
}
result, err := service.Renewal.RunOnce(cmd.Context())
if err != nil {
return err
}
return printJSON(cmd, result)
},
}
command.Flags().StringVar(&id, "id", "", "域名 ID;留空时检查所有需要续期的域名")
return command
}
func newDeployCommand() *cobra.Command {
var id string
command := &cobra.Command{
Use: "deploy",
Short: "部署指定域名的当前证书",
RunE: func(cmd *cobra.Command, args []string) error {
if strings.TrimSpace(id) == "" {
return errors.New("域名 ID 不能为空")
}
service, err := openApp(cmd.Context())
if err != nil {
return err
}
defer service.Close()
result, err := service.Workflow.DeployCurrent(cmd.Context(), id)
if err != nil {
return err
}
return printJSON(cmd, result)
},
}
command.Flags().StringVar(&id, "id", "", "域名 ID")
_ = command.MarkFlagRequired("id")
return command
}
func newLogsCommand() *cobra.Command {
var lines int
command := &cobra.Command{
Use: "logs",
Short: "查看服务日志",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
return err
}
if lines < 1 || lines > 1000 {
return errors.New("日志行数必须在 1 到 1000 之间")
}
path := filepath.Join(cfg.Paths.Log, "scert.log")
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("打开日志文件失败:%w", err)
}
defer file.Close()
values, err := tailLines(file, lines)
if err != nil {
return err
}
for _, value := range values {
if _, err := fmt.Fprintln(cmd.OutOrStdout(), value); err != nil {
return err
}
}
return nil
},
}
command.Flags().IntVar(&lines, "lines", 100, "显示最后多少行日志")
return command
}
func newConfigCommand() *cobra.Command {
command := &cobra.Command{Use: "config", Short: "查看和修改服务配置"}
command.AddCommand(newConfigShowCommand(), newConfigSetCommand(), newConfigValidateCommand())
return command
}
func newConfigShowCommand() *cobra.Command {
return &cobra.Command{
Use: "show",
Short: "查看脱敏后的配置",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
return err
}
return printJSON(cmd, safeConfigMap(cfg))
},
}
}
func newConfigValidateCommand() *cobra.Command {
return &cobra.Command{
Use: "validate",
Short: "校验服务配置",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
return err
}
if err := cfg.Validate(); err != nil {
return err
}
_, err = fmt.Fprintln(cmd.OutOrStdout(), "配置校验通过")
return err
},
}
}
func newConfigSetCommand() *cobra.Command {
var key, value string
command := &cobra.Command{
Use: "set",
Short: "修改允许调整的配置项",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
return err
}
if err := setConfigValue(&cfg, key, value); err != nil {
return err
}
if err := cfg.Save(resolveConfigPath()); err != nil {
return err
}
_, err = fmt.Fprintf(cmd.OutOrStdout(), "配置已更新:%s\n", key)
return err
},
}
command.Flags().StringVar(&key, "key", "", "配置项名称")
command.Flags().StringVar(&value, "value", "", "配置项值")
_ = command.MarkFlagRequired("key")
_ = command.MarkFlagRequired("value")
return command
}
func newBackupCommand() *cobra.Command {
var output string
command := &cobra.Command{
Use: "backup",
Short: "备份配置和 SQLite 数据库",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
return err
}
if strings.TrimSpace(output) == "" {
output = filepath.Join(cfg.Paths.Backup, "scert-"+time.Now().UTC().Format("20060102-150405.000000000"))
}
output = filepath.Clean(output)
if err := ensureBackupDestination(output); err != nil {
return err
}
if err := os.MkdirAll(output, 0o700); err != nil {
return fmt.Errorf("创建备份目录失败:%w", err)
}
if err := copyFileExclusive(resolveConfigPath(), filepath.Join(output, "scert.json"), 0o600); err != nil {
return err
}
if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" {
if err := copyFileExclusive(cfg.Database.DSN, filepath.Join(output, "scert.db"), 0o600); err != nil {
return err
}
}
_, err = fmt.Fprintf(cmd.OutOrStdout(), "备份已创建:%s\n", output)
return err
},
}
command.Flags().StringVar(&output, "output", "", "备份目录")
return command
}
func newRestoreCommand() *cobra.Command {
var input string
command := &cobra.Command{
Use: "restore",
Short: "恢复 SQLite 数据库备份",
RunE: func(cmd *cobra.Command, args []string) error {
input, err := validateRestoreInput(input)
if err != nil {
return err
}
configFile := filepath.Join(input, "scert.json")
cfg, err := config.Load(configFile)
if err != nil {
return fmt.Errorf("读取备份配置失败:%w", err)
}
currentPath := filepath.Clean(resolveConfigPath())
_, currentConfigErr := config.Load(currentPath)
if currentConfigErr != nil && !errors.Is(currentConfigErr, os.ErrNotExist) {
return fmt.Errorf("读取当前配置失败:%w", currentConfigErr)
}
if info, statErr := os.Stat(currentPath); statErr == nil && !info.Mode().IsRegular() {
return errors.New("当前配置路径不是普通文件")
} else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return fmt.Errorf("检查当前配置失败:%w", statErr)
}
databaseSource := filepath.Join(input, "scert.db")
databaseSourceInfo, databaseSourceErr := os.Stat(databaseSource)
databaseSourceExists := databaseSourceErr == nil
if databaseSourceErr != nil && !errors.Is(databaseSourceErr, os.ErrNotExist) {
return fmt.Errorf("检查备份数据库失败:%w", databaseSourceErr)
}
if databaseSourceExists && !databaseSourceInfo.Mode().IsRegular() {
return errors.New("备份数据库不是普通文件")
}
if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && databaseSourceExists {
if samePath(databaseSource, cfg.Database.DSN) {
return errors.New("备份数据库与当前数据库路径相同")
}
if err := ensureParentDirectory(cfg.Database.DSN); err != nil {
return fmt.Errorf("创建当前数据库父目录失败:%w", err)
}
if databaseTargetInfo, statErr := os.Stat(cfg.Database.DSN); statErr == nil && !databaseTargetInfo.Mode().IsRegular() {
return errors.New("当前数据库不是普通文件")
} else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return fmt.Errorf("检查当前数据库失败:%w", statErr)
}
}
configBackupPath := ""
if isRegularFile(currentPath) {
configBackupPath = currentPath + ".before-restore-" + time.Now().UTC().Format("20060102-150405.000000000")
if err := copyFileExclusive(currentPath, configBackupPath, 0o600); err != nil {
return err
}
}
databaseBackupPath := ""
if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && databaseSourceExists && isRegularFile(cfg.Database.DSN) {
databaseBackupPath = cfg.Database.DSN + ".before-restore-" + time.Now().UTC().Format("20060102-150405.000000000")
if err := copyFileExclusive(cfg.Database.DSN, databaseBackupPath, 0o600); err != nil {
return err
}
}
if err := cfg.Save(currentPath); err != nil {
return err
}
if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && databaseSourceExists {
if err := copyFile(databaseSource, cfg.Database.DSN, 0o600); err != nil {
if configBackupPath != "" {
_ = copyFile(configBackupPath, currentPath, 0o600)
}
if databaseBackupPath != "" {
_ = copyFile(databaseBackupPath, cfg.Database.DSN, 0o600)
}
return fmt.Errorf("恢复 SQLite 数据库失败:%w", err)
}
}
_, err = fmt.Fprintf(cmd.OutOrStdout(), "恢复已完成:%s\n", input)
return err
},
}
command.Flags().StringVar(&input, "input", "", "备份目录")
_ = command.MarkFlagRequired("input")
return command
}
func openApp(ctx context.Context) (*app.App, error) {
cfg, err := loadConfig()
if err != nil {
return nil, err
}
return app.NewWithConfigPath(ctx, cfg, resolveConfigPath())
}
func tailLines(reader io.Reader, count int) ([]string, error) {
values := make([]string, 0, count)
scanner := bufio.NewScanner(reader)
scanner.Buffer(make([]byte, 4096), 1<<20)
for scanner.Scan() {
if len(values) == count {
copy(values, values[1:])
values[len(values)-1] = scanner.Text()
continue
}
values = append(values, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("读取日志失败:%w", err)
}
return values, nil
}
func safeConfigMap(cfg config.Config) map[string]any {
data, _ := json.Marshal(cfg)
result := make(map[string]any)
_ = json.Unmarshal(data, &result)
if admin, ok := result["admin"].(map[string]any); ok {
if _, exists := admin["password_hash"]; exists {
admin["password_hash"] = "已配置"
}
}
return result
}
func setConfigValue(cfg *config.Config, key, value string) error {
if cfg == nil {
return errors.New("配置不能为空")
}
key = strings.ToLower(strings.TrimSpace(key))
value = strings.TrimSpace(value)
if value == "" {
return errors.New("配置值不能为空")
}
parseBool := func() (bool, error) { return strconv.ParseBool(value) }
parseInt := func() (int, error) { return strconv.Atoi(value) }
switch key {
case "server.host":
cfg.Server.Host = value
case "server.port":
parsed, err := parseInt()
if err != nil {
return fmt.Errorf("端口格式无效:%w", err)
}
cfg.Server.Port = parsed
case "server.https_mode":
cfg.Server.HTTPSMode = value
case "web.enabled":
parsed, err := parseBool()
if err != nil {
return fmt.Errorf("管理页面开关格式无效:%w", err)
}
cfg.Web.Enabled = parsed
case "web.hostname":
cfg.Web.Hostname = value
case "web.public_ip":
cfg.Web.PublicIP = value
case "paths.install":
cfg.Paths.Install = value
case "paths.certificate":
cfg.Paths.Certificate = value
case "paths.config":
cfg.Paths.Config = value
case "paths.data":
cfg.Paths.Data = value
case "paths.log":
cfg.Paths.Log = value
case "paths.backup":
cfg.Paths.Backup = value
case "acme.environment":
cfg.ACME.Environment = value
case "acme.account_email":
cfg.ACME.AccountEmail = value
case "acme.renewal_threshold_days":
parsed, err := parseInt()
if err != nil {
return fmt.Errorf("续期阈值格式无效:%w", err)
}
cfg.ACME.RenewalThresholdDays = parsed
case "dns.provider":
cfg.DNS.Provider = value
case "dns.credential_ref":
cfg.DNS.CredentialRef = value
case "dns.verification_state":
cfg.DNS.VerificationState = value
case "notification.http_enabled":
parsed, err := parseBool()
if err != nil {
return fmt.Errorf("HTTP 通知开关格式无效:%w", err)
}
cfg.Notification.HTTPEnabled = parsed
case "notification.smtp_enabled":
parsed, err := parseBool()
if err != nil {
return fmt.Errorf("SMTP 通知开关格式无效:%w", err)
}
cfg.Notification.SMTPEnabled = parsed
case "notification.provider":
cfg.Notification.Provider = value
case "notification.endpoint":
cfg.Notification.Endpoint = value
case "notification.http_path":
cfg.Notification.HTTPPath = value
case "notification.http_login_path":
cfg.Notification.HTTPLoginPath = value
case "notification.http_auth_mode":
cfg.Notification.HTTPAuthMode = value
case "notification.http_credential_ref":
cfg.Notification.HTTPCredentialRef = value
case "notification.event_mode":
cfg.Notification.EventMode = value
case "notification.sender_name":
cfg.Notification.SenderName = value
case "notification.sender_email":
cfg.Notification.SenderEmail = value
case "notification.recipients":
cfg.Notification.Recipients = splitCommaValues(value)
case "notification.timeout_secs":
parsed, err := parseInt()
if err != nil {
return fmt.Errorf("通知超时时间格式无效:%w", err)
}
cfg.Notification.TimeoutSecs = parsed
default:
return fmt.Errorf("不允许通过命令行修改配置项:%s", key)
}
return cfg.Validate()
}
func splitCommaValues(value string) []string {
parts := strings.Split(value, ",")
result := make([]string, 0, len(parts))
for _, part := range parts {
part = strings.TrimSpace(part)
if part != "" {
result = append(result, part)
}
}
return result
}
func copyFile(source, target string, mode os.FileMode) error {
input, err := os.Open(source)
if err != nil {
return fmt.Errorf("打开文件失败:%w", err)
}
defer input.Close()
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return fmt.Errorf("创建目标目录失败:%w", err)
}
output, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
if err != nil {
return fmt.Errorf("创建目标文件失败:%w", err)
}
if _, err := io.Copy(output, input); err != nil {
_ = output.Close()
return fmt.Errorf("复制文件失败:%w", err)
}
if err := output.Close(); err != nil {
return fmt.Errorf("关闭目标文件失败:%w", err)
}
return os.Chmod(target, mode)
}
func copyFileExclusive(source, target string, mode os.FileMode) error {
input, err := os.Open(source)
if err != nil {
return fmt.Errorf("打开文件失败:%w", err)
}
defer input.Close()
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return fmt.Errorf("创建目标目录失败:%w", err)
}
output, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
if err != nil {
return fmt.Errorf("创建目标文件失败:%w", err)
}
if _, err := io.Copy(output, input); err != nil {
_ = output.Close()
return fmt.Errorf("复制文件失败:%w", err)
}
if err := output.Close(); err != nil {
return fmt.Errorf("关闭目标文件失败:%w", err)
}
return os.Chmod(target, mode)
}
func ensureBackupDestination(path string) error {
if strings.TrimSpace(path) == "" || path == "." {
return errors.New("备份目录不能为空")
}
if _, err := os.Stat(path); err == nil {
return fmt.Errorf("备份目录已存在,为避免覆盖原备份请更换路径:%s", path)
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("检查备份目录失败:%w", err)
}
return nil
}
func validateRestoreInput(path string) (string, error) {
path = filepath.Clean(strings.TrimSpace(path))
if path == "." || path == "" {
return "", errors.New("备份目录不能为空")
}
info, err := os.Stat(path)
if err != nil {
return "", fmt.Errorf("检查备份目录失败:%w", err)
}
if !info.IsDir() {
return "", errors.New("备份路径必须是目录")
}
configFile := filepath.Join(path, "scert.json")
if !isRegularFile(configFile) {
return "", errors.New("备份目录缺少有效的 scert.json 文件")
}
return path, nil
}
func isRegularFile(path string) bool {
info, err := os.Lstat(path)
return err == nil && info.Mode().IsRegular()
}
func ensureParentDirectory(path string) error {
parent := filepath.Dir(path)
info, err := os.Stat(parent)
if err != nil {
return fmt.Errorf("目标目录不可用:%w", err)
}
if !info.IsDir() {
return errors.New("目标父路径不是目录")
}
return nil
}
func samePath(left, right string) bool {
leftAbs, leftErr := filepath.Abs(filepath.Clean(left))
rightAbs, rightErr := filepath.Abs(filepath.Clean(right))
if leftErr != nil || rightErr != nil {
return false
}
return strings.EqualFold(leftAbs, rightAbs)
}
@@ -0,0 +1,65 @@
package cli
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestValidateRestoreInputRequiresDirectoryAndConfig(t *testing.T) {
if _, err := validateRestoreInput(t.TempDir()); err == nil {
t.Fatal("缺少配置文件的备份目录未被拒绝")
}
file := filepath.Join(t.TempDir(), "backup.txt")
if err := os.WriteFile(file, []byte("backup"), 0o600); err != nil {
t.Fatalf("创建测试文件失败:%v", err)
}
if _, err := validateRestoreInput(file); err == nil {
t.Fatal("普通文件路径未被拒绝")
}
}
func TestValidateRestoreInputAcceptsCompleteDirectory(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "scert.json"), []byte("{}"), 0o600); err != nil {
t.Fatalf("创建测试配置失败:%v", err)
}
result, err := validateRestoreInput(dir)
if err != nil {
t.Fatalf("有效备份目录未通过校验:%v", err)
}
if !strings.EqualFold(result, filepath.Clean(dir)) {
t.Fatalf("备份目录未规范化:%s", result)
}
}
func TestCopyFileExclusiveRefusesOverwrite(t *testing.T) {
dir := t.TempDir()
source := filepath.Join(dir, "source")
target := filepath.Join(dir, "target")
if err := os.WriteFile(source, []byte("new"), 0o600); err != nil {
t.Fatalf("创建源文件失败:%v", err)
}
if err := os.WriteFile(target, []byte("old"), 0o600); err != nil {
t.Fatalf("创建目标文件失败:%v", err)
}
if err := copyFileExclusive(source, target, 0o600); err == nil {
t.Fatal("排他复制覆盖了已有文件")
}
data, err := os.ReadFile(target)
if err != nil {
t.Fatalf("读取目标文件失败:%v", err)
}
if string(data) != "old" {
t.Fatalf("目标文件内容被修改:%s", data)
}
}
func TestSamePathNormalizesAbsolutePaths(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "file")
if !samePath(path, filepath.Join(dir, ".", "file")) {
t.Fatal("相同路径未被识别")
}
}
+75
View File
@@ -0,0 +1,75 @@
package cli
import (
"strings"
"testing"
"git.pcux.cn/xuans/Scert/backend/internal/config"
)
func TestTailLinesReturnsOnlyLatestEntries(t *testing.T) {
values, err := tailLines(strings.NewReader("one\ntwo\nthree\n"), 2)
if err != nil {
t.Fatalf("读取日志尾部失败:%v", err)
}
if strings.Join(values, ",") != "two,three" {
t.Fatalf("日志尾部不正确:%v", values)
}
}
func TestSafeConfigMapRedactsPasswordHash(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.Admin.PasswordHash = "secret-hash"
result := safeConfigMap(cfg)
admin, ok := result["admin"].(map[string]any)
if !ok {
t.Fatalf("脱敏配置缺少管理员字段:%v", result)
}
if admin["password_hash"] != "已配置" {
t.Fatalf("密码摘要未脱敏:%v", admin["password_hash"])
}
}
func TestSetConfigValueUpdatesAndValidatesAllowedFields(t *testing.T) {
cfg := config.Default(t.TempDir())
if err := setConfigValue(&cfg, "server.port", "5200"); err != nil {
t.Fatalf("设置端口失败:%v", err)
}
if cfg.Server.Port != 5200 {
t.Fatalf("端口未更新:%d", cfg.Server.Port)
}
if err := setConfigValue(&cfg, "notification.recipients", "a@example.com, b@example.com"); err != nil {
t.Fatalf("设置收件人失败:%v", err)
}
if len(cfg.Notification.Recipients) != 2 {
t.Fatalf("收件人未拆分:%v", cfg.Notification.Recipients)
}
if err := setConfigValue(&cfg, "notification.http_login_path", "/api/login"); err != nil {
t.Fatalf("设置 HTTP 登录路径失败:%v", err)
}
if cfg.Notification.HTTPLoginPath != "/api/login" {
t.Fatalf("HTTP 登录路径未更新:%s", cfg.Notification.HTTPLoginPath)
}
if err := setConfigValue(&cfg, "admin.password_hash", "plain"); err == nil {
t.Fatal("不应允许直接修改密码摘要")
}
}
func TestRootIncludesOperationalCommands(t *testing.T) {
root := newRootCommand()
for _, name := range []string{"certificate", "renew", "deploy", "logs", "config", "backup", "restore"} {
if root.CommandPath() == name || root.Commands() == nil {
t.Fatalf("根命令状态异常:%s", name)
}
found := false
for _, command := range root.Commands() {
if command.Name() == name {
found = true
break
}
}
if !found {
t.Fatalf("缺少命令:%s", name)
}
}
}
+72 -8
View File
@@ -68,7 +68,9 @@ func newRootCommand() *cobra.Command {
root.PersistentFlags().StringVar(&baseDir, "base-dir", "", "Windows 默认安装根目录")
root.AddCommand(
&cobra.Command{Use: "version", Short: "显示版本信息", Run: func(cmd *cobra.Command, args []string) { cmd.Printf("Scert %s\n", version) }},
newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(), newServerCommand(), newSSHKeyCommand(),
newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(), newCertificateCommand(),
newRenewCommand(), newDeployCommand(), newLogsCommand(), newConfigCommand(), newBackupCommand(), newRestoreCommand(),
newServerCommand(), newSSHKeyCommand(),
)
localizeHelpFlags(root)
return root
@@ -111,11 +113,15 @@ func newInitCommand() *cobra.Command {
func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command {
var (
adminUsername, adminEmail, adminPassword, emailProvider, emailEndpoint string
recipients, dnsProvider, dnsCredentialRef, certificateRoot string
webHostname, webPublicIP, httpsMode string
serverPort int
dnsVerified, webEnabled bool
adminUsername, adminEmail, adminPassword, emailProvider, emailEndpoint string
emailHTTPPath, emailHTTPLoginPath, emailHTTPAuthMode, emailHTTPCredentialRef, emailHTTPHeaders string
emailEventMode, emailSenderName, emailSenderEmail, emailRetryIntervals string
recipients, dnsProvider, dnsCredentialRef, certificateRoot string
webHostname, webPublicIP, httpsMode string
serverPort, emailTimeoutSecs, emailRetryCount int
emailHTTPEnabled, emailIncludeDeploymentDetails bool
emailIncludeCertificateSerial, emailIncludeManagementURL bool
dnsVerified, webEnabled bool
)
command := &cobra.Command{Use: "init", Short: "交互式初始化配置", RunE: func(cmd *cobra.Command, args []string) error {
path := resolveConfigPath()
@@ -125,10 +131,26 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
return err
}
cfg := config.Default(baseDir)
emailHeaders, err := parseStringMap(emailHTTPHeaders)
if err != nil {
return fmt.Errorf("HTTP 自定义请求头格式无效:%w", err)
}
emailIntervals, err := splitInts(emailRetryIntervals)
if err != nil {
return fmt.Errorf("通知重试间隔格式无效:%w", err)
}
input := setup.Input{
AdminUsername: adminUsername, AdminEmail: adminEmail, AdminPassword: adminPassword, ServerPort: serverPort,
EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
EmailRecipients: splitValues(recipients), DNSProvider: dnsProvider, DNSCredentialRef: dnsCredentialRef,
EmailHTTPEnabled: emailHTTPEnabled,
EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
EmailHTTPPath: emailHTTPPath, EmailHTTPLoginPath: emailHTTPLoginPath, EmailHTTPAuthMode: emailHTTPAuthMode,
EmailHTTPCredentialRef: emailHTTPCredentialRef, EmailHTTPHeaders: emailHeaders,
EmailEventMode: emailEventMode, EmailIncludeDeploymentDetails: emailIncludeDeploymentDetails,
EmailIncludeCertificateSerial: emailIncludeCertificateSerial, EmailIncludeManagementURL: emailIncludeManagementURL,
EmailSenderName: emailSenderName, EmailSenderEmail: emailSenderEmail,
EmailTimeoutSecs: emailTimeoutSecs, EmailRetryCount: emailRetryCount,
EmailRetryIntervalsSecs: emailIntervals,
EmailRecipients: splitValues(recipients), DNSProvider: dnsProvider, DNSCredentialRef: dnsCredentialRef,
DNSVerified: dnsVerified, CertificateRoot: certificateRoot, WebHostname: webHostname,
WebPublicIP: webPublicIP, WebEnabled: webEnabled, HTTPSMode: httpsMode,
}
@@ -154,9 +176,24 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
command.Flags().StringVar(&adminEmail, "admin-email", "", "超级管理员绑定邮箱")
command.Flags().StringVar(&adminPassword, "admin-password", "", "超级管理员密码(仅建议临时使用参数,优先交互输入)")
command.Flags().IntVar(&serverPort, "server-port", 8080, "Scert 主服务端口")
command.Flags().BoolVar(&emailHTTPEnabled, "email-http-enabled", false, "是否启用 HTTP 邮件通知")
command.Flags().StringVar(&emailHTTPPath, "email-http-path", "/api/email/send", "HTTP 邮件通知请求路径")
command.Flags().StringVar(&emailHTTPLoginPath, "email-http-login-path", "/api/login", "HTTP 会话认证登录请求路径")
command.Flags().StringVar(&emailHTTPAuthMode, "email-http-auth-mode", "none", "HTTP 邮件通知认证方式:none、bearer、hmac_sha256、session")
command.Flags().StringVar(&emailHTTPCredentialRef, "email-http-credential-ref", "", "HTTP 邮件通知凭据引用")
command.Flags().StringVar(&emailHTTPHeaders, "email-http-headers", "", "HTTP 自定义请求头 JSON")
command.Flags().StringVar(&emailEventMode, "email-event-mode", "detailed", "通知事件模式:detailed、unified")
command.Flags().StringVar(&emailSenderName, "email-sender-name", "Scert", "通知发件人名称")
command.Flags().StringVar(&emailSenderEmail, "email-sender-email", "", "通知发件人地址,留空使用管理员邮箱")
command.Flags().BoolVar(&emailIncludeDeploymentDetails, "email-include-deployment-details", true, "是否发送服务器部署明细")
command.Flags().BoolVar(&emailIncludeCertificateSerial, "email-include-certificate-serial", true, "是否发送证书序列号")
command.Flags().BoolVar(&emailIncludeManagementURL, "email-include-management-url", true, "是否发送管理后台链接")
command.Flags().StringVar(&emailProvider, "email-provider", "", "第三方邮箱服务标识")
command.Flags().StringVar(&emailEndpoint, "email-endpoint", "", "第三方邮箱 API 地址")
command.Flags().StringVar(&recipients, "recipients", "", "通知收件人,多个地址用逗号分隔")
command.Flags().IntVar(&emailTimeoutSecs, "email-timeout-secs", 10, "通知请求超时时间(秒)")
command.Flags().IntVar(&emailRetryCount, "email-retry-count", 3, "通知失败重试次数")
command.Flags().StringVar(&emailRetryIntervals, "email-retry-intervals", "30,120,600", "通知重试间隔(秒,逗号分隔)")
command.Flags().StringVar(&dnsProvider, "dns-provider", "", "DNS API 服务商标识")
command.Flags().StringVar(&dnsCredentialRef, "dns-credential-ref", "", "DNS 凭据引用,不保存明文密钥")
command.Flags().BoolVar(&dnsVerified, "dns-verified", false, "DNS API 是否已通过外部验证测试")
@@ -315,6 +352,33 @@ func splitValues(value string) []string {
return strings.Split(value, ",")
}
func splitInts(value string) ([]int, error) {
if strings.TrimSpace(value) == "" {
return nil, nil
}
items := strings.Split(value, ",")
result := make([]int, 0, len(items))
for _, item := range items {
parsed, err := strconv.Atoi(strings.TrimSpace(item))
if err != nil {
return nil, fmt.Errorf("%q 不是有效数字", strings.TrimSpace(item))
}
result = append(result, parsed)
}
return result, nil
}
func parseStringMap(value string) (map[string]string, error) {
if strings.TrimSpace(value) == "" {
return nil, nil
}
var result map[string]string
if err := json.Unmarshal([]byte(value), &result); err != nil {
return nil, err
}
return result, nil
}
func newStatusCommand() *cobra.Command {
return &cobra.Command{Use: "status", Short: "查看服务状态", RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()