diff --git a/backend/cmd/scert-admin/main.go b/backend/cmd/scert-admin/main.go index 1c84b11..9c12754 100644 --- a/backend/cmd/scert-admin/main.go +++ b/backend/cmd/scert-admin/main.go @@ -4,6 +4,7 @@ import ( "context" "flag" "fmt" + "io" "os" "os/signal" "path/filepath" @@ -14,9 +15,17 @@ import ( "git.pcux.cn/xuans/Scert/backend/internal/config" ) +func writeSessionInfo(writer io.Writer, session admin.Session) { + fmt.Fprintln(writer, "Scert-admin 已启用临时密码重置入口,不监听独立网络端口。") + fmt.Fprintln(writer, "重置地址:", session.State.ResetURL) + fmt.Fprintln(writer, "一次性校验码已写入受保护的临时文件:", session.State.CodePath) + fmt.Fprintln(writer, "请使用 root 或 Scert 用户读取该文件;密码重置完成后文件会自动销毁。") + fmt.Fprintln(writer, "停止 Scert-admin 后入口将立即关闭;异常退出时入口会在租约过期后自动关闭。") +} func main() { baseDir := flag.String("base-dir", "", "Windows 默认安装根目录") configPath := flag.String("config", "", "配置文件路径") + codeOutput := flag.String("code-output", "", "一次性校验码文件路径") flag.Parse() path := *configPath if path == "" { @@ -27,16 +36,13 @@ func main() { fmt.Fprintln(os.Stderr, "读取配置失败:", err) os.Exit(1) } - controller := admin.New(cfg) + controller := admin.NewWithCodePath(cfg, *codeOutput) session, err := controller.Start() if err != nil { fmt.Fprintln(os.Stderr, "启用密码重置入口失败:", err) os.Exit(1) } - fmt.Println("Scert-admin 已启用临时密码重置入口,不监听独立网络端口。") - fmt.Println("重置地址:", session.State.ResetURL) - fmt.Println("一次性校验码:", session.Code) - fmt.Println("停止 Scert-admin 后入口将立即关闭;异常退出时入口会在租约过期后自动关闭。") + writeSessionInfo(os.Stdout, session) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() ticker := time.NewTicker(admin.RefreshInterval) diff --git a/backend/cmd/scert-admin/main_test.go b/backend/cmd/scert-admin/main_test.go new file mode 100644 index 0000000..74db9c3 --- /dev/null +++ b/backend/cmd/scert-admin/main_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "bytes" + "strings" + "testing" + + "git.pcux.cn/xuans/Scert/backend/internal/admin" +) + +func TestSessionInfoDoesNotExposeResetCode(t *testing.T) { + const secretCode = "ABCDE-12345-FGHIJ" + var output bytes.Buffer + writeSessionInfo(&output, admin.Session{ + State: admin.State{ + ResetURL: "https://scert.example.test/reset", + CodePath: "/run/scert-admin/reset-code", + }, + Code: secretCode, + }) + if strings.Contains(output.String(), secretCode) { + t.Fatal("命令行输出不得包含一次性校验码") + } + if !strings.Contains(output.String(), "/run/scert-admin/reset-code") { + t.Fatal("命令行输出必须提示受保护校验码文件路径") + } +} diff --git a/backend/internal/admin/code_protection_unix.go b/backend/internal/admin/code_protection_unix.go new file mode 100644 index 0000000..d67c4c9 --- /dev/null +++ b/backend/internal/admin/code_protection_unix.go @@ -0,0 +1,7 @@ +//go:build !windows + +package admin + +func protectCodeFile(string) error { + return nil +} diff --git a/backend/internal/admin/code_protection_windows.go b/backend/internal/admin/code_protection_windows.go new file mode 100644 index 0000000..1d66633 --- /dev/null +++ b/backend/internal/admin/code_protection_windows.go @@ -0,0 +1,100 @@ +//go:build windows + +package admin + +import ( + "fmt" + "runtime" + + "golang.org/x/sys/windows" +) + +func protectCodeFile(path string) error { + currentSID, err := currentProcessUserSID() + if err != nil { + return err + } + systemSID, err := windows.CreateWellKnownSid(windows.WinLocalSystemSid) + if err != nil { + return fmt.Errorf("创建系统账户安全标识失败:%w", err) + } + adminSID, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid) + if err != nil { + return fmt.Errorf("创建本地管理员组安全标识失败:%w", err) + } + + var pinner runtime.Pinner + pinner.Pin(currentSID) + pinner.Pin(systemSID) + pinner.Pin(adminSID) + defer pinner.Unpin() + + readDelete := windows.ACCESS_MASK(windows.FILE_GENERIC_READ | windows.DELETE | windows.READ_CONTROL | windows.SYNCHRONIZE) + fullControl := windows.ACCESS_MASK(windows.FILE_GENERIC_READ | + windows.FILE_GENERIC_WRITE | + windows.FILE_GENERIC_EXECUTE | + windows.DELETE | + windows.READ_CONTROL | + windows.WRITE_DAC | + windows.WRITE_OWNER | + windows.SYNCHRONIZE) + entries := []windows.EXPLICIT_ACCESS{ + { + AccessPermissions: readDelete, + AccessMode: windows.SET_ACCESS, + Inheritance: windows.NO_INHERITANCE, + Trustee: windows.TRUSTEE{ + TrusteeForm: windows.TRUSTEE_IS_SID, + TrusteeType: windows.TRUSTEE_IS_USER, + TrusteeValue: windows.TrusteeValueFromSID(currentSID), + }, + }, + { + AccessPermissions: fullControl, + AccessMode: windows.SET_ACCESS, + Inheritance: windows.NO_INHERITANCE, + Trustee: windows.TRUSTEE{ + TrusteeForm: windows.TRUSTEE_IS_SID, + TrusteeType: windows.TRUSTEE_IS_WELL_KNOWN_GROUP, + TrusteeValue: windows.TrusteeValueFromSID(systemSID), + }, + }, + { + AccessPermissions: fullControl, + AccessMode: windows.SET_ACCESS, + Inheritance: windows.NO_INHERITANCE, + Trustee: windows.TRUSTEE{ + TrusteeForm: windows.TRUSTEE_IS_SID, + TrusteeType: windows.TRUSTEE_IS_ALIAS, + TrusteeValue: windows.TrusteeValueFromSID(adminSID), + }, + }, + } + acl, err := windows.ACLFromEntries(entries, nil) + if err != nil { + return fmt.Errorf("创建校验码文件访问控制列表失败:%w", err) + } + if err := windows.SetNamedSecurityInfo( + path, + windows.SE_FILE_OBJECT, + windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, + nil, + nil, + acl, + nil, + ); err != nil { + return fmt.Errorf("应用校验码文件访问控制列表失败:%w", err) + } + return nil +} + +func currentProcessUserSID() (*windows.SID, error) { + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + return nil, fmt.Errorf("读取当前服务账户安全标识失败:%w", err) + } + if user == nil || user.User.Sid == nil { + return nil, fmt.Errorf("当前服务账户没有有效的安全标识") + } + return user.User.Sid, nil +} diff --git a/backend/internal/admin/server.go b/backend/internal/admin/server.go index e9416c0..82cef5d 100644 --- a/backend/internal/admin/server.go +++ b/backend/internal/admin/server.go @@ -20,6 +20,7 @@ import ( const ( ResetPath = "/reset" stateFileName = "scert-admin-reset.json" + codeFileName = "scert-admin-reset-code" defaultLease = 90 * time.Second RefreshInterval = 30 * time.Second ) @@ -30,6 +31,7 @@ type State struct { Active bool `json:"active"` ResetURL string `json:"reset_url"` CodeHash string `json:"code_hash"` + CodePath string `json:"code_path,omitempty"` ProcessID int `json:"process_id"` StartedAt time.Time `json:"started_at"` ExpiresAt time.Time `json:"expires_at"` @@ -43,15 +45,24 @@ type Session struct { type Controller struct { config config.Config statePath string + codePath string leaseDuration time.Duration now func() time.Time state State } func New(cfg config.Config) *Controller { + return NewWithCodePath(cfg, "") +} + +func NewWithCodePath(cfg config.Config, codePath string) *Controller { + if strings.TrimSpace(codePath) == "" { + codePath = CodePath(cfg.Paths.Data) + } return &Controller{ config: cfg, statePath: StatePath(cfg.Paths.Data), + codePath: codePath, leaseDuration: defaultLease, now: time.Now, } @@ -61,6 +72,10 @@ func StatePath(dataDir string) string { return filepath.Join(dataDir, stateFileName) } +func CodePath(dataDir string) string { + return filepath.Join(dataDir, codeFileName) +} + func (c *Controller) Start() (Session, error) { if c == nil { return Session{}, fmt.Errorf("Scert-admin 控制器不能为空") @@ -72,9 +87,11 @@ func (c *Controller) Start() (Session, error) { if resetURL == "" { return Session{}, fmt.Errorf("未配置管理页面域名或公网 IP,无法生成密码重置地址") } - if active, err := IsActive(c.statePath, c.now()); err != nil { + active, err := IsActive(c.statePath, c.now()) + if err != nil { return Session{}, err - } else if active { + } + if active { return Session{}, fmt.Errorf("密码重置入口已经启用") } code, err := generateCode() @@ -83,10 +100,14 @@ func (c *Controller) Start() (Session, error) { } now := c.now().UTC() c.state = State{ - Active: true, ResetURL: resetURL, CodeHash: hashCode(code), ProcessID: os.Getpid(), + Active: true, ResetURL: resetURL, CodeHash: hashCode(code), CodePath: c.codePath, ProcessID: os.Getpid(), StartedAt: now, ExpiresAt: now.Add(c.leaseDuration), } + if err := writeCodeFile(c.codePath, code); err != nil { + return Session{}, err + } if err := writeState(c.statePath, c.state); err != nil { + _ = removeCodeFile(c.codePath) return Session{}, err } return Session{State: c.state, Code: code}, nil @@ -102,6 +123,7 @@ func (c *Controller) Refresh() error { } if !latest.Active || latest.CodeHash != c.state.CodeHash || !c.now().UTC().Before(latest.ExpiresAt) { c.state.Active = false + _ = removeCodeFile(codePathForState(c.statePath, latest)) return ErrResetSessionClosed } c.state = latest @@ -113,9 +135,14 @@ func (c *Controller) Stop() error { if c == nil || !c.state.Active { return nil } - c.state.Active = false - c.state.ExpiresAt = c.now().UTC() - return writeState(c.statePath, c.state) + state := c.state + state.Active = false + state.ExpiresAt = c.now().UTC() + if err := writeState(c.statePath, state); err != nil { + return err + } + c.state = state + return removeCodeFile(codePathForState(c.statePath, state)) } func IsActive(path string, now time.Time) (bool, error) { @@ -126,7 +153,13 @@ func IsActive(path string, now time.Time) (bool, error) { if err != nil { return false, err } - return state.Active && now.UTC().Before(state.ExpiresAt), nil + active := state.Active && now.UTC().Before(state.ExpiresAt) + if !active { + if err := removeCodeFile(codePathForState(path, state)); err != nil { + return false, err + } + } + return active, nil } func VerifyCode(path, code string, now time.Time) (State, error) { @@ -135,6 +168,7 @@ func VerifyCode(path, code string, now time.Time) (State, error) { return State{}, err } if !state.Active || state.CodeHash == "" || !now.UTC().Before(state.ExpiresAt) { + _ = removeCodeFile(codePathForState(path, state)) return State{}, ErrResetSessionClosed } expected := hashCode(code) @@ -150,6 +184,7 @@ func Consume(path string, session State, now time.Time) error { return err } if !latest.Active || latest.CodeHash == "" || !now.UTC().Before(latest.ExpiresAt) { + _ = removeCodeFile(codePathForState(path, latest)) return ErrResetSessionClosed } if subtle.ConstantTimeCompare([]byte(latest.CodeHash), []byte(session.CodeHash)) != 1 { @@ -158,7 +193,10 @@ func Consume(path string, session State, now time.Time) error { latest.Active = false latest.CodeHash = "" latest.ExpiresAt = now.UTC() - return writeState(path, latest) + if err := writeState(path, latest); err != nil { + return err + } + return removeCodeFile(codePathForState(path, latest)) } func ReadState(path string) (State, error) { @@ -200,6 +238,56 @@ func writeState(path string, state State) error { return nil } +func writeCodeFile(path, code string) error { + if strings.TrimSpace(path) == "" { + return fmt.Errorf("未配置一次性校验码文件路径") + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return fmt.Errorf("创建一次性校验码目录失败:%w", err) + } + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return fmt.Errorf("创建一次性校验码文件失败:%w", err) + } + success := false + defer func() { + _ = file.Close() + if !success { + _ = os.Remove(path) + } + }() + if err := file.Chmod(0o600); err != nil { + return fmt.Errorf("设置一次性校验码文件权限失败:%w", err) + } + if _, err := file.WriteString(code + "\n"); err != nil { + return fmt.Errorf("写入一次性校验码文件失败:%w", err) + } + if err := file.Sync(); err != nil { + return fmt.Errorf("刷新一次性校验码文件失败:%w", err) + } + if err := protectCodeFile(path); err != nil { + return fmt.Errorf("保护一次性校验码文件失败:%w", err) + } + success = true + return nil +} + +func removeCodeFile(path string) error { + if strings.TrimSpace(path) == "" { + return nil + } + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("销毁一次性校验码文件失败:%w", err) + } + return nil +} + +func codePathForState(statePath string, state State) string { + if strings.TrimSpace(state.CodePath) != "" { + return state.CodePath + } + return CodePath(filepath.Dir(statePath)) +} func generateCode() (string, error) { buffer := make([]byte, 10) if _, err := rand.Read(buffer); err != nil { diff --git a/backend/internal/admin/server_test.go b/backend/internal/admin/server_test.go index bba154f..ebfdbc8 100644 --- a/backend/internal/admin/server_test.go +++ b/backend/internal/admin/server_test.go @@ -24,10 +24,12 @@ func TestScertAdminSystemdUnitKeepsManualOnlyPolicy(t *testing.T) { unit := activeUnitText(string(data)) for _, required := range []string{ - "Documentation=file:///scert/docs/Scert-admin服务管理说明.md", + "Documentation=file:///scert/docs/Scert-admin-service-management.md", "User=Scert", "Group=Scert", - "ExecStart=/scert/scert-admin --config /scert/conf/scert.json", + "RuntimeDirectory=scert-admin", + "RuntimeDirectoryMode=0700", + "ExecStart=/scert/scert-admin --config /scert/conf/scert.json --code-output /run/scert-admin/reset-code", "Restart=no", "RuntimeMaxSec=30min", "UMask=0077", @@ -131,6 +133,109 @@ func TestResetCodeCanOnlyBeConsumedOnce(t *testing.T) { } } +func TestControllerWritesAndDestroysProtectedCodeFile(t *testing.T) { + cfg := config.Default(t.TempDir()) + cfg.SetupReady = true + cfg.Web.Hostname = "scert.example.test" + codePath := filepath.Join(t.TempDir(), "runtime", "reset-code") + controller := NewWithCodePath(cfg, codePath) + + session, err := controller.Start() + if err != nil { + t.Fatalf("启动密码重置入口失败:%v", err) + } + content, err := os.ReadFile(codePath) + if err != nil { + t.Fatalf("读取受保护校验码文件失败:%v", err) + } + if string(content) != session.Code+"\n" { + t.Fatalf("校验码文件内容错误:%q", string(content)) + } + if runtime.GOOS != "windows" { + info, err := os.Stat(codePath) + if err != nil { + t.Fatalf("读取校验码文件属性失败:%v", err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("校验码文件权限错误:%o", info.Mode().Perm()) + } + } + if err := controller.Stop(); err != nil { + t.Fatalf("停止密码重置入口失败:%v", err) + } + if _, err := os.Stat(codePath); !os.IsNotExist(err) { + t.Fatalf("停止服务后校验码文件必须销毁,当前错误:%v", err) + } +} + +func TestConsumeDestroysCodeFile(t *testing.T) { + cfg := config.Default(t.TempDir()) + cfg.SetupReady = true + cfg.Web.Hostname = "scert.example.test" + codePath := filepath.Join(t.TempDir(), "runtime", "reset-code") + controller := NewWithCodePath(cfg, codePath) + now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC) + controller.now = func() time.Time { return now } + + session, err := controller.Start() + if err != nil { + t.Fatalf("启动密码重置入口失败:%v", err) + } + verified, err := VerifyCode(StatePath(cfg.Paths.Data), session.Code, now) + if err != nil { + t.Fatalf("校验一次性校验码失败:%v", err) + } + if err := Consume(StatePath(cfg.Paths.Data), verified, now); err != nil { + t.Fatalf("消费一次性校验码失败:%v", err) + } + if _, err := os.Stat(codePath); !os.IsNotExist(err) { + t.Fatalf("校验码消费后文件必须销毁,当前错误:%v", err) + } +} + +func TestExpiredLeaseDestroysCodeFile(t *testing.T) { + dataDir := t.TempDir() + statePath := StatePath(dataDir) + codePath := CodePath(dataDir) + if err := writeCodeFile(codePath, "expired-code"); err != nil { + t.Fatalf("创建过期校验码文件失败:%v", err) + } + now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC) + if err := writeState(statePath, State{Active: true, CodePath: codePath, ExpiresAt: now.Add(-time.Second)}); err != nil { + t.Fatalf("写入过期租约失败:%v", err) + } + active, err := IsActive(statePath, now) + if err != nil || active { + t.Fatalf("过期租约必须失效:active=%t err=%v", active, err) + } + if _, err := os.Stat(codePath); !os.IsNotExist(err) { + t.Fatalf("租约失效后校验码文件必须销毁,当前错误:%v", err) + } +} + +func TestControllerDoesNotOverwriteExistingCodeFile(t *testing.T) { + cfg := config.Default(t.TempDir()) + cfg.SetupReady = true + cfg.Web.Hostname = "scert.example.test" + codePath := filepath.Join(t.TempDir(), "runtime", "reset-code") + if err := os.MkdirAll(filepath.Dir(codePath), 0o700); err != nil { + t.Fatalf("创建测试目录失败:%v", err) + } + const existing = "existing-code\n" + if err := os.WriteFile(codePath, []byte(existing), 0o600); err != nil { + t.Fatalf("创建已有校验码文件失败:%v", err) + } + if _, err := NewWithCodePath(cfg, codePath).Start(); err == nil { + t.Fatal("已有校验码文件时不允许覆盖") + } + content, err := os.ReadFile(codePath) + if err != nil { + t.Fatalf("读取已有校验码文件失败:%v", err) + } + if string(content) != existing { + t.Fatalf("已有校验码文件被修改:%q", string(content)) + } +} func activeUnitText(unit string) string { lines := strings.Split(unit, "\n") active := make([]string, 0, len(lines)) @@ -143,3 +248,28 @@ func activeUnitText(unit string) string { } return strings.Join(active, "\n") } + +func TestConsumeExpiredSessionRemovesCodeFile(t *testing.T) { + baseDir := t.TempDir() + statePath := filepath.Join(baseDir, "state.json") + codePath := filepath.Join(baseDir, "reset-code") + now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC) + if err := os.WriteFile(codePath, []byte("expired-code\n"), 0o600); err != nil { + t.Fatalf("创建过期校验码文件失败:%v", err) + } + state := State{ + Active: true, + CodeHash: hashCode("expired-code"), + CodePath: codePath, + ExpiresAt: now.Add(-time.Second), + } + if err := writeState(statePath, state); err != nil { + t.Fatalf("写入过期会话失败:%v", err) + } + if err := Consume(statePath, state, now); err != ErrResetSessionClosed { + t.Fatalf("消费过期会话应返回关闭错误:%v", err) + } + if _, err := os.Stat(codePath); !os.IsNotExist(err) { + t.Fatalf("消费过期会话后必须销毁校验码文件:%v", err) + } +} diff --git a/backend/internal/admin/service_units_test.go b/backend/internal/admin/service_units_test.go index 952403e..2ab93b5 100644 --- a/backend/internal/admin/service_units_test.go +++ b/backend/internal/admin/service_units_test.go @@ -20,7 +20,7 @@ func TestScertSystemdUnitPolicy(t *testing.T) { } unit := activeUnitText(string(data)) for _, required := range []string{ - "Documentation=file:///scert/docs/Scert服务管理说明.md", + "Documentation=file:///scert/docs/Scert-service-management.md", "User=Scert", "Group=Scert", "ExecStart=/scert/scert --config /scert/conf/scert.json serve", diff --git a/backend/internal/app/app.go b/backend/internal/app/app.go index b68f872..a7c90a0 100644 --- a/backend/internal/app/app.go +++ b/backend/internal/app/app.go @@ -100,7 +100,7 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string renewal := certificate.NewRenewalScheduler(repo, workflow, cfg.ACME.RenewalThresholdDays) server := httpapi.New(httpapi.Dependencies{ Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo, Servers: serverRepo, SSHKeys: sshKeys, - SetupDNS: dnsVerification, Firewall: firewall.NewManager(), + SetupDNS: dnsVerification, Secrets: secretStore, Firewall: firewall.NewManager(), IssueCertificate: workflow.IssueForHTTP, IssueSetupCertificate: func(ctx context.Context, request certificate.SetupCertificateRequest) (certificate.SavedResource, error) { return certificates.IssueForSetup(ctx, request) diff --git a/backend/internal/certificate/lego.go b/backend/internal/certificate/lego.go index 0c72f07..8a97103 100644 --- a/backend/internal/certificate/lego.go +++ b/backend/internal/certificate/lego.go @@ -28,11 +28,30 @@ func (u *AccountUser) GetRegistration() *acme.ExtendedAccount { return u.Registr func (u *AccountUser) GetPrivateKey() crypto.Signer { return u.PrivateKey } type LegoIssuer struct { - User *AccountUser - Provider challenge.Provider - Environment string - HTTPClient *http.Client - Now func() time.Time + User *AccountUser + Provider challenge.Provider + Environment string + PropagationTimeout time.Duration + PropagationInterval time.Duration + HTTPClient *http.Client + Now func() time.Time +} + +type propagationProvider struct { + challenge.Provider + timeout time.Duration + interval time.Duration +} + +func (p propagationProvider) Timeout() (time.Duration, time.Duration) { + return p.timeout, p.interval +} + +func withPropagationSettings(provider challenge.Provider, timeout, interval time.Duration) challenge.Provider { + if provider == nil || timeout <= 0 || interval <= 0 || interval > timeout { + return provider + } + return propagationProvider{Provider: provider, timeout: timeout, interval: interval} } func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resource, error) { @@ -66,7 +85,8 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc if err != nil { return Resource{}, fmt.Errorf("创建 ACME 客户端失败:%w", err) } - if err := client.Challenge.SetDNS01Provider(i.Provider); err != nil { + provider := withPropagationSettings(i.Provider, i.PropagationTimeout, i.PropagationInterval) + if err := client.Challenge.SetDNS01Provider(provider); err != nil { return Resource{}, fmt.Errorf("配置 DNS-01 验证失败:%w", err) } if i.User.Registration == nil { @@ -77,11 +97,14 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc i.User.Registration = account } issued, err := client.Certificate.Obtain(ctx, legoCertificate.ObtainRequest{ - Domains: domains, EmailAddresses: nonEmptyEmail(request.AccountEmail, i.User.Email), + Domains: domains, KeyType: certcrypto.RSA2048, Bundle: true, PreferredChain: request.PreferredChain, }) if err != nil { + if i.PropagationTimeout > 0 && i.PropagationInterval > 0 && i.PropagationInterval <= i.PropagationTimeout { + return Resource{}, fmt.Errorf("申请证书失败(DNS 传播等待时间 %s,检测间隔 %s):%w", i.PropagationTimeout, i.PropagationInterval, err) + } return Resource{}, fmt.Errorf("申请证书失败:%w", err) } resource := Resource{ @@ -93,12 +116,3 @@ func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resourc } return ValidateResource(resource) } - -func nonEmptyEmail(values ...string) []string { - for _, value := range values { - if strings.TrimSpace(value) != "" { - return []string{strings.TrimSpace(value)} - } - } - return nil -} diff --git a/backend/internal/certificate/lego_test.go b/backend/internal/certificate/lego_test.go new file mode 100644 index 0000000..c00ef2f --- /dev/null +++ b/backend/internal/certificate/lego_test.go @@ -0,0 +1,74 @@ +package certificate + +import ( + "context" + "testing" + "time" + + "github.com/go-acme/lego/v5/challenge" +) + +type propagationTestProvider struct { + present bool + cleanup bool +} + +func (p *propagationTestProvider) Present(context.Context, string, string, string) error { + p.present = true + return nil +} + +func (p *propagationTestProvider) CleanUp(context.Context, string, string, string) error { + p.cleanup = true + return nil +} + +func TestWithPropagationSettingsProvidesConfiguredTimeout(t *testing.T) { + base := &propagationTestProvider{} + timeout := 15 * time.Minute + interval := 10 * time.Second + wrapped := withPropagationSettings(base, timeout, interval) + provider, ok := wrapped.(challenge.ProviderTimeout) + if !ok { + t.Fatal("DNS Provider 未实现传播等待配置接口") + } + actualTimeout, actualInterval := provider.Timeout() + if actualTimeout != timeout || actualInterval != interval { + t.Fatalf("DNS 传播参数不正确:timeout=%s interval=%s", actualTimeout, actualInterval) + } + if err := wrapped.Present(context.Background(), "example.com", "token", "key-auth"); err != nil { + t.Fatalf("Provider Present 转发失败:%v", err) + } + if err := wrapped.CleanUp(context.Background(), "example.com", "token", "key-auth"); err != nil { + t.Fatalf("Provider CleanUp 转发失败:%v", err) + } + if !base.present || !base.cleanup { + t.Fatal("包装器未正确转发 Provider 操作") + } +} + +func TestWithPropagationSettingsPreservesProviderForInvalidValues(t *testing.T) { + base := &propagationTestProvider{} + cases := []struct { + name string + timeout time.Duration + interval time.Duration + }{ + {name: "zero timeout", timeout: 0, interval: time.Second}, + {name: "zero interval", timeout: time.Minute, interval: 0}, + {name: "interval exceeds timeout", timeout: time.Second, interval: time.Minute}, + } + for _, item := range cases { + t.Run(item.name, func(t *testing.T) { + if got := withPropagationSettings(base, item.timeout, item.interval); got != base { + t.Fatal("无效 DNS 传播参数不应替换原 Provider") + } + }) + } +} + +func TestWithPropagationSettingsPreservesNilProvider(t *testing.T) { + if got := withPropagationSettings(nil, time.Minute, time.Second); got != nil { + t.Fatal("空 Provider 应保持为空") + } +} diff --git a/backend/internal/certificate/service.go b/backend/internal/certificate/service.go index c12b0e7..7f2666d 100644 --- a/backend/internal/certificate/service.go +++ b/backend/internal/certificate/service.go @@ -75,7 +75,13 @@ func NewService(cfg config.Config, repository DomainStateRepository, credentials config: cfg, repository: repository, credentials: credentials, providers: providers, accounts: accounts, store: FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup}, newIssuer: func(user *AccountUser, provider challenge.Provider, environment string) Issuer { - return &LegoIssuer{User: user, Provider: provider, Environment: environment} + return &LegoIssuer{ + User: user, + Provider: provider, + Environment: environment, + PropagationTimeout: time.Duration(cfg.ACME.PropagationTimeoutSecs) * time.Second, + PropagationInterval: time.Duration(cfg.ACME.PropagationPollingIntervalSecs) * time.Second, + } }, } } diff --git a/backend/internal/certificate/service_test.go b/backend/internal/certificate/service_test.go index 9cfbeb3..ef708ad 100644 --- a/backend/internal/certificate/service_test.go +++ b/backend/internal/certificate/service_test.go @@ -18,6 +18,7 @@ import ( "git.pcux.cn/xuans/Scert/backend/internal/config" "git.pcux.cn/xuans/Scert/backend/internal/domain" + "git.pcux.cn/xuans/Scert/backend/internal/secretstore" ) type serviceRepository struct { @@ -53,6 +54,17 @@ func (serviceProviderFactory) Create(string, map[string]string) (challenge.Provi return serviceProvider{}, nil } +type recordingProviderFactory struct { + providerID string + credentials map[string]string +} + +func (f *recordingProviderFactory) Create(providerID string, credentials map[string]string) (challenge.Provider, error) { + f.providerID = providerID + f.credentials = credentials + return serviceProvider{}, nil +} + type serviceAccounts struct{} func (serviceAccounts) LoadOrCreate(context.Context, string, string) (*AccountUser, error) { @@ -262,3 +274,49 @@ func TestServiceIssuesSetupCertificateWithTypedLayout(t *testing.T) { } } } + +func TestServiceDecryptsCredentialReferenceBeforeCreatingProvider(t *testing.T) { + root := t.TempDir() + cfg := certificateTestConfig(root) + store, err := secretstore.Open(cfg.Paths.Config) + if err != nil { + t.Fatalf("打开敏感信息存储失败:%v", err) + } + credentialRef := "secret://dns/cloudflare/service-test" + if err := store.Put(context.Background(), credentialRef, map[string]string{ + "api_token": "test-dns-token", + }); err != nil { + t.Fatalf("保存测试 DNS 凭据失败:%v", err) + } + cfg.DNS.CredentialRef = credentialRef + item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSingle, nil, true, domain.ACMEEnvironmentStaging, "cloudflare") + if err != nil { + t.Fatal(err) + } + repository := &serviceRepository{item: item} + factory := &recordingProviderFactory{} + issuer := &serviceIssuer{resource: testResource(t, "example.com")} + service := NewService(cfg, repository, store, factory, serviceAccounts{}) + service.newIssuer = func(*AccountUser, challenge.Provider, string) Issuer { return issuer } + + if _, err := service.Issue(context.Background(), item.ID); err != nil { + t.Fatalf("使用加密凭据引用申请证书失败:%v", err) + } + if factory.providerID != "cloudflare" || factory.credentials["api_token"] != "test-dns-token" { + t.Fatalf("创建 DNS Provider 时未正确解密凭据:provider=%q credentials=%v", factory.providerID, factory.credentials) + } +} + +func TestNewServiceInjectsPropagationSettings(t *testing.T) { + cfg := certificateTestConfig(t.TempDir()) + cfg.ACME.PropagationTimeoutSecs = 1200 + cfg.ACME.PropagationPollingIntervalSecs = 15 + service := NewService(cfg, nil, nil, nil, nil) + issuer, ok := service.newIssuer(&AccountUser{}, serviceProvider{}, "staging").(*LegoIssuer) + if !ok { + t.Fatal("创建的 Issuer 类型不正确") + } + if issuer.PropagationTimeout != 1200*time.Second || issuer.PropagationInterval != 15*time.Second { + t.Fatalf("DNS 传播参数注入不正确:timeout=%s interval=%s", issuer.PropagationTimeout, issuer.PropagationInterval) + } +} diff --git a/backend/internal/cli/mysql_backup.go b/backend/internal/cli/mysql_backup.go new file mode 100644 index 0000000..6ead1e8 --- /dev/null +++ b/backend/internal/cli/mysql_backup.go @@ -0,0 +1,341 @@ +package cli + +import ( + "context" + "database/sql" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "git.pcux.cn/xuans/Scert/backend/internal/config" + "git.pcux.cn/xuans/Scert/backend/internal/database" +) + +// backupMySQL 将 MySQL 的表结构和数据导出为可在 MySQL 5.7/8.0 导入的 SQL 文件。 +func backupMySQL(ctx context.Context, cfg config.Config, output string) error { + db, err := database.Open(ctx, cfg.Database) + if err != nil { + return fmt.Errorf("打开 MySQL 备份连接失败:%w", err) + } + defer db.Close() + + temporaryPath := output + ".tmp" + file, err := os.OpenFile(temporaryPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + return fmt.Errorf("创建 MySQL 备份文件失败:%w", err) + } + removeTemporary := true + defer func() { + _ = file.Close() + if removeTemporary { + _ = os.Remove(temporaryPath) + } + }() + + if _, err := fmt.Fprintf(file, "-- Scert MySQL 数据备份\n-- 生成时间:%s\n\nSET FOREIGN_KEY_CHECKS=0;\n\n", time.Now().UTC().Format(time.RFC3339)); err != nil { + return fmt.Errorf("写入 MySQL 备份头失败:%w", err) + } + + rows, err := db.DB.QueryContext(ctx, "SHOW TABLES") + if err != nil { + return fmt.Errorf("读取 MySQL 表列表失败:%w", err) + } + var tableNames []string + for rows.Next() { + var tableName string + if err := rows.Scan(&tableName); err != nil { + _ = rows.Close() + return fmt.Errorf("读取 MySQL 表名失败:%w", err) + } + tableNames = append(tableNames, tableName) + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return fmt.Errorf("遍历 MySQL 表列表失败:%w", err) + } + if err := rows.Close(); err != nil { + return fmt.Errorf("关闭 MySQL 表列表失败:%w", err) + } + + for _, tableName := range tableNames { + if err := dumpMySQLTable(ctx, db.DB, file, tableName); err != nil { + return err + } + } + if _, err := fmt.Fprint(file, "SET FOREIGN_KEY_CHECKS=1;\n"); err != nil { + return fmt.Errorf("写入 MySQL 备份尾失败:%w", err) + } + if err := file.Close(); err != nil { + return fmt.Errorf("关闭 MySQL 备份文件失败:%w", err) + } + if err := os.Chmod(temporaryPath, 0o600); err != nil { + return fmt.Errorf("设置 MySQL 备份文件权限失败:%w", err) + } + if err := os.Rename(temporaryPath, output); err != nil { + return fmt.Errorf("保存 MySQL 备份文件失败:%w", err) + } + removeTemporary = false + return nil +} + +// createMySQLRestoreBackup 在恢复前保留目标数据库快照,供失败时回滚使用。 +// 快照目录不会在恢复成功后自动删除,便于管理员在需要时继续排查或手动恢复。 +func createMySQLRestoreBackup(ctx context.Context, cfg config.Config) (string, error) { + backupRoot := filepath.Clean(strings.TrimSpace(cfg.Paths.Backup)) + if backupRoot == "." || backupRoot == "" { + return "", fmt.Errorf("MySQL 恢复前备份目录不能为空") + } + if err := os.MkdirAll(backupRoot, 0o700); err != nil { + return "", fmt.Errorf("创建 MySQL 恢复前备份目录失败:%w", err) + } + info, err := os.Lstat(backupRoot) + if err != nil { + return "", fmt.Errorf("检查 MySQL 恢复前备份目录失败:%w", err) + } + if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + return "", fmt.Errorf("MySQL 恢复前备份目录必须是普通目录") + } + if err := os.Chmod(backupRoot, 0o700); err != nil { + return "", fmt.Errorf("设置 MySQL 恢复前备份目录权限失败:%w", err) + } + rollbackDirectory, err := os.MkdirTemp(backupRoot, "scert-before-restore-") + if err != nil { + return "", fmt.Errorf("创建 MySQL 恢复快照目录失败:%w", err) + } + rollbackPath := filepath.Join(rollbackDirectory, "scert.sql") + if err := backupMySQL(ctx, cfg, rollbackPath); err != nil { + return "", fmt.Errorf("创建 MySQL 恢复前快照失败:%w", err) + } + return rollbackPath, nil +} + +func dumpMySQLTable(ctx context.Context, db *sql.DB, output *os.File, tableName string) error { + quotedTable := quoteMySQLIdentifier(tableName) + var name, createSQL string + if err := db.QueryRowContext(ctx, "SHOW CREATE TABLE "+quotedTable).Scan(&name, &createSQL); err != nil { + return fmt.Errorf("读取 MySQL 表结构失败(%s):%w", tableName, err) + } + if _, err := fmt.Fprintf(output, "DROP TABLE IF EXISTS %s;\n%s;\n\n", quotedTable, createSQL); err != nil { + return fmt.Errorf("写入 MySQL 表结构失败(%s):%w", tableName, err) + } + + rows, err := db.QueryContext(ctx, "SELECT * FROM "+quotedTable) + if err != nil { + return fmt.Errorf("读取 MySQL 表数据失败(%s):%w", tableName, err) + } + defer rows.Close() + columns, err := rows.Columns() + if err != nil { + return fmt.Errorf("读取 MySQL 表字段失败(%s):%w", tableName, err) + } + for rows.Next() { + values := make([]any, len(columns)) + pointers := make([]any, len(columns)) + for index := range values { + pointers[index] = &values[index] + } + if err := rows.Scan(pointers...); err != nil { + return fmt.Errorf("读取 MySQL 表行失败(%s):%w", tableName, err) + } + literals := make([]string, len(values)) + for index, value := range values { + literals[index] = mysqlSQLLiteral(value) + } + if _, err := fmt.Fprintf(output, "INSERT INTO %s (%s) VALUES (%s);\n", quotedTable, quoteMySQLColumns(columns), strings.Join(literals, ", ")); err != nil { + return fmt.Errorf("写入 MySQL 表数据失败(%s):%w", tableName, err) + } + } + if err := rows.Err(); err != nil { + return fmt.Errorf("遍历 MySQL 表数据失败(%s):%w", tableName, err) + } + _, err = fmt.Fprintln(output) + return err +} + +func quoteMySQLIdentifier(value string) string { + return "`" + strings.ReplaceAll(value, "`", "``") + "`" +} + +func quoteMySQLColumns(columns []string) string { + quoted := make([]string, len(columns)) + for index, column := range columns { + quoted[index] = quoteMySQLIdentifier(column) + } + return strings.Join(quoted, ", ") +} + +func mysqlSQLLiteral(value any) string { + switch typed := value.(type) { + case nil: + return "NULL" + case sql.RawBytes: + return "X'" + hex.EncodeToString(typed) + "'" + case []byte: + return "X'" + hex.EncodeToString(typed) + "'" + case string: + return mysqlStringLiteral(typed) + case time.Time: + return "'" + typed.UTC().Format("2006-01-02 15:04:05.999999") + "'" + case bool: + if typed { + return "1" + } + return "0" + case int64: + return strconv.FormatInt(typed, 10) + case uint64: + return strconv.FormatUint(typed, 10) + case float64: + return strconv.FormatFloat(typed, 'g', -1, 64) + case float32: + return strconv.FormatFloat(float64(typed), 'g', -1, 32) + default: + return mysqlStringLiteral(fmt.Sprint(typed)) + } +} + +func mysqlStringLiteral(value string) string { + var builder strings.Builder + builder.Grow(len(value) + 2) + builder.WriteByte('\'') + for index := 0; index < len(value); index++ { + switch value[index] { + case '\\': + builder.WriteString(`\\`) + case '\x00': + builder.WriteString(`\0`) + case '\n': + builder.WriteString(`\n`) + case '\r': + builder.WriteString(`\r`) + case '\x1a': + builder.WriteString(`\Z`) + case '\'': + builder.WriteString(`''`) + default: + builder.WriteByte(value[index]) + } + } + builder.WriteByte('\'') + return builder.String() +} + +// restoreMySQL 执行 Scert 生成的 MySQL SQL 备份。 +func restoreMySQL(ctx context.Context, cfg config.Config, input string) error { + script, err := os.ReadFile(input) + if err != nil { + return fmt.Errorf("读取 MySQL 备份文件失败:%w", err) + } + db, err := database.Open(ctx, cfg.Database) + if err != nil { + return fmt.Errorf("打开 MySQL 恢复连接失败:%w", err) + } + defer db.Close() + for _, statement := range splitMySQLStatements(string(script)) { + if _, err := db.DB.ExecContext(ctx, statement); err != nil { + return fmt.Errorf("执行 MySQL 恢复语句失败:%w", err) + } + } + return nil +} + +func splitMySQLStatements(script string) []string { + var statements []string + var statement strings.Builder + var quote byte + lineComment := false + blockComment := false + executableComment := false + escaped := false + flush := func() { + value := strings.TrimSpace(statement.String()) + if value != "" { + statements = append(statements, value) + } + statement.Reset() + } + for index := 0; index < len(script); index++ { + current := script[index] + if lineComment { + if current == '\n' { + lineComment = false + statement.WriteByte('\n') + } + continue + } + if blockComment { + if current == '*' && index+1 < len(script) && script[index+1] == '/' { + blockComment = false + index++ + statement.WriteByte(' ') + } + continue + } + if executableComment { + statement.WriteByte(current) + if current == '*' && index+1 < len(script) && script[index+1] == '/' { + statement.WriteByte(script[index+1]) + index++ + executableComment = false + } + continue + } + if quote != 0 { + statement.WriteByte(current) + if escaped { + escaped = false + continue + } + if current == '\\' { + escaped = true + continue + } + if current == quote { + if index+1 < len(script) && script[index+1] == quote { + statement.WriteByte(script[index+1]) + index++ + continue + } + quote = 0 + } + continue + } + if current == '\'' || current == '"' || current == '`' { + quote = current + statement.WriteByte(current) + continue + } + if current == '#' { + lineComment = true + continue + } + if current == '-' && index+2 < len(script) && script[index+1] == '-' && (script[index+2] == ' ' || script[index+2] == '\t' || script[index+2] == '\n') { + lineComment = true + index++ + continue + } + if current == '/' && index+1 < len(script) && script[index+1] == '*' { + if index+2 < len(script) && (script[index+2] == '!' || script[index+2] == '+') { + statement.WriteByte(current) + statement.WriteByte(script[index+1]) + index++ + executableComment = true + continue + } + blockComment = true + index++ + continue + } + if current == ';' { + flush() + continue + } + statement.WriteByte(current) + } + flush() + return statements +} diff --git a/backend/internal/cli/mysql_backup_test.go b/backend/internal/cli/mysql_backup_test.go new file mode 100644 index 0000000..33a6c61 --- /dev/null +++ b/backend/internal/cli/mysql_backup_test.go @@ -0,0 +1,63 @@ +package cli + +import ( + "database/sql" + "strings" + "testing" +) + +func TestQuoteMySQLIdentifierEscapesBackticks(t *testing.T) { + if value := quoteMySQLIdentifier("a`b"); value != "`a``b`" { + t.Fatalf("MySQL 标识符转义不正确:%s", value) + } +} + +func TestMySQLSQLLiteral(t *testing.T) { + cases := []struct { + name string + value any + want string + }{ + {name: "null", value: nil, want: "NULL"}, + {name: "string", value: "a'b\\c\n\x00\x1a", want: "'a''b\\\\c\\n\\0\\Z'"}, + {name: "binary", value: []byte{0x01, 0xaf}, want: "X'01af'"}, + {name: "raw bytes", value: sql.RawBytes{0x00, 0xff}, want: "X'00ff'"}, + {name: "integer", value: int64(42), want: "42"}, + {name: "boolean", value: true, want: "1"}, + } + for _, item := range cases { + t.Run(item.name, func(t *testing.T) { + if value := mysqlSQLLiteral(item.value); value != item.want { + t.Fatalf("SQL 字面量不正确:%s", value) + } + }) + } +} + +func TestQuoteMySQLColumns(t *testing.T) { + value := quoteMySQLColumns([]string{"id", "display_name"}) + if value != "`id`, `display_name`" || strings.Contains(value, "'") { + t.Fatalf("MySQL 字段列表不正确:%s", value) + } +} +func TestSplitMySQLStatementsKeepsQuotedSemicolons(t *testing.T) { + script := "-- 注释\nSET FOREIGN_KEY_CHECKS=0;\nINSERT INTO `items` (`value`) VALUES ('a; b'), ('it''s');\n" + statements := splitMySQLStatements(script) + if len(statements) != 2 { + t.Fatalf("SQL 语句拆分数量不正确:%d %#v", len(statements), statements) + } + if strings.Contains(statements[0], "注释") || !strings.Contains(statements[1], "'a; b'") || !strings.Contains(statements[1], "'it''s'") { + t.Fatalf("SQL 语句拆分内容不正确:%#v", statements) + } +} + +func TestSplitMySQLStatementsKeepsExecutableComments(t *testing.T) { + script := "CREATE TABLE `items` (`id` bigint) /*!50100 SET @value = 'a;b' */;\n" + statements := splitMySQLStatements(script) + if len(statements) != 1 { + t.Fatalf("带可执行注释的 SQL 语句拆分数量不正确:%d %#v", len(statements), statements) + } + if !strings.Contains(statements[0], "/*!50100 SET @value = 'a;b' */") { + t.Fatalf("MySQL 可执行注释不应被删除:%s", statements[0]) + } +} diff --git a/backend/internal/cli/operations.go b/backend/internal/cli/operations.go index 252a85f..6d8fd4c 100644 --- a/backend/internal/cli/operations.go +++ b/backend/internal/cli/operations.go @@ -270,7 +270,7 @@ func newBackupCommand() *cobra.Command { var output string command := &cobra.Command{ Use: "backup", - Short: "备份配置和 SQLite 数据库", + Short: "备份配置和数据库", RunE: func(cmd *cobra.Command, args []string) error { cfg, err := loadConfig() if err != nil { @@ -294,6 +294,11 @@ func newBackupCommand() *cobra.Command { return err } } + if cfg.Database.Driver == "mysql" { + if err := backupMySQL(cmd.Context(), cfg, filepath.Join(output, "scert.sql")); err != nil { + return err + } + } _, err = fmt.Fprintf(cmd.OutOrStdout(), "备份已创建:%s\n", output) return err }, @@ -306,7 +311,7 @@ func newRestoreCommand() *cobra.Command { var input string command := &cobra.Command{ Use: "restore", - Short: "恢复 SQLite 数据库备份", + Short: "恢复配置和数据库备份", RunE: func(cmd *cobra.Command, args []string) error { input, err := validateRestoreInput(input) if err != nil { @@ -319,16 +324,24 @@ func newRestoreCommand() *cobra.Command { } currentPath := filepath.Clean(resolveConfigPath()) - _, currentConfigErr := config.Load(currentPath) + currentConfig, currentConfigErr := config.Load(currentPath) if currentConfigErr != nil && !errors.Is(currentConfigErr, os.ErrNotExist) { return fmt.Errorf("读取当前配置失败:%w", currentConfigErr) } + if currentConfigErr == nil && currentConfig.Database.Driver != cfg.Database.Driver { + return fmt.Errorf("备份数据库类型(%s)与当前配置数据库类型(%s)不一致,拒绝恢复", cfg.Database.Driver, currentConfig.Database.Driver) + } 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) } + mysqlSource := filepath.Join(input, "scert.sql") + if cfg.Database.Driver == "mysql" && !isRegularFile(mysqlSource) { + return errors.New("MySQL 备份目录缺少有效的 scert.sql 文件") + } + databaseSource := filepath.Join(input, "scert.db") databaseSourceInfo, databaseSourceErr := os.Stat(databaseSource) databaseSourceExists := databaseSourceErr == nil @@ -338,6 +351,9 @@ func newRestoreCommand() *cobra.Command { if databaseSourceExists && !databaseSourceInfo.Mode().IsRegular() { return errors.New("备份数据库不是普通文件") } + if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && !databaseSourceExists { + return errors.New("SQLite 备份目录缺少有效的 scert.db 文件") + } if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && databaseSourceExists { if samePath(databaseSource, cfg.Database.DSN) { return errors.New("备份数据库与当前数据库路径相同") @@ -368,6 +384,14 @@ func newRestoreCommand() *cobra.Command { } } + mysqlBackupPath := "" + if cfg.Database.Driver == "mysql" { + mysqlBackupPath, err = createMySQLRestoreBackup(cmd.Context(), cfg) + if err != nil { + return err + } + } + if err := cfg.Save(currentPath); err != nil { return err } @@ -382,6 +406,20 @@ func newRestoreCommand() *cobra.Command { return fmt.Errorf("恢复 SQLite 数据库失败:%w", err) } } + if cfg.Database.Driver == "mysql" { + if err := restoreMySQL(cmd.Context(), cfg, mysqlSource); err != nil { + restoreFailure := fmt.Errorf("恢复 MySQL 数据库失败:%w", err) + if mysqlBackupPath != "" { + if rollbackErr := restoreMySQL(cmd.Context(), cfg, mysqlBackupPath); rollbackErr != nil { + restoreFailure = fmt.Errorf("%w;MySQL 数据库回滚失败:%v", restoreFailure, rollbackErr) + } + } + if configBackupPath != "" { + _ = copyFile(configBackupPath, currentPath, 0o600) + } + return restoreFailure + } + } _, err = fmt.Fprintf(cmd.OutOrStdout(), "恢复已完成:%s\n", input) return err }, @@ -483,6 +521,18 @@ func setConfigValue(cfg *config.Config, key, value string) error { return fmt.Errorf("续期阈值格式无效:%w", err) } cfg.ACME.RenewalThresholdDays = parsed + case "acme.propagation_timeout_secs": + parsed, err := parseInt() + if err != nil { + return fmt.Errorf("DNS 传播等待时间格式无效:%w", err) + } + cfg.ACME.PropagationTimeoutSecs = parsed + case "acme.propagation_polling_interval_secs": + parsed, err := parseInt() + if err != nil { + return fmt.Errorf("DNS 传播检测间隔格式无效:%w", err) + } + cfg.ACME.PropagationPollingIntervalSecs = parsed case "dns.provider": cfg.DNS.Provider = value case "dns.credential_ref": diff --git a/backend/internal/cli/operations_test.go b/backend/internal/cli/operations_test.go index 8f72f30..90bba81 100644 --- a/backend/internal/cli/operations_test.go +++ b/backend/internal/cli/operations_test.go @@ -50,6 +50,15 @@ func TestSetConfigValueUpdatesAndValidatesAllowedFields(t *testing.T) { if cfg.Notification.HTTPLoginPath != "/api/login" { t.Fatalf("HTTP 登录路径未更新:%s", cfg.Notification.HTTPLoginPath) } + if err := setConfigValue(&cfg, "acme.propagation_timeout_secs", "1200"); err != nil { + t.Fatal(err) + } + if err := setConfigValue(&cfg, "acme.propagation_polling_interval_secs", "15"); err != nil { + t.Fatal(err) + } + if cfg.ACME.PropagationTimeoutSecs != 1200 || cfg.ACME.PropagationPollingIntervalSecs != 15 { + t.Fatalf("DNS 传播参数未更新:%+v", cfg.ACME) + } if err := setConfigValue(&cfg, "admin.password_hash", "plain"); err == nil { t.Fatal("不应允许直接修改密码摘要") } diff --git a/backend/internal/cli/root.go b/backend/internal/cli/root.go index 5bc7362..3079fc8 100644 --- a/backend/internal/cli/root.go +++ b/backend/internal/cli/root.go @@ -22,8 +22,10 @@ import ( "git.pcux.cn/xuans/Scert/backend/internal/buildinfo" "git.pcux.cn/xuans/Scert/backend/internal/certificate" "git.pcux.cn/xuans/Scert/backend/internal/config" + "git.pcux.cn/xuans/Scert/backend/internal/dnsprovider" "git.pcux.cn/xuans/Scert/backend/internal/domain" "git.pcux.cn/xuans/Scert/backend/internal/firewall" + "git.pcux.cn/xuans/Scert/backend/internal/secretstore" "git.pcux.cn/xuans/Scert/backend/internal/setup" ) @@ -159,15 +161,21 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command return err } } + cleanupSecret, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout()) + if err != nil { + return err + } if err := setup.Apply(&cfg, input); err != nil { + cleanupSecret() return err } firewallResult, err := saveSetupWithFirewall(cmd.Context(), cfg, path, firewallManager) if err != nil { + cleanupSecret() return err } fmt.Fprintf(cmd.OutOrStdout(), "初始化配置已保存:%s\n", path) - fmt.Fprintf(cmd.OutOrStdout(), "DNS API 已标记为验证通过;真实 provider 连通性测试和 Web 证书申请将在后续任务接入。\n") + fmt.Fprintf(cmd.OutOrStdout(), "DNS API 已完成在线验证,凭据已加密保存;真实 Web 证书申请将在后续任务接入。\n") fmt.Fprintf(cmd.OutOrStdout(), "本机防火墙:%s\n", firewallResult.Message) fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d。Scert-admin 默认关闭;需要重置密码时启动后访问:%s\n", cfg.Server.Port, cfg.ResetURL()) return nil @@ -195,8 +203,8 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command 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 是否已通过外部验证测试") + command.Flags().StringVar(&dnsCredentialRef, "dns-credential-ref", "", "DNS 凭据引用") + command.Flags().BoolVar(&dnsVerified, "dns-verified", false, "DNS API 是否已通过验证测试") command.Flags().StringVar(&certificateRoot, "certificate-root", "", "证书部署根目录,默认使用系统目录") command.Flags().StringVar(&webHostname, "web-hostname", "", "管理页面域名") command.Flags().StringVar(&webPublicIP, "web-public-ip", "", "没有域名时使用的公网 IP") @@ -267,15 +275,15 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input, return err } value.EmailRecipients = splitValues(receiver) - value.DNSProvider, err = ask(reader, output, "DNS API 服务商 *", "") + value.DNSProvider, err = askDNSProvider(reader, output) if err != nil { return err } - value.DNSCredentialRef, err = ask(reader, output, "DNS 凭据引用 *(不要输入明文密钥)", "") + value.DNSCredentials, err = askDNSCredentials(reader, output, value.DNSProvider) if err != nil { return err } - value.DNSVerified, err = askYesNo(reader, output, "DNS API 是否已经完成验证测试?", false) + value.DNSTestDomain, err = ask(reader, output, "DNS 权限测试域名 *", "") if err != nil { return err } @@ -297,6 +305,120 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input, return err } +func askDNSCredentials(reader *bufio.Reader, output io.Writer, providerID string) (map[string]string, error) { + descriptor, err := dnsprovider.GetDescriptor(providerID) + if err != nil { + return nil, err + } + credentials := make(map[string]string, len(descriptor.CredentialFields)) + fmt.Fprintln(output, "请输入 DNS API 凭据。输入内容会在当前配置过程中明文显示,提交后只保存加密内容。") + for _, field := range descriptor.CredentialFields { + label := field.Label + if field.Required { + label += " *" + } + value, err := ask(reader, output, label, "") + if err != nil { + return nil, err + } + if strings.TrimSpace(value) != "" { + credentials[field.Name] = value + } + } + return credentials, nil +} + +func prepareDNSCredentials(ctx context.Context, cfg config.Config, input *setup.Input, output io.Writer) (func(), error) { + if input == nil { + return func() {}, errors.New("初始化输入不能为空") + } + if strings.TrimSpace(input.DNSCredentialRef) != "" { + return func() {}, nil + } + if len(input.DNSCredentials) == 0 { + return func() {}, errors.New("DNS 凭据不能为空") + } + if strings.TrimSpace(input.DNSTestDomain) == "" { + return func() {}, errors.New("DNS 权限测试域名不能为空") + } + + store, err := secretstore.Open(cfg.Paths.Config) + if err != nil { + return func() {}, fmt.Errorf("初始化 DNS 凭据存储失败:%w", err) + } + manager := setup.NewDNSVerificationManager( + dnsprovider.NewTester(dnsprovider.NewLegoFactory()), + store, + ) + return prepareDNSCredentialsWithManager(ctx, input, output, manager, store) +} + +func prepareDNSCredentialsWithManager(ctx context.Context, input *setup.Input, output io.Writer, manager *setup.DNSVerificationManager, store *secretstore.Store) (func(), error) { + if input == nil { + return func() {}, errors.New("初始化输入不能为空") + } + if manager == nil || store == nil { + return func() {}, errors.New("DNS 凭据验证服务未初始化") + } + if strings.TrimSpace(input.DNSCredentialRef) != "" { + return func() {}, nil + } + if len(input.DNSCredentials) == 0 { + return func() {}, errors.New("DNS 凭据不能为空") + } + if strings.TrimSpace(input.DNSTestDomain) == "" { + return func() {}, errors.New("DNS 权限测试域名不能为空") + } + testContext, cancel := context.WithTimeout(ctx, 45*time.Second) + defer cancel() + result, err := manager.Verify(testContext, setup.DNSVerificationInput{ + ProviderID: input.DNSProvider, + TestDomain: input.DNSTestDomain, + Credentials: input.DNSCredentials, + }) + if err != nil { + return func() {}, fmt.Errorf("DNS API 在线验证失败:%w", err) + } + input.DNSCredentialRef = result.CredentialRef + input.DNSVerified = true + input.DNSCredentials = nil + fmt.Fprintf(output, "DNS API 在线验证通过,凭据已加密保存,有效期至 %s。\n", result.ExpiresAt.Local().Format("2006-01-02 15:04:05")) + return func() { + cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cleanupCancel() + _ = store.Delete(cleanupContext, result.CredentialRef) + }, nil +} + +func askDNSProvider(reader *bufio.Reader, output io.Writer) (string, error) { + providers := dnsprovider.Descriptors() + fmt.Fprintln(output, "请选择 DNS API 服务商:") + for index, provider := range providers { + status := "" + if !provider.Available { + status = "(暂未开放)" + } + fmt.Fprintf(output, "%d. %s%s\n", index+1, provider.Name, status) + } + + for { + value, err := ask(reader, output, "请输入编号", "") + if err != nil { + return "", err + } + index, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil || index < 1 || index > len(providers) { + fmt.Fprintln(output, "编号无效,请重新输入。") + continue + } + provider := providers[index-1] + if !provider.Available { + fmt.Fprintf(output, "%s 当前暂未开放,请选择其他服务商。\n", provider.Name) + continue + } + return provider.ID, nil + } +} func ask(reader *bufio.Reader, output io.Writer, label, defaultValue string) (string, error) { if defaultValue != "" { fmt.Fprintf(output, "%s [%s]:", label, defaultValue) diff --git a/backend/internal/cli/root_test.go b/backend/internal/cli/root_test.go index 95cba63..8db6a71 100644 --- a/backend/internal/cli/root_test.go +++ b/backend/internal/cli/root_test.go @@ -1,6 +1,7 @@ package cli import ( + "bufio" "bytes" "context" "errors" @@ -12,7 +13,10 @@ import ( "git.pcux.cn/xuans/Scert/backend/internal/buildinfo" "git.pcux.cn/xuans/Scert/backend/internal/config" "git.pcux.cn/xuans/Scert/backend/internal/deployment" + "git.pcux.cn/xuans/Scert/backend/internal/dnsprovider" "git.pcux.cn/xuans/Scert/backend/internal/firewall" + "git.pcux.cn/xuans/Scert/backend/internal/secretstore" + "git.pcux.cn/xuans/Scert/backend/internal/setup" ) type cliFakeFirewallManager struct { @@ -164,6 +168,36 @@ func TestInitCommandDoesNotExposeResetServicePort(t *testing.T) { } } +func TestAskDNSProviderUsesNumberedSelection(t *testing.T) { + var output bytes.Buffer + provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("99\n2\n")), &output) + if err != nil { + t.Fatalf("DNS 服务商选择失败:%v", err) + } + if provider != "aliyun" { + t.Fatalf("编号 2 应选择阿里云 DNS,实际为:%s", provider) + } + if !strings.Contains(output.String(), "1. Cloudflare") || !strings.Contains(output.String(), "2. 阿里云 DNS") { + t.Fatalf("DNS 服务商列表未按编号显示:%s", output.String()) + } + if !strings.Contains(output.String(), "编号无效,请重新输入。") { + t.Fatalf("无效编号未提示重新输入:%s", output.String()) + } +} + +func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) { + var output bytes.Buffer + provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("4\n1\n")), &output) + if err != nil { + t.Fatalf("DNS 服务商选择失败:%v", err) + } + if provider != "cloudflare" { + t.Fatalf("重新选择后应返回 Cloudflare,实际为:%s", provider) + } + if !strings.Contains(output.String(), "当前暂未开放") { + t.Fatalf("选择未开放服务商时未给出提示:%s", output.String()) + } +} func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) { baseDir := t.TempDir() blockedParent := filepath.Join(baseDir, "blocked") @@ -197,3 +231,54 @@ func TestSaveSetupWithFirewallReportsRollbackFailure(t *testing.T) { t.Fatalf("防火墙回滚失败应返回明确错误:%v", err) } } + +type cliFakeDNSCredentialTester struct { + credentials map[string]string +} + +func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) error { + f.credentials = credentials + return nil +} + +func TestPrepareDNSCredentialsEncryptsAndClearsInput(t *testing.T) { + configDir := t.TempDir() + store, err := secretstore.Open(configDir) + if err != nil { + t.Fatalf("打开敏感信息存储失败:%v", err) + } + tester := &cliFakeDNSCredentialTester{} + manager := setup.NewDNSVerificationManager(tester, store) + input := &setup.Input{ + DNSProvider: dnsprovider.Cloudflare, + DNSCredentials: map[string]string{"api_token": "test-dns-token"}, + DNSTestDomain: "example.com", + } + var output bytes.Buffer + cleanup, err := prepareDNSCredentialsWithManager(context.Background(), input, &output, manager, store) + if err != nil { + t.Fatalf("准备 DNS 凭据失败:%v", err) + } + if input.DNSCredentialRef == "" || !input.DNSVerified || input.DNSCredentials != nil { + t.Fatalf("DNS 凭据输入状态不正确:%+v", input) + } + if tester.credentials["api_token"] != "test-dns-token" { + t.Fatalf("在线验证未收到凭据:%v", tester.credentials) + } + content, err := os.ReadFile(filepath.Join(configDir, "secrets.json")) + if err != nil { + t.Fatalf("读取敏感信息文件失败:%v", err) + } + if strings.Contains(string(content), "test-dns-token") || strings.Contains(output.String(), "test-dns-token") { + t.Fatal("DNS 凭据不应以明文写入文件或输出") + } + value, err := store.Get(context.Background(), input.DNSCredentialRef) + if err != nil || value["api_token"] != "test-dns-token" { + t.Fatalf("加密凭据解密结果不正确:value=%v err=%v", value, err) + } + cleanup() + exists, err := store.Has(context.Background(), input.DNSCredentialRef) + if err != nil || exists { + t.Fatalf("保存失败清理后凭据引用仍存在:exists=%t err=%v", exists, err) + } +} diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index c661925..61040d3 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -7,8 +7,10 @@ import ( "net/mail" "net/url" "os" + "os/user" "path/filepath" "runtime" + "strconv" "strings" ) @@ -72,10 +74,12 @@ type PathsConfig struct { } type ACMEConfig struct { - CA string `json:"ca"` - Environment string `json:"environment"` - AccountEmail string `json:"account_email"` - RenewalThresholdDays int `json:"renewal_threshold_days"` + CA string `json:"ca"` + Environment string `json:"environment"` + AccountEmail string `json:"account_email"` + RenewalThresholdDays int `json:"renewal_threshold_days"` + PropagationTimeoutSecs int `json:"propagation_timeout_secs"` + PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"` } type DNSConfig struct { @@ -119,8 +123,14 @@ func Default(baseDir string) Config { MaxOpenConns: 4, MaxIdleConns: 2, ConnMaxLifetimeMins: 30, }, Paths: paths, - ACME: ACMEConfig{CA: "letsencrypt", Environment: "staging", RenewalThresholdDays: 6}, - DNS: DNSConfig{VerificationState: "not_configured"}, + ACME: ACMEConfig{ + CA: "letsencrypt", + Environment: "staging", + RenewalThresholdDays: 6, + PropagationTimeoutSecs: 900, + PropagationPollingIntervalSecs: 10, + }, + DNS: DNSConfig{VerificationState: "not_configured"}, Notification: NotificationConfig{ HTTPHeaders: map[string]string{}, HTTPPath: "/api/email/send", @@ -207,6 +217,12 @@ func (c *Config) Normalize() { if c.DNS.VerificationState == "" { c.DNS.VerificationState = "not_configured" } + if c.ACME.PropagationTimeoutSecs == 0 { + c.ACME.PropagationTimeoutSecs = 900 + } + if c.ACME.PropagationPollingIntervalSecs == 0 { + c.ACME.PropagationPollingIntervalSecs = 10 + } if c.Notification.HTTPPath == "" { c.Notification.HTTPPath = "/api/email/send" } @@ -258,9 +274,44 @@ func (c Config) Save(path string) error { if err := os.Chmod(path, 0o600); err != nil { return fmt.Errorf("设置配置文件权限失败:%w", err) } + if err := applyLinuxServiceOwnership(filepath.Dir(path), path); err != nil { + return fmt.Errorf("设置配置文件归属失败:%w", err) + } return nil } +// applyLinuxServiceOwnership 在 root 初始化配置时,将配置目录和文件交给 Scert 服务用户管理。 +// 非 Linux、非 root 进程或系统尚未创建 Scert 用户时保持原有行为,便于开发环境使用。 +func applyLinuxServiceOwnership(directory, path string) error { + if runtime.GOOS != "linux" || os.Geteuid() != 0 { + return nil + } + + serviceUser, err := user.Lookup("Scert") + if err != nil { + return nil + } + serviceGroup, err := user.LookupGroup("Scert") + if err != nil { + return nil + } + uid, err := strconv.Atoi(serviceUser.Uid) + if err != nil { + return fmt.Errorf("解析 Scert 用户编号失败:%w", err) + } + gid, err := strconv.Atoi(serviceGroup.Gid) + if err != nil { + return fmt.Errorf("解析 Scert 用户组编号失败:%w", err) + } + if err := os.Chown(directory, uid, gid); err != nil { + return err + } + if err := os.Chmod(directory, 0o700); err != nil { + return err + } + return os.Chown(path, uid, gid) +} + func (c Config) Validate() error { if c.Version != CurrentVersion { return fmt.Errorf("配置版本不兼容:%d", c.Version) @@ -303,6 +354,15 @@ func (c Config) Validate() error { if c.ACME.RenewalThresholdDays < 1 { return fmt.Errorf("续期阈值必须大于 0") } + if c.ACME.PropagationTimeoutSecs < 1 || c.ACME.PropagationTimeoutSecs > 86400 { + return fmt.Errorf("DNS 传播等待时间必须在 1 到 86400 秒之间") + } + if c.ACME.PropagationPollingIntervalSecs < 1 { + return fmt.Errorf("DNS 传播检测间隔必须大于 0") + } + if c.ACME.PropagationPollingIntervalSecs > c.ACME.PropagationTimeoutSecs { + return fmt.Errorf("DNS 传播检测间隔不能大于传播等待时间") + } if c.DNS.VerificationState != "not_configured" && c.DNS.VerificationState != "pending" && c.DNS.VerificationState != "verified" && c.DNS.VerificationState != "failed" { return fmt.Errorf("DNS 验证状态无效:%s", c.DNS.VerificationState) } @@ -369,19 +429,37 @@ func (c Config) Validate() error { // ResetURL 返回通过主 Web 服务访问密码重置入口的公开地址。 func (c Config) ResetURL() string { - host := strings.TrimSpace(c.Web.Hostname) - if host == "" { - host = strings.TrimSpace(c.Web.PublicIP) + rawHost := strings.TrimSpace(c.Web.Hostname) + if rawHost == "" { + rawHost = strings.TrimSpace(c.Web.PublicIP) } - if host == "" { + if rawHost == "" { return "" } - if parsed, err := url.Parse(host); err == nil && parsed.Hostname() != "" { - host = parsed.Hostname() - } + host, _ := splitResetHost(rawHost) host = strings.Trim(host, "[]") - if ip := net.ParseIP(host); ip != nil && strings.Contains(host, ":") { + if ip := net.ParseIP(host); ip != nil && ip.To4() == nil { host = "[" + host + "]" } return (&url.URL{Scheme: "https", Host: host, Path: "/reset"}).String() } + +func splitResetHost(rawHost string) (string, string) { + trimmed := strings.TrimSpace(rawHost) + withoutBrackets := strings.Trim(trimmed, "[]") + if net.ParseIP(withoutBrackets) != nil { + return withoutBrackets, "" + } + + parseTarget := trimmed + if !strings.Contains(parseTarget, "://") { + parseTarget = "//" + parseTarget + } + if parsed, err := url.Parse(parseTarget); err == nil && parsed.Hostname() != "" { + return parsed.Hostname(), parsed.Port() + } + if parsedHost, parsedPort, err := net.SplitHostPort(trimmed); err == nil { + return parsedHost, parsedPort + } + return withoutBrackets, "" +} diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index c8f6085..82b9709 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -78,12 +78,12 @@ func TestValidateRejectsInvalidPort(t *testing.T) { } } -func TestResetURLUsesWebHostnameWithoutPort(t *testing.T) { +func TestResetURLAlwaysUsesWebHostnameWithoutPort(t *testing.T) { cfg := Default(t.TempDir()) cfg.Web.Hostname = "scert.example.test" cfg.Server.Port = 8443 if value := cfg.ResetURL(); value != "https://scert.example.test/reset" { - t.Fatalf("域名密码重置地址不正确:%s", value) + t.Fatalf("密码重置地址不得暴露主服务端口:%s", value) } cfg.Server.Port = 443 if value := cfg.ResetURL(); value != "https://scert.example.test/reset" { @@ -91,7 +91,7 @@ func TestResetURLUsesWebHostnameWithoutPort(t *testing.T) { } } -func TestResetURLSupportsPublicIPv6(t *testing.T) { +func TestResetURLSupportsPublicIPv6WithoutPort(t *testing.T) { cfg := Default(t.TempDir()) cfg.Web.PublicIP = "2001:db8::10" cfg.Server.Port = 8443 @@ -116,3 +116,95 @@ func TestSavedConfigDoesNotContainIndependentResetPort(t *testing.T) { t.Fatalf("配置文件不应再包含独立密码重置监听配置:%s", content) } } + +func TestResetURLIgnoresExplicitPortAndURLInput(t *testing.T) { + cfg := Default(t.TempDir()) + cfg.Web.Hostname = "https://scert.example.test:9443" + cfg.Server.Port = 5200 + if value := cfg.ResetURL(); value != "https://scert.example.test/reset" { + t.Fatalf("外部地址中的显式端口不得出现在重置地址中:%s", value) + } +} + +func TestResetURLIgnoresPathFromWebHostname(t *testing.T) { + cfg := Default(t.TempDir()) + cfg.Web.Hostname = "scert.example.test/manage" + cfg.Server.Port = 8443 + if value := cfg.ResetURL(); value != "https://scert.example.test/reset" { + t.Fatalf("管理页面域名附带路径时重置地址不正确:%s", value) + } +} + +func TestResetURLUsesExternalProxyAddress(t *testing.T) { + cfg := Default(t.TempDir()) + cfg.Web.Hostname = "scert.example.test" + cfg.Server.HTTPSMode = "proxy" + cfg.Server.Port = 5200 + if value := cfg.ResetURL(); value != "https://scert.example.test/reset" { + t.Fatalf("代理模式不应暴露核心服务端口:%s", value) + } +} + +func TestResetURLSupportsIPv6WithoutPort(t *testing.T) { + cfg := Default(t.TempDir()) + cfg.Web.PublicIP = "2001:db8::10" + cfg.Server.Port = 443 + if value := cfg.ResetURL(); value != "https://[2001:db8::10]/reset" { + t.Fatalf("IPv6 默认 HTTPS 地址不正确:%s", value) + } +} + +func TestDefaultACMEPropagationSettings(t *testing.T) { + cfg := Default(t.TempDir()) + if cfg.ACME.PropagationTimeoutSecs != 900 || cfg.ACME.PropagationPollingIntervalSecs != 10 { + t.Fatalf("默认 DNS 传播参数不正确:%+v", cfg.ACME) + } +} + +func TestNormalizeRestoresMissingACMEPropagationSettings(t *testing.T) { + cfg := Default(t.TempDir()) + cfg.ACME.PropagationTimeoutSecs = 0 + cfg.ACME.PropagationPollingIntervalSecs = 0 + cfg.Normalize() + if cfg.ACME.PropagationTimeoutSecs != 900 || cfg.ACME.PropagationPollingIntervalSecs != 10 { + t.Fatalf("旧配置的 DNS 传播参数未补齐:%+v", cfg.ACME) + } +} + +func TestValidateRejectsInvalidACMEPropagationTimeout(t *testing.T) { + for _, value := range []int{0, 86401} { + cfg := Default(t.TempDir()) + cfg.ACME.PropagationTimeoutSecs = value + if err := cfg.Validate(); err == nil { + t.Fatalf("无效 DNS 传播等待时间未被拒绝:%d", value) + } + } +} + +func TestValidateRejectsInvalidACMEPropagationInterval(t *testing.T) { + for _, value := range []int{0, 901} { + cfg := Default(t.TempDir()) + cfg.ACME.PropagationPollingIntervalSecs = value + if err := cfg.Validate(); err == nil { + t.Fatalf("无效 DNS 传播检测间隔未被拒绝:%d", value) + } + } +} + +func TestSaveAndLoadACMEPropagationSettings(t *testing.T) { + dir := t.TempDir() + cfg := Default(dir) + cfg.ACME.PropagationTimeoutSecs = 1200 + cfg.ACME.PropagationPollingIntervalSecs = 15 + path := filepath.Join(dir, "config", "scert.json") + if err := cfg.Save(path); err != nil { + t.Fatalf("保存配置失败:%v", err) + } + loaded, err := Load(path) + if err != nil { + t.Fatalf("读取配置失败:%v", err) + } + if loaded.ACME.PropagationTimeoutSecs != 1200 || loaded.ACME.PropagationPollingIntervalSecs != 15 { + t.Fatalf("DNS 传播参数持久化不一致:%+v", loaded.ACME) + } +} diff --git a/backend/internal/firewall/linux.go b/backend/internal/firewall/linux.go index f47b49c..8c44f1a 100644 --- a/backend/internal/firewall/linux.go +++ b/backend/internal/firewall/linux.go @@ -124,7 +124,9 @@ func (m *manager) rollbackFirewalld(ctx context.Context, result Result) error { func ufwIsActive(output []byte) bool { for _, line := range strings.Split(strings.ToLower(string(output)), "\n") { - if strings.TrimSpace(line) == "status: active" { + line = strings.TrimSpace(strings.ReplaceAll(line, ":", ":")) + line = strings.Join(strings.Fields(line), " ") + if line == "status: active" || line == "状态: 激活" { return true } } diff --git a/backend/internal/firewall/manager_test.go b/backend/internal/firewall/manager_test.go index 1e40ffd..b42db07 100644 --- a/backend/internal/firewall/manager_test.go +++ b/backend/internal/firewall/manager_test.go @@ -139,6 +139,19 @@ func TestUFWKeepsExistingRule(t *testing.T) { } } +func TestUFWRecognizesChineseActiveStatus(t *testing.T) { + runner := &fakeRunner{ + paths: map[string]string{"ufw": "/usr/sbin/ufw"}, + responses: []runnerResponse{{result: CommandResult{Output: []byte("状态: 激活\n8443/tcp ALLOW Anywhere\n")}}}, + } + result, err := NewManagerForOS("linux", runner).OpenTCP(context.Background(), 8443) + if err != nil { + t.Fatalf("中文 UFW 状态检查失败:%v", err) + } + if result.Created || result.Backend != backendUFW { + t.Fatalf("中文 UFW 已有规则不应重复创建:%+v", result) + } +} func TestFirewalldCreatesPermanentRuleAndReloads(t *testing.T) { runner := &fakeRunner{ paths: map[string]string{"firewall-cmd": "/usr/bin/firewall-cmd"}, diff --git a/backend/internal/httpapi/server.go b/backend/internal/httpapi/server.go index 77cd0f1..3f28c8b 100644 --- a/backend/internal/httpapi/server.go +++ b/backend/internal/httpapi/server.go @@ -27,6 +27,10 @@ import ( "git.pcux.cn/xuans/Scert/backend/internal/sshkey" ) +type setupSecretWriter interface { + Put(context.Context, string, map[string]string) error +} + type Dependencies struct { Config config.Config ConfigPath string @@ -35,6 +39,7 @@ type Dependencies struct { Servers repository.ServerRepository SSHKeys *sshkey.Service SetupDNS setupDNSVerifier + Secrets setupSecretWriter Firewall firewall.Manager IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error) IssueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error) @@ -56,6 +61,7 @@ type Server struct { servers repository.ServerRepository sshKeys *sshkey.Service setupDNS setupDNSVerifier + secrets setupSecretWriter firewall firewall.Manager issueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error) issueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error) @@ -84,7 +90,7 @@ func New(deps Dependencies) *Server { router.Use(gin.Recovery()) server := &Server{ config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger, - repository: deps.Repository, setupDNS: deps.SetupDNS, firewall: deps.Firewall, router: router, + repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router, servers: deps.Servers, sshKeys: deps.SSHKeys, issueCertificate: deps.IssueCertificate, diff --git a/backend/internal/httpapi/setup.go b/backend/internal/httpapi/setup.go index 07d46ea..47daf7f 100644 --- a/backend/internal/httpapi/setup.go +++ b/backend/internal/httpapi/setup.go @@ -2,6 +2,8 @@ package httpapi import ( "context" + "crypto/rand" + "encoding/base64" "errors" "fmt" "net" @@ -27,37 +29,40 @@ type setupDNSVerifier interface { } type setupRequest struct { - AdminUsername string `json:"admin_username"` - AdminEmail string `json:"admin_email"` - AdminPassword string `json:"admin_password"` - ServerPort int `json:"server_port"` - EmailHTTPEnabled *bool `json:"email_http_enabled"` - EmailProvider string `json:"email_provider"` - EmailEndpoint string `json:"email_endpoint"` - EmailHTTPPath string `json:"email_http_path"` - EmailHTTPLoginPath string `json:"email_http_login_path"` - EmailHTTPAuthMode string `json:"email_http_auth_mode"` - EmailHTTPCredentialRef string `json:"email_http_credential_ref"` - EmailHTTPHeaders map[string]string `json:"email_http_headers"` - EmailEventMode string `json:"email_event_mode"` - EmailIncludeDeploymentDetails bool `json:"email_include_deployment_details"` - EmailIncludeCertificateSerial bool `json:"email_include_certificate_serial"` - EmailIncludeManagementURL bool `json:"email_include_management_url"` - EmailSenderName string `json:"email_sender_name"` - EmailSenderEmail string `json:"email_sender_email"` - Recipients []string `json:"recipients"` - EmailTimeoutSecs int `json:"email_timeout_secs"` - EmailRetryCount int `json:"email_retry_count"` - EmailRetryIntervalsSecs []int `json:"email_retry_intervals_secs"` - DNSProvider string `json:"dns_provider"` - DNSCredentialRef string `json:"dns_credential_ref"` - DNSVerificationToken string `json:"dns_verification_token"` - DNSTestDomain string `json:"dns_test_domain"` - CertificateRoot string `json:"certificate_root"` - WebHostname string `json:"web_hostname"` - WebPublicIP string `json:"web_public_ip"` - WebEnabled *bool `json:"web_enabled"` - HTTPSMode string `json:"https_mode"` + AdminUsername string `json:"admin_username"` + AdminEmail string `json:"admin_email"` + AdminPassword string `json:"admin_password"` + ServerPort int `json:"server_port"` + EmailHTTPEnabled *bool `json:"email_http_enabled"` + EmailProvider string `json:"email_provider"` + EmailEndpoint string `json:"email_endpoint"` + EmailHTTPPath string `json:"email_http_path"` + EmailHTTPLoginPath string `json:"email_http_login_path"` + EmailHTTPAuthMode string `json:"email_http_auth_mode"` + EmailHTTPCredentialRef string `json:"email_http_credential_ref"` + EmailHTTPCredentials map[string]string `json:"email_http_credentials"` + EmailHTTPHeaders map[string]string `json:"email_http_headers"` + EmailEventMode string `json:"email_event_mode"` + EmailIncludeDeploymentDetails bool `json:"email_include_deployment_details"` + EmailIncludeCertificateSerial bool `json:"email_include_certificate_serial"` + EmailIncludeManagementURL bool `json:"email_include_management_url"` + EmailSenderName string `json:"email_sender_name"` + EmailSenderEmail string `json:"email_sender_email"` + Recipients []string `json:"recipients"` + EmailTimeoutSecs int `json:"email_timeout_secs"` + EmailRetryCount int `json:"email_retry_count"` + EmailRetryIntervalsSecs []int `json:"email_retry_intervals_secs"` + DNSProvider string `json:"dns_provider"` + DNSCredentialRef string `json:"dns_credential_ref"` + DNSVerificationToken string `json:"dns_verification_token"` + DNSTestDomain string `json:"dns_test_domain"` + PropagationTimeoutSecs int `json:"propagation_timeout_secs"` + PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"` + CertificateRoot string `json:"certificate_root"` + WebHostname string `json:"web_hostname"` + WebPublicIP string `json:"web_public_ip"` + WebEnabled *bool `json:"web_enabled"` + HTTPSMode string `json:"https_mode"` } type dnsTestRequest struct { @@ -91,19 +96,21 @@ func (s *Server) setupStatus(c *gin.Context) { } } c.JSON(http.StatusOK, gin.H{ - "initialized": cfg.SetupReady, - "phase": phase, - "blockers": blockers, - "server_port": cfg.Server.Port, - "reset_url": cfg.ResetURL(), - "https_mode": cfg.Server.HTTPSMode, - "web_enabled": cfg.Web.Enabled, - "web_hostname": cfg.Web.Hostname, - "web_public_ip": cfg.Web.PublicIP, - "certificate_root": cfg.Paths.Certificate, - "dns_provider": cfg.DNS.Provider, - "dns_verification_state": cfg.DNS.VerificationState, - "dns_test_available": s.setupDNS != nil, + "initialized": cfg.SetupReady, + "phase": phase, + "blockers": blockers, + "server_port": cfg.Server.Port, + "reset_url": cfg.ResetURL(), + "https_mode": cfg.Server.HTTPSMode, + "web_enabled": cfg.Web.Enabled, + "web_hostname": cfg.Web.Hostname, + "web_public_ip": cfg.Web.PublicIP, + "certificate_root": cfg.Paths.Certificate, + "dns_provider": cfg.DNS.Provider, + "dns_verification_state": cfg.DNS.VerificationState, + "dns_test_available": s.setupDNS != nil, + "propagation_timeout_secs": cfg.ACME.PropagationTimeoutSecs, + "propagation_polling_interval_secs": cfg.ACME.PropagationPollingIntervalSecs, }) } @@ -190,38 +197,64 @@ func (s *Server) applySetup(c *gin.Context) { if request.EmailHTTPEnabled != nil { emailHTTPEnabled = *request.EmailHTTPEnabled } + emailCredentialRef := strings.TrimSpace(request.EmailHTTPCredentialRef) + var notificationCredentials map[string]string + var credentialErr error + if emailHTTPEnabled && strings.ToLower(strings.TrimSpace(request.EmailHTTPAuthMode)) != "none" { + if len(request.EmailHTTPCredentials) > 0 { + notificationCredentials, credentialErr = normalizeNotificationCredentials(request.EmailHTTPAuthMode, request.EmailHTTPCredentials) + if credentialErr != nil { + s.writeError(c, http.StatusBadRequest, credentialErr.Error(), nil) + return + } + if s.secrets == nil { + s.writeError(c, http.StatusServiceUnavailable, "HTTP 通知敏感凭据存储尚未初始化", nil) + return + } + emailCredentialRef, credentialErr = newNotificationCredentialReference() + if credentialErr != nil { + s.writeError(c, http.StatusInternalServerError, "生成 HTTP 通知凭据引用失败", credentialErr) + return + } + } else if emailCredentialRef == "" { + s.writeError(c, http.StatusBadRequest, "启用 HTTP 通知认证后必须填写明文凭据或已有凭据引用", nil) + return + } + } updated := s.config err := setup.Apply(&updated, setup.Input{ - AdminUsername: request.AdminUsername, - AdminEmail: request.AdminEmail, - AdminPassword: request.AdminPassword, - ServerPort: request.ServerPort, - EmailHTTPEnabled: emailHTTPEnabled, - EmailProvider: request.EmailProvider, - EmailEndpoint: request.EmailEndpoint, - EmailHTTPPath: request.EmailHTTPPath, - EmailHTTPLoginPath: request.EmailHTTPLoginPath, - EmailHTTPAuthMode: request.EmailHTTPAuthMode, - EmailHTTPCredentialRef: request.EmailHTTPCredentialRef, - EmailHTTPHeaders: request.EmailHTTPHeaders, - EmailEventMode: request.EmailEventMode, - EmailIncludeDeploymentDetails: request.EmailIncludeDeploymentDetails, - EmailIncludeCertificateSerial: request.EmailIncludeCertificateSerial, - EmailIncludeManagementURL: request.EmailIncludeManagementURL, - EmailSenderName: request.EmailSenderName, - EmailSenderEmail: request.EmailSenderEmail, - EmailRecipients: request.Recipients, - EmailTimeoutSecs: request.EmailTimeoutSecs, - EmailRetryCount: request.EmailRetryCount, - EmailRetryIntervalsSecs: request.EmailRetryIntervalsSecs, - DNSProvider: request.DNSProvider, - DNSCredentialRef: request.DNSCredentialRef, - DNSVerified: true, - CertificateRoot: request.CertificateRoot, - WebHostname: request.WebHostname, - WebPublicIP: request.WebPublicIP, - WebEnabled: webEnabled, - HTTPSMode: request.HTTPSMode, + AdminUsername: request.AdminUsername, + AdminEmail: request.AdminEmail, + AdminPassword: request.AdminPassword, + ServerPort: request.ServerPort, + EmailHTTPEnabled: emailHTTPEnabled, + EmailProvider: request.EmailProvider, + EmailEndpoint: request.EmailEndpoint, + EmailHTTPPath: request.EmailHTTPPath, + EmailHTTPLoginPath: request.EmailHTTPLoginPath, + EmailHTTPAuthMode: request.EmailHTTPAuthMode, + EmailHTTPCredentialRef: emailCredentialRef, + EmailHTTPHeaders: request.EmailHTTPHeaders, + EmailEventMode: request.EmailEventMode, + EmailIncludeDeploymentDetails: request.EmailIncludeDeploymentDetails, + EmailIncludeCertificateSerial: request.EmailIncludeCertificateSerial, + EmailIncludeManagementURL: request.EmailIncludeManagementURL, + EmailSenderName: request.EmailSenderName, + EmailSenderEmail: request.EmailSenderEmail, + EmailRecipients: request.Recipients, + EmailTimeoutSecs: request.EmailTimeoutSecs, + EmailRetryCount: request.EmailRetryCount, + EmailRetryIntervalsSecs: request.EmailRetryIntervalsSecs, + DNSProvider: request.DNSProvider, + DNSCredentialRef: request.DNSCredentialRef, + DNSVerified: true, + PropagationTimeoutSecs: request.PropagationTimeoutSecs, + PropagationPollingIntervalSecs: request.PropagationPollingIntervalSecs, + CertificateRoot: request.CertificateRoot, + WebHostname: request.WebHostname, + WebPublicIP: request.WebPublicIP, + WebEnabled: webEnabled, + HTTPSMode: request.HTTPSMode, }) if err != nil { s.writeError(c, http.StatusBadRequest, err.Error(), err) @@ -265,6 +298,15 @@ func (s *Server) applySetup(c *gin.Context) { } updated.Server.TLSCert = savedCertificate.FullChainPath updated.Server.TLSKey = savedCertificate.PrivateKeyPath + if len(notificationCredentials) > 0 { + if err := s.secrets.Put(c.Request.Context(), emailCredentialRef, notificationCredentials); err != nil { + if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil { + s.logger.Error("保存 HTTP 通知凭据失败,且证书回滚失败", "error", rollbackErr) + } + s.writeError(c, http.StatusInternalServerError, "保存 HTTP 通知凭据失败,初始化尚未完成", err) + return + } + } updated.SetupReady = true if err := updated.Validate(); err != nil { if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil { @@ -387,3 +429,49 @@ func isLoopbackRequest(request *http.Request) bool { ip := net.ParseIP(strings.TrimSpace(host)) return ip != nil && ip.IsLoopback() } + +func newNotificationCredentialReference() (string, error) { + buffer := make([]byte, 18) + if _, err := rand.Read(buffer); err != nil { + return "", err + } + return "secret://notification/" + base64.RawURLEncoding.EncodeToString(buffer), nil +} + +func normalizeNotificationCredentials(authMode string, values map[string]string) (map[string]string, error) { + result := make(map[string]string, len(values)) + for key, value := range values { + key = strings.TrimSpace(key) + if key == "" { + continue + } + result[key] = value + } + if len(result) == 0 { + return nil, fmt.Errorf("HTTP 通知凭据不能为空") + } + switch strings.ToLower(strings.TrimSpace(authMode)) { + case "bearer": + if strings.TrimSpace(result["token"]) == "" && strings.TrimSpace(result["access_token"]) == "" { + return nil, fmt.Errorf("Bearer Token 凭据必须包含 token 或 access_token") + } + case "hmac_sha256": + if strings.TrimSpace(result["secret"]) == "" && strings.TrimSpace(result["hmac_secret"]) == "" && strings.TrimSpace(result["key"]) == "" && strings.TrimSpace(result["token"]) == "" { + return nil, fmt.Errorf("HMAC-SHA256 凭据必须包含签名密钥") + } + case "session": + account := result["account"] + if account == "" { + account = result["username"] + } + if account == "" { + account = result["identifier"] + } + if strings.TrimSpace(account) == "" || result["password"] == "" { + return nil, fmt.Errorf("会话认证凭据必须包含账号和密码") + } + default: + return nil, fmt.Errorf("HTTP 通知认证方式无效") + } + return result, nil +} diff --git a/backend/internal/httpapi/setup_test.go b/backend/internal/httpapi/setup_test.go index a68bd63..97540aa 100644 --- a/backend/internal/httpapi/setup_test.go +++ b/backend/internal/httpapi/setup_test.go @@ -28,6 +28,22 @@ type fakeSetupDNSVerifier struct { consumed bool } +type fakeSetupSecretWriter struct { + values map[string]map[string]string +} + +func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value map[string]string) error { + if f.values == nil { + f.values = make(map[string]map[string]string) + } + copyValue := make(map[string]string, len(value)) + for key, item := range value { + copyValue[key] = item + } + f.values[reference] = copyValue + return nil +} + type fakeFirewallManager struct { result firewall.Result openErr error @@ -186,6 +202,8 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) { "dns_credential_ref":"secret://dns/cloudflare/default", "dns_verification_token":"verified-token", "dns_test_domain":"scert.example.test", + "propagation_timeout_secs":1200, + "propagation_polling_interval_secs":15, "certificate_root":"` + filepath.ToSlash(filepath.Join(baseDir, "ssl")) + `", "web_hostname":"scert.example.test", "web_enabled":true, @@ -229,6 +247,9 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) { if len(saved.Notification.Recipients) != 1 { t.Fatalf("通知收件人未去重:%v", saved.Notification.Recipients) } + if saved.ACME.PropagationTimeoutSecs != 1200 || saved.ACME.PropagationPollingIntervalSecs != 15 { + t.Fatalf("Web 初始化未保存 DNS 传播等待配置:timeout=%d interval=%d", saved.ACME.PropagationTimeoutSecs, saved.ACME.PropagationPollingIntervalSecs) + } repeat := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload)) repeat.RemoteAddr = "127.0.0.1:53001" @@ -240,6 +261,65 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) { } } +func TestSetupApplyEncryptsNotificationCredentialsAndPersistsReference(t *testing.T) { + baseDir := t.TempDir() + cfg := config.Default(baseDir) + configPath := filepath.Join(baseDir, "config", "scert.json") + verifier := &fakeSetupDNSVerifier{} + secrets := &fakeSetupSecretWriter{} + server := New(Dependencies{ + Config: cfg, ConfigPath: configPath, Repository: &stubDomainRepository{}, + SetupDNS: verifier, Secrets: secrets, + IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil), + }) + payload := `{ + "admin_username":"root-admin", + "admin_email":"admin@example.test", + "admin_password":"secure-pass-123", + "server_port":8443, + "email_http_enabled":true, + "email_provider":"mail-api", + "email_endpoint":"https://mail.example.test/send", + "email_http_auth_mode":"bearer", + "email_http_credentials":{"token":"plain-token-value"}, + "recipients":["ops@example.test"], + "dns_provider":"cloudflare", + "dns_credential_ref":"secret://dns/cloudflare/default", + "dns_verification_token":"verified-token", + "dns_test_domain":"scert.example.test", + "certificate_root":"` + filepath.ToSlash(filepath.Join(baseDir, "ssl")) + `", + "web_hostname":"scert.example.test", + "web_enabled":true, + "https_mode":"direct" + }` + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload)) + request.RemoteAddr = "127.0.0.1:53000" + request.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK { + t.Fatalf("提交带 HTTP 通知凭据的初始化配置失败:%d %s", response.Code, response.Body.String()) + } + data, err := os.ReadFile(configPath) + if err != nil { + t.Fatalf("读取初始化配置失败:%v", err) + } + if strings.Contains(string(data), "plain-token-value") || strings.Contains(string(data), "email_http_credentials") { + t.Fatal("普通配置文件不应保存 HTTP 通知明文凭据") + } + var saved config.Config + if err := json.Unmarshal(data, &saved); err != nil { + t.Fatalf("解析初始化配置失败:%v", err) + } + if !strings.HasPrefix(saved.Notification.HTTPCredentialRef, "secret://notification/") { + t.Fatalf("初始化配置应保存通知凭据引用:%q", saved.Notification.HTTPCredentialRef) + } + stored, ok := secrets.values[saved.Notification.HTTPCredentialRef] + if !ok || stored["token"] != "plain-token-value" { + t.Fatalf("通知凭据未写入敏感信息存储:%v", secrets.values) + } +} + func TestSetupApplyRejectsUnverifiedDNSConfiguration(t *testing.T) { cfg := config.Default(t.TempDir()) verifier := &fakeSetupDNSVerifier{checkErr: errors.New("DNS 验证令牌无效或已经过期,请重新测试")} @@ -254,6 +334,63 @@ func TestSetupApplyRejectsUnverifiedDNSConfiguration(t *testing.T) { } } +func TestNormalizeNotificationCredentials(t *testing.T) { + tests := []struct { + name string + mode string + values map[string]string + wantErr bool + }{ + {name: "bearer", mode: "bearer", values: map[string]string{"token": "token-value"}}, + {name: "hmac", mode: "hmac_sha256", values: map[string]string{"secret": "secret-value"}}, + {name: "session", mode: "session", values: map[string]string{"account": "test", "password": "password-value"}}, + {name: "missing bearer token", mode: "bearer", values: map[string]string{"name": "test"}, wantErr: true}, + {name: "missing session password", mode: "session", values: map[string]string{"account": "test"}, wantErr: true}, + {name: "unknown mode", mode: "unknown", values: map[string]string{"token": "test"}, wantErr: true}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := normalizeNotificationCredentials(test.mode, test.values) + if (err != nil) != test.wantErr { + t.Fatalf("凭据校验结果不正确:error=%v", err) + } + }) + } +} + +func TestSetupApplyRejectsMissingNotificationCredentials(t *testing.T) { + cfg := config.Default(t.TempDir()) + verifier := &fakeSetupDNSVerifier{} + server := New(Dependencies{ + Config: cfg, ConfigPath: filepath.Join(t.TempDir(), "scert.json"), + Repository: &stubDomainRepository{}, SetupDNS: verifier, + }) + payload := `{ + "admin_username":"root-admin", + "admin_email":"admin@example.test", + "admin_password":"secure-pass-123", + "server_port":8443, + "email_http_enabled":true, + "email_endpoint":"https://mail.example.test", + "email_http_auth_mode":"bearer", + "dns_provider":"cloudflare", + "dns_credential_ref":"secret://dns/cloudflare/test", + "dns_verification_token":"verified-token", + "dns_test_domain":"example.test", + "certificate_root":"/ssl", + "web_hostname":"scert.example.test", + "https_mode":"direct" + }` + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload)) + request.RemoteAddr = "127.0.0.1:53000" + request.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "明文凭据或已有凭据引用") { + t.Fatalf("缺少 HTTP 通知凭据时应被拒绝:%d %s", response.Code, response.Body.String()) + } +} + func TestSetupApplyRejectsOversizedRequest(t *testing.T) { cfg := config.Default(t.TempDir()) server := New(Dependencies{ diff --git a/backend/internal/httpapi/task_api.go b/backend/internal/httpapi/task_api.go index bbfbbb1..880c2fc 100644 --- a/backend/internal/httpapi/task_api.go +++ b/backend/internal/httpapi/task_api.go @@ -80,6 +80,12 @@ func (s *Server) issueDomainAsTask(c *gin.Context) { } _ = s.tasks.UpdateTask(context.Background(), task.ID, status, "certificate_issue", message, &now, &finished) _ = s.tasks.FinishAttempt(context.Background(), attempt.ID, status, message, &finished) + task.Status = status + task.Stage = "certificate_issue" + task.Message = message + task.StartedAt = &now + task.FinishedAt = &finished + task.UpdatedAt = finished if s.audit != nil { auditStatus := status if issueErr != nil { @@ -105,12 +111,6 @@ func (s *Server) issueDomainAsTask(c *gin.Context) { c.JSON(http.StatusBadGateway, response) return } - task.Status = status - task.Stage = "certificate_issue" - task.Message = message - task.StartedAt = &now - task.FinishedAt = &finished - task.UpdatedAt = finished response["task"] = task c.JSON(http.StatusOK, response) } diff --git a/backend/internal/httpapi/task_api_test.go b/backend/internal/httpapi/task_api_test.go index e9e083f..4f6b1b0 100644 --- a/backend/internal/httpapi/task_api_test.go +++ b/backend/internal/httpapi/task_api_test.go @@ -2,6 +2,7 @@ package httpapi import ( "context" + "encoding/json" "errors" "net/http" "net/http/httptest" @@ -110,6 +111,26 @@ func TestTaskAPIReturnsFailureAndKeepsTaskTrace(t *testing.T) { if response.Code != http.StatusBadGateway || !strings.Contains(response.Body.String(), "模拟证书申请失败") { t.Fatalf("失败任务响应错误:%d %s", response.Code, response.Body.String()) } + var payload struct { + Task struct { + Status string `json:"status"` + Stage string `json:"stage"` + Message string `json:"message"` + FinishedAt string `json:"finished_at"` + UpdatedAt string `json:"updated_at"` + } `json:"task"` + TaskStatus string `json:"task_status"` + FinishedAt string `json:"finished_at"` + } + if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil { + t.Fatalf("失败任务响应不是有效 JSON:%v;响应:%s", err, response.Body.String()) + } + if payload.Task.Status != "failed" || payload.Task.Stage != "certificate_issue" || payload.Task.Message != "模拟证书申请失败" { + t.Fatalf("失败任务嵌套状态不一致:%+v", payload.Task) + } + if payload.TaskStatus != "failed" || payload.FinishedAt == "" || payload.Task.FinishedAt == "" || payload.Task.UpdatedAt == "" { + t.Fatalf("失败任务顶层状态或时间字段不完整:%+v", payload) + } items, err := taskRepo.ListTasks(context.Background(), "", 10) if err != nil || len(items) != 1 || items[0].Status != "failed" { t.Fatalf("失败任务状态错误:%+v %v", items, err) diff --git a/backend/internal/setup/setup.go b/backend/internal/setup/setup.go index d85e348..b13c57b 100644 --- a/backend/internal/setup/setup.go +++ b/backend/internal/setup/setup.go @@ -13,36 +13,40 @@ import ( ) type Input struct { - AdminUsername string - AdminEmail string - AdminPassword string - ServerPort int - EmailHTTPEnabled bool - EmailProvider string - EmailEndpoint string - EmailHTTPPath string - EmailHTTPLoginPath string - EmailHTTPAuthMode string - EmailHTTPCredentialRef string - EmailHTTPHeaders map[string]string - EmailEventMode string - EmailIncludeDeploymentDetails bool - EmailIncludeCertificateSerial bool - EmailIncludeManagementURL bool - EmailSenderName string - EmailSenderEmail string - EmailRecipients []string - EmailTimeoutSecs int - EmailRetryCount int - EmailRetryIntervalsSecs []int - DNSProvider string - DNSCredentialRef string - DNSVerified bool - CertificateRoot string - WebHostname string - WebPublicIP string - WebEnabled bool - HTTPSMode string + AdminUsername string + AdminEmail string + AdminPassword string + ServerPort int + EmailHTTPEnabled bool + EmailProvider string + EmailEndpoint string + EmailHTTPPath string + EmailHTTPLoginPath string + EmailHTTPAuthMode string + EmailHTTPCredentialRef string + EmailHTTPHeaders map[string]string + EmailEventMode string + EmailIncludeDeploymentDetails bool + EmailIncludeCertificateSerial bool + EmailIncludeManagementURL bool + EmailSenderName string + EmailSenderEmail string + EmailRecipients []string + EmailTimeoutSecs int + EmailRetryCount int + EmailRetryIntervalsSecs []int + DNSProvider string + DNSCredentialRef string + DNSCredentials map[string]string + DNSTestDomain string + DNSVerified bool + PropagationTimeoutSecs int + PropagationPollingIntervalSecs int + CertificateRoot string + WebHostname string + WebPublicIP string + WebEnabled bool + HTTPSMode string } func Apply(cfg *config.Config, input Input) error { @@ -97,6 +101,12 @@ func Apply(cfg *config.Config, input Input) error { cfg.Admin.Email = adminEmail cfg.Admin.PasswordHash = string(hash) cfg.ACME.AccountEmail = adminEmail + if input.PropagationTimeoutSecs != 0 { + cfg.ACME.PropagationTimeoutSecs = input.PropagationTimeoutSecs + } + if input.PropagationPollingIntervalSecs != 0 { + cfg.ACME.PropagationPollingIntervalSecs = input.PropagationPollingIntervalSecs + } cfg.Server.Port = input.ServerPort cfg.Server.HTTPSMode = input.HTTPSMode cfg.Web.Enabled = input.WebEnabled diff --git a/backend/internal/setup/setup_test.go b/backend/internal/setup/setup_test.go index 3d0086f..d7c0e85 100644 --- a/backend/internal/setup/setup_test.go +++ b/backend/internal/setup/setup_test.go @@ -1,6 +1,9 @@ package setup import ( + "os" + "path/filepath" + "strings" "testing" "git.pcux.cn/xuans/Scert/backend/internal/config" @@ -24,6 +27,7 @@ func TestApplyBuildsReadyConfig(t *testing.T) { AdminUsername: "admin", AdminEmail: "admin@example.com", AdminPassword: "password123", ServerPort: 8080, EmailProvider: "mail-api", EmailEndpoint: "https://mail.example.test/send", EmailRecipients: []string{"a@example.test,b@example.test", "a@example.test"}, DNSProvider: "cloudflare", DNSCredentialRef: "credential-1", DNSVerified: true, CertificateRoot: cfg.Paths.Certificate, + PropagationTimeoutSecs: 1200, PropagationPollingIntervalSecs: 15, WebHostname: "panel.example.com", WebEnabled: true, }) if err != nil { @@ -41,8 +45,44 @@ func TestApplyBuildsReadyConfig(t *testing.T) { if cfg.ResetURL() != "https://panel.example.com/reset" { t.Fatalf("密码重置地址生成错误:%s", cfg.ResetURL()) } + if cfg.ACME.PropagationTimeoutSecs != 1200 || cfg.ACME.PropagationPollingIntervalSecs != 15 { + t.Fatalf("DNS 传播等待配置保存错误:timeout=%d interval=%d", cfg.ACME.PropagationTimeoutSecs, cfg.ACME.PropagationPollingIntervalSecs) + } } +func TestApplyRejectsInvalidPropagationSettings(t *testing.T) { + cases := []struct { + name string + timeout int + interval int + }{ + {name: "等待时间小于最小值", timeout: 0 - 1, interval: 10}, + {name: "等待时间超过最大值", timeout: 86401, interval: 10}, + {name: "检测间隔超过等待时间", timeout: 900, interval: 901}, + } + + for _, item := range cases { + t.Run(item.name, func(t *testing.T) { + cfg := config.Default(t.TempDir()) + err := Apply(&cfg, Input{ + AdminUsername: "admin", + AdminEmail: "admin@example.com", + AdminPassword: "password123", + ServerPort: 8080, + DNSProvider: "cloudflare", + DNSCredentialRef: "credential-1", + DNSVerified: true, + PropagationTimeoutSecs: item.timeout, + PropagationPollingIntervalSecs: item.interval, + WebHostname: "panel.example.com", + WebEnabled: true, + }) + if err == nil { + t.Fatal("非法 DNS 传播等待配置不应完成初始化") + } + }) + } +} func TestApplyRejectsWebIPAsHostnamePair(t *testing.T) { cfg := config.Default(t.TempDir()) err := Apply(&cfg, Input{ @@ -77,3 +117,48 @@ func TestApplyUsesAdminEmailAndStoresNotificationOptions(t *testing.T) { t.Fatalf("HTTP 通知配置未正确保存:%+v", cfg.Notification) } } + +func TestApplyAndSaveStoresOnlyCredentialReference(t *testing.T) { + root := t.TempDir() + cfg := config.Default(root) + credentialRef := "secret://dns/cloudflare/test" + secretValue := "test-dns-token" + if err := Apply(&cfg, Input{ + AdminUsername: "admin", + AdminEmail: "admin@example.com", + AdminPassword: "password123", + ServerPort: 8080, + DNSProvider: "cloudflare", + DNSCredentialRef: credentialRef, + DNSVerified: true, + CertificateRoot: cfg.Paths.Certificate, + WebHostname: "panel.example.com", + WebEnabled: true, + }); err != nil { + t.Fatalf("构造初始化配置失败:%v", err) + } + + path := filepath.Join(root, "config", "scert.json") + if err := cfg.Save(path); err != nil { + t.Fatalf("保存初始化配置失败:%v", err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("读取初始化配置失败:%v", err) + } + content := string(data) + if !strings.Contains(content, credentialRef) { + t.Fatalf("初始化配置应保存凭据引用:%s", content) + } + if strings.Contains(content, secretValue) || strings.Contains(content, "api_token") { + t.Fatalf("初始化配置不应保存 DNS 明文凭据:%s", content) + } + + loaded, err := config.Load(path) + if err != nil { + t.Fatalf("重新读取初始化配置失败:%v", err) + } + if loaded.DNS.CredentialRef != credentialRef { + t.Fatalf("重新读取后凭据引用不正确:%q", loaded.DNS.CredentialRef) + } +} diff --git a/deploy/README.md b/deploy/README.md index c462fa3..4ba73a4 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -60,7 +60,7 @@ systemctl start Scert-admin systemctl stop Scert-admin ``` -`Scert-admin` 不监听任何 TCP/UDP 端口。启动后,它只维护 Scert 主服务 `/reset` 路径的短时激活租约并输出一次性校验码;停止后入口立即失效,异常退出后入口会在租约过期时失效。云安全组只需由管理员根据初始化提示放行主服务端口。 +`Scert-admin` 不监听任何 TCP/UDP 端口。启动后,它只维护 Scert 主服务 `/reset` 路径的短时激活租约,并将一次性校验码写入 `/run/scert-admin/reset-code` 受保护临时文件,不写入标准输出或 systemd 日志;停止后入口立即失效,异常退出后入口会在租约过期时失效。管理员可使用 `sudo cat /run/scert-admin/reset-code` 读取校验码,校验码在成功消费、服务停止或租约失效后自动销毁。云安全组只需由管理员根据初始化提示放行主服务端口。 ## 参数说明 diff --git a/deploy/install-linux.sh b/deploy/install-linux.sh index 2203037..d676ffd 100644 --- a/deploy/install-linux.sh +++ b/deploy/install-linux.sh @@ -116,8 +116,8 @@ validate_managed_paths() { "$INSTALL_DIR/scert" \ "$INSTALL_DIR/scert-admin" \ "$INSTALL_METADATA_FILE" \ - "$INSTALL_DIR/docs/Scert服务管理说明.md" \ - "$INSTALL_DIR/docs/Scert-admin服务管理说明.md" \ + "$INSTALL_DIR/docs/Scert-service-management.md" \ + "$INSTALL_DIR/docs/Scert-admin-service-management.md" \ "$SERVICE_DIR/Scert.service" \ "$SERVICE_DIR/Scert-admin.service" \ "$SERVICE_DROP_IN_DIR" \ @@ -227,10 +227,10 @@ install_service_files() { install -o root -g root -m 0644 \ "$SCRIPT_DIR/systemd/Scert服务管理说明.md" \ - "$INSTALL_DIR/docs/Scert服务管理说明.md" + "$INSTALL_DIR/docs/Scert-service-management.md" install -o root -g root -m 0644 \ "$SCRIPT_DIR/systemd/Scert-admin服务管理说明.md" \ - "$INSTALL_DIR/docs/Scert-admin服务管理说明.md" + "$INSTALL_DIR/docs/Scert-admin-service-management.md" } reload_systemd() { diff --git a/deploy/systemd/Scert-admin.service b/deploy/systemd/Scert-admin.service index 7cf7f1a..b5a6bf3 100644 --- a/deploy/systemd/Scert-admin.service +++ b/deploy/systemd/Scert-admin.service @@ -1,6 +1,6 @@ [Unit] Description=Scert-admin 临时密码重置入口激活器 -Documentation=file:///scert/docs/Scert-admin服务管理说明.md +Documentation=file:///scert/docs/Scert-admin-service-management.md After=network-online.target Wants=network-online.target ConditionPathExists=/scert/conf/scert.json @@ -10,7 +10,9 @@ Type=simple User=Scert Group=Scert WorkingDirectory=/scert -ExecStart=/scert/scert-admin --config /scert/conf/scert.json +RuntimeDirectory=scert-admin +RuntimeDirectoryMode=0700 +ExecStart=/scert/scert-admin --config /scert/conf/scert.json --code-output /run/scert-admin/reset-code KillSignal=SIGTERM TimeoutStopSec=15 Restart=no @@ -20,7 +22,7 @@ NoNewPrivileges=yes PrivateTmp=yes ProtectHome=yes ProtectSystem=full -ReadWritePaths=/scert/data /scert/log +ReadWritePaths=/scert/data /scert/log /run/scert-admin RestrictAddressFamilies=AF_UNIX # Scert-admin 不监听任何 TCP/UDP 端口,只维护主服务 /reset 路径的短时激活租约。 diff --git a/deploy/systemd/Scert-admin服务管理说明.md b/deploy/systemd/Scert-admin服务管理说明.md index 38cdc28..703091d 100644 --- a/deploy/systemd/Scert-admin服务管理说明.md +++ b/deploy/systemd/Scert-admin服务管理说明.md @@ -6,6 +6,12 @@ Linux 安装程序必须同时安装 `Scert` 和 `Scert-admin` 的 systemd 单元,但不得执行 `systemctl enable Scert-admin`,不得为 `Scert-admin` 创建开机启动软链接,也不得配置 `Restart=always` 或其他自动拉起策略。 +## 一次性校验码文件 + +Linux systemd 安装默认将校验码写入 `/run/scert-admin/reset-code`,该目录由 systemd 创建并设置为 `0700`,文件由 Scert-admin 创建并设置为 `0600`。直接运行程序时可以通过 `--code-output` 指定受保护的临时文件路径;不要将该路径放入公开目录、日志目录或备份目录。 + +校验码文件只用于人工读取,不属于配置数据。读取后不得复制到工单、聊天记录或日志中;密码重置成功后文件会立即销毁。 + ## 支持的生命周期控制 日常运行时,`Scert-admin` 只支持以下两个控制命令: @@ -32,7 +38,7 @@ systemd 无法阻止 root 或具备等效系统权限的操作者调用 `status` 5. 安装器、桌面端和运维文档只提供 `start`、`stop` 两个日常控制入口。 6. 任何需要重新加载 unit 的行为仅限安装或升级阶段,不能通过 Web 管理界面触发。 7. 激活租约有效期为 90 秒,每 30 秒刷新;systemd 使用 `RuntimeMaxSec=30min` 将单次激活最长时间限制为 30 分钟。 -8. 启动时生成的一次性校验码只在当前终端显示,状态文件仅保存 SHA-256 摘要,不保存明文校验码。 +8. 启动时生成的一次性校验码不会写入标准输出或 systemd 日志。校验码只写入受保护的临时文件;systemd 单元使用 `RuntimeDirectory=scert-admin` 和 `RuntimeDirectoryMode=0700`,文件权限为 `0600`,仅允许 `Scert` 用户和 root 读取。 这组限制可以避免服务因安装配置被纳入开机启动、避免服务自动反复拉起,并彻底取消独立密码重置监听端口。需要注意:`/reset` 与 Scert 主服务共享 HTTPS 端口,激活期间仍可能被外部访问,因此完整密码重置实现还必须校验一次性校验码、限制请求频率、单次消费校验码并记录审计日志。不能把拥有 root 权限的恶意操作者从 systemd 管理能力中排除。 @@ -54,4 +60,4 @@ systemctl restart Scert-admin 安装完成后只提示管理员在确有需要时手动执行 `systemctl start Scert-admin`;不需要密码重置时保持服务停止,完成重置后立即执行 `systemctl stop Scert-admin`。 -当前实现已经接入一次性校验码、单次消费、密码复杂度校验、CSRF、同源校验、失败限流、配置原子保存和审计日志。密码重置成功后 `/reset` 立即关闭,Scert-admin 后续刷新旧租约也会自动终止。一次性校验码仍会在直接运行或 systemd 标准输出中呈现;正式上线前必须替换为不把明文校验码长期保留在持久日志中的受保护本地呈现机制。 +当前实现已经接入一次性校验码、单次消费、密码复杂度校验、CSRF、同源校验、失败限流、配置原子保存和审计日志。密码重置成功后 `/reset` 立即关闭,Scert-admin 后续刷新旧租约也会自动终止。启动后请按终端提示,使用 root 或 `Scert` 用户读取受保护的临时校验码文件:`sudo cat /run/scert-admin/reset-code`。校验码在密码重置成功、服务停止或租约失效后自动销毁。 diff --git a/deploy/systemd/Scert.service b/deploy/systemd/Scert.service index 3476012..a88eaa6 100644 --- a/deploy/systemd/Scert.service +++ b/deploy/systemd/Scert.service @@ -1,6 +1,6 @@ [Unit] Description=Scert SSL 证书管理核心服务 -Documentation=file:///scert/docs/Scert服务管理说明.md +Documentation=file:///scert/docs/Scert-service-management.md After=network-online.target Wants=network-online.target ConditionPathExists=/scert/conf/scert.json diff --git a/doc/SSL服务程序技术架构设计文档.md b/doc/SSL服务程序技术架构设计文档.md index 7b05f53..25e1ae2 100644 --- a/doc/SSL服务程序技术架构设计文档.md +++ b/doc/SSL服务程序技术架构设计文档.md @@ -157,6 +157,8 @@ CLI 在初始化完成后不直接操作数据库。`init` 负责交互式填写 - `lego`、DNS provider、证书解析、任务调度和部署逻辑均作为 Go 模块或内部适配器实现,减少 Linux 与 Windows 的行为差异。 - 初始化阶段仍需要预检公网连通性、DNS API 权限、证书存储目录、系统时间和文件权限;这些预检必须使用 Go 实现,不依赖平台特定 Shell 命令。 - DNS 凭据只以受控配置对象传递到 provider,禁止出现在命令行参数、日志、任务错误详情和 API 响应中。 +- DNS-01 传播最大等待时间:默认900秒,可通过配置修改。 +- DNS-01 传播检测间隔:默认10秒,不得大于最大等待时间。 - 证书链和私钥校验优先使用 Go 标准库 `crypto/x509`;只有确实需要调用外部 Web 服务器检查命令时,才通过平台命令执行适配器运行白名单命令。 - Windows 和 Linux 的服务注册、文件权限、路径规范化和系统托盘仍由平台适配层分别实现。 - 安装、升级和卸载不得删除用户证书、数据库或备份;所有删除操作必须经过 Web/CLI 明确确认并写入审计日志。 @@ -543,6 +545,8 @@ POST /api/v1/domains/{id}/renew - 允许域名级覆盖:需要时覆盖全局 DNS 配置 - CNAME 委派:自动创建、失败手动提示 - DNS 传播检测超时 +- DNS-01 传播最大等待时间:默认900秒,可通过配置修改。 +- DNS-01 传播检测间隔:默认10秒,不得大于最大等待时间。 - 测试 DNS 权限和 Zone **三、部署服务器配置** @@ -652,7 +656,6 @@ POST /api/v1/domains/{id}/test-servers | check_interval_days | 常规检查间隔,默认 3 天 | | near_expiry_check_days | 临近到期检查阈值,默认 10 天 | | renewal_threshold_days | 自动续期阈值,默认 6 天 | -| emergency_threshold_days | 紧急重试阈值,默认 3 天 | | next_check_at | 下一次计划检查时间 | | next_renewal_at | 下一次计划续期时间,可为空 | | notification_rule_id | 域名级通知规则引用 | diff --git a/doc/SSL服务程序需求确认文档.md b/doc/SSL服务程序需求确认文档.md index 07db5ad..0b96e13 100644 --- a/doc/SSL服务程序需求确认文档.md +++ b/doc/SSL服务程序需求确认文档.md @@ -104,6 +104,12 @@ - [x] 支持 DNSPod API Token - [x] 预留其他 DNS 服务商适配接口 - [x] 支持 CNAME 委派方式 +- [x] 已确认需求:配置 DNS API 凭据时允许在 CLI 和 Web 初始化界面中明文查看,便于用户核对输入内容;提交保存后不得将明文凭据写入普通配置文件、数据库字段、日志或命令行输出。 + - 【用户补充 U-074】(请填写): + - 补充内容:配置时允许明文显示,存入数据库和调用时加密 + - 确认结果:已填写 +- [x] 已确认需求:DNS API 凭据在线验证期间仅在内存中使用;验证成功后写入加密敏感信息存储并返回凭据引用,证书申请和续期时根据凭据引用解密后调用 Provider。 + - 【实现约束】:Web 和 CLI 不得把完整凭据写入响应、日志、错误信息、测试输出或备份;配置文件只保存 `secret://` 凭据引用。 - [x] 第一阶段 DNS 验证方式支持 Cloudflare、阿里云 DNS、DNSPod、CNAME 委派、华为云、腾讯云、AWS Route 53、Google Cloud DNS,并预留其他服务商适配接口。 - [x] 已确认需求:第一阶段使用 Let's Encrypt 作为 ACME CA,并使用 `go-acme/lego` 负责证书申请、DNS-01 验证和自动续期。 - 【用户补充 U-007】(请填写): @@ -539,6 +545,8 @@ web页面:站内信提示全部的通知状态 - [x] DNS API 密钥加密存储 - [x] SMTP 密码加密存储 - [x] 日志中禁止记录明文密钥 +- [x] 已确认需求:敏感凭据在配置录入阶段允许明文显示,但仅限当前配置页面或当前交互输入过程;保存时使用 AES-GCM 等认证加密方式持久化,业务调用时按凭据引用解密,普通配置和数据库业务字段不保存明文。 + - 【安全边界】:明文只允许短时存在于进程内存;验证失败、取消配置或保存失败时不得留下可复用的普通配置记录;敏感信息文件和主密钥继续使用受限权限保护。 - [x] 所有重要操作记录审计日志 - [x] 已确认需求:使用主密码保护的加密配置。 - 【用户补充 U-063】(请填写): diff --git a/doc/Scert开发任务清单.md b/doc/Scert开发任务清单.md index 70b29bb..63f5dd7 100644 --- a/doc/Scert开发任务清单.md +++ b/doc/Scert开发任务清单.md @@ -1397,13 +1397,50 @@ Linux amd64 可以交叉编译 - [ ] 接入阿里云 DNS、DNSPod/腾讯云、华为云、AWS Route 53 和 Google Cloud DNS 在线适配器。 - [ ] 完成 CNAME 委派的目标 Provider 组合验证流程。 -- [ ] 将 CLI `scert init` 从“凭据引用加手动确认”升级为真实 DNS 在线验证流程。 +- [x] 将 CLI `scert init` 从“凭据引用加手动确认”升级为真实 DNS 在线验证流程;交互输入允许明文查看,验证通过后只保存加密凭据引用。 - [ ] 集成 `go-acme/lego` 真实证书签发、续期和初始化管理后台证书部署。 - [ ] 实现 HTTPS 双模式实际启动和初始化完成后的安全切换。 -- [ ] 将敏感信息密文文件保存升级为安全原子替换,并补充异常中断恢复测试。 +- [x] 将敏感信息密文文件保存升级为安全原子替换,并补充异常替换失败时保留旧文件的测试。 - [ ] 清理过期、重复测试或放弃初始化所产生的未引用 DNS 凭据。 - [ ] 完成 Scert-admin 受保护的本地密码重置通道、安装器和系统服务。 - [!] MySQL 5.7/8.0 真实实例测试仍等待明确的 DSN、端口、账号和密码;不得通过 PATH 自动判断 MySQL 实例。 + +## 五十七、配置凭据明文查看与加密存储复审记录(2026-08-28) + +### 57.1 需求清单 + +- [x] 配置阶段允许用户在 CLI 中明文查看 DNS API 凭据,便于核对输入内容。 +- [x] 配置阶段允许用户在 Web 初始化页面中切换 DNS 凭据的明文显示和隐藏显示。 +- [x] DNS 凭据在线验证时只在进程内存中传递给 Provider 测试器。 +- [x] 验证成功后使用 AES-GCM 加密写入敏感信息存储,普通配置文件只保存 `secret://` 凭据引用。 +- [x] 证书申请和续期通过凭据引用从敏感信息存储解密后创建 DNS Provider,不要求业务配置保存明文凭据。 +- [x] 验证失败、初始化提交失败或配置保存失败时,不消费验证令牌,不把明文凭据写入普通配置或日志。 + +### 57.2 实现和测试状态 + +- [x] CLI 动态读取 DNS Provider 凭据字段,并在明文输入提示中明确说明提交后的加密保存边界。 +- [x] Web 初始化向导新增“显示凭据明文”控制项;隐藏状态使用掩码显示,JSON 凭据不在隐藏状态下暴露内容。 +- [x] 增加 CLI 凭据输入、验证、加密保存、输入清空和临时凭据清理测试。 +- [x] 增加最终 `scert.json` 只保存 DNS 凭据引用、不保存 Token 或字段名的测试。 +- [x] 增加证书服务根据加密凭据引用解密后创建 DNS Provider 的测试。 +- [x] 增加敏感信息密文文件不包含明文凭据、权限受限和原子替换失败保留旧文件的测试。 + +### 57.3 验证结果 + +- [✓] `go test -race ./...` 通过。 +- [✓] `go vet ./...` 通过。 +- [✓] 前端 `npm.cmd run build` 通过。 +- [✓] 代码和文档中未新增明文测试凭据输出;测试使用的凭据仅用于断言,未写入仓库文件。 + +### 57.4 复审边界 + +- [!] 浏览器真实操作时,初始化页面仍应限制为本机访问;明文凭据只应在用户明确操作期间短时显示。 +- [!] 生产环境仍需继续执行真实 DNS Provider、Let’s Encrypt、MySQL 5.7/8.0 和远程部署验收;本轮自动化测试不替代实机验收。 +- [!] 未引用敏感信息的定期清理策略仍需后续实现,不能在本轮擅自删除可能仍被业务引用的密文记录。 + +### 57.5 复审结论 + +本轮“配置时可明文查看、保存时加密、调用时按引用解密”的代码链路和自动化测试已完成并通过复审。明文凭据不进入普通配置文件、业务数据库字段、日志、错误响应或 Git 文件;生产级部署和真实外部服务验收仍按既有边界执行。 --- ## 三十一、敏感信息文件原子写入复审记录(2026-08-26) @@ -2097,3 +2134,452 @@ Linux amd64 可以交叉编译 ### 48.3 复审结论 本轮已完成 HTTP 邮件通知的 UTF-8 编码、业务响应判断、会话失效刷新和配置入口开发,并通过自动化验证;同时已通过临时邮件服务的接口详情确认修复后的中文内容正常。Scert 代码链路已经避免因客户端默认字符集导致的中文乱码,但最终收件邮箱客户端的到达和渲染仍需在发布环境继续复核。 + +## 四十九、持续开发复审记录(2026-08-28) + +### 49.1 本轮需求清单 + +- [x] 继续复审上一轮 Ubuntu 模拟测试后的配置、任务、重置地址、安装服务和数据库备份恢复改动。 +- [x] 增强 MySQL 5.7/8.0 备份 SQL 的数据字面量和恢复语句拆分兼容性。 +- [x] 补充失败证书任务 HTTP 响应的嵌套状态、顶层状态和完成时间断言。 +- [x] 补充管理页面域名带路径时的 `/reset` 地址边界测试。 +- [x] 复核 systemd 技术文档路径与 Linux 安装脚本复制路径的一致性。 +- [x] 执行本地全量自动化验证和 Windows/Linux amd64 交叉构建。 + +### 49.2 本轮开发任务状态 + +- [x] MySQL 备份导出支持 `sql.RawBytes`,并对字符串中的反斜杠、空字节、换行、回车、控制字符和单引号进行 SQL 字面量转义。 +- [x] MySQL 恢复语句拆分器保留 `/*!...*/` 和 `/*+...*/` 可执行注释,避免丢失 MySQL 版本条件语句或优化提示。 +- [x] 失败证书任务返回 JSON 中的 `task.status`、`task.stage`、`task.message`、完成时间、更新时间与 `task_status` 已增加一致性测试。 +- [x] `/reset` 地址生成支持不带协议的域名、完整 URL、IPv4、IPv6、显式端口和附带路径的域名输入。 +- [x] systemd unit 使用 ASCII 技术文档文件名,安装脚本保留中文源文档并复制为技术文件名。 + +### 49.3 自动化验证状态 + +- [✓] `go test ./...` 通过。 +- [✓] `go test -race ./...` 通过。 +- [✓] `go vet ./...` 通过。 +- [✓] `go mod verify` 通过。 +- [✓] `npm.cmd run build` 通过。 +- [✓] Windows amd64 核心服务和 `Scert-admin` 交叉构建通过。 +- [✓] Linux amd64 核心服务和 `Scert-admin` 交叉构建通过。 +- [✓] `git diff --check` 通过;Git 输出的 LF/CRLF 提示不属于代码差异错误。 +- [✓] 源码范围未发现 `acme.sh`、旧的 `super-admin-reset` 或旧独立重置端口配置引用;测试中保留的旧字段字符串仅用于确认配置不会再次写入该字段。 +- [✓] 本轮未删除文件,未清理 `.runtime`,未执行 Git 提交、推送、重置或强制操作。 + +### 49.4 当前边界和后续验收 + +- [!] 尚未使用真实 MySQL 5.7 和 MySQL 8.0 实例执行备份、恢复、迁移和回滚;当前结论为代码级和 SQLite 自动化验证通过。 +- [!] 尚未在真实 Let’s Encrypt、DNS Provider、远程 SSH/SFTP、Windows 服务器和各类反向代理环境中完成端到端验收。 +- [!] 尚未完成生产级 HTTPS 终止、高级代理内部 HTTPS、Wails 桌面安装器、Windows Service 和跨平台防火墙的完整实机验收。 +- [!] `Scert-admin` 一次性重置入口仍需受保护的本地校验码呈现机制,不能把标准输出校验码作为生产方案。 + +### 49.5 复审结论 + +本轮可以在本机独立验证的代码修复、测试和构建任务已完成并通过复审。项目仍处于“本地开发复审通过、真实环境和产品级验收未完成”状态,不能据此宣称完整需求已全部交付。 + +## 五十、Ubuntu 22.04 服务生命周期复测与重置地址修复记录(2026-08-28) + +### 50.1 本轮需求清单 + +- [✓] 使用 Ubuntu 22.04 测试环境复测 `Scert` 和 `Scert-admin` 的手动启停流程。 +- [✓] 确认 `Scert-admin` 不开机自启动、不监听独立 TCP/UDP 端口,只通过 `systemctl start Scert-admin` 和 `systemctl stop Scert-admin` 控制。 +- [✓] 确认 `Scert-admin` 启动后 `/reset` 可用,停止后 `/reset` 返回 404。 +- [✓] 按已确认规则修复重置地址,不在 `https://域名或IP/reset` 中暴露主服务端口。 +- [✓] 同步当前 Linux amd64 构建产物到 Ubuntu 测试机,并保留远程旧二进制备份。 +- [✓] 复核本机全量测试、竞态测试、静态检查、模块校验和前端构建。 + +### 50.2 Ubuntu 22.04 实测结果 + +- [✓] 测试环境为 Ubuntu 22.04.5 LTS,systemd 版本为 249.11。 +- [✓] `Scert.service` 使用当前构建产物后正常启动并保持 `active` 状态。 +- [✓] `Scert-admin.service` 使用当前构建产物后可以手动启动并保持 `active` 状态。 +- [✓] `systemctl is-enabled Scert-admin` 返回 `static`,服务未配置 `[Install]` 和 `WantedBy=`,不能纳入开机启动。 +- [✓] `ss -lntup` 仅观察到核心 `Scert` 监听 `*:5200`,没有发现 `Scert-admin` 独立监听端口。 +- [✓] `Scert-admin` 启动后访问 `/reset` 返回 HTTP 200,页面中文正常显示。 +- [✓] `systemctl stop Scert-admin` 后访问 `/reset` 返回 HTTP 404,临时入口已关闭。 +- [✓] systemd unit 的 `Documentation` 已同步为 ASCII 技术文档路径,`systemctl show` 不再出现中文路径 URL 警告。 + +### 50.3 本轮修复内容 + +- [✓] `Config.ResetURL()` 现在始终根据管理域名或公网 IP 生成不带端口的 `https://域名或IP/reset` 地址。 +- [✓] 保留 IPv4、IPv6、完整 URL、附带路径和显式端口输入的解析能力,但不把输入端口写入公开重置地址。 +- [✓] 更新配置、初始化、管理接口和重置控制器相关测试,覆盖不带端口的域名、IPv4、IPv6、完整 URL和附带路径场景。 +- [✓] 测试机直接模式使用临时自签名测试证书启动,仅用于本次 HTTPS 服务生命周期验证,不代表生产证书验收。 + +### 50.4 自动化验证状态 + +- [✓] `go test ./...` 通过。 +- [✓] `go test -race ./...` 通过。 +- [✓] `go vet ./...` 通过。 +- [✓] `go mod verify` 通过。 +- [✓] `npm.cmd run build` 通过。 +- [✓] `git diff --check` 通过;Git 输出的换行格式提示不属于差异错误。 +- [✓] Linux amd64 核心服务和 `Scert-admin` 重新构建并在 Ubuntu 22.04 测试机启动验证通过。 + +### 50.5 当前边界 + +- [!] 测试机使用的是临时自签名证书,尚未完成 Let’s Encrypt Production 真实申请、证书链校验和公网域名访问验收。 +- [!] 尚未使用真实 DNS API 权限执行 DNS-01 记录创建、传播检测、清理和证书续期。 +- [!] 尚未完成真实远程 SSH/SFTP 部署、Nginx reload、部署失败回滚以及 Windows 服务器实测。 +- [!] `Scert-admin` 一次性校验码当前仍通过标准输出和 systemd 日志呈现,正式生产前需要替换为受保护的本地呈现机制。 +- [!] 当前测试机原有 SQLite 配置未切换为 MySQL,MySQL 5.7 和 8.0 的真实迁移、备份、恢复和回滚仍需单独验收。 + +### 50.6 复审结论 + +Ubuntu 22.04 上的核心服务启动、`Scert-admin` 手动控制、无独立重置端口、`/reset` 入口启停生命周期和当前构建产物验证通过。本轮同时修复了重置地址仍暴露主服务端口的问题。项目仍为“本地代码和受控测试环境复审通过”,真实 ACME、DNS、远程部署、生产 HTTPS、Windows 和 MySQL 双版本验收仍未完成。 + +## 五十一、真实环境集成测试记录(2026-08-28) + +### 51.1 本轮测试范围 + +- [x] 使用临时邮件服务执行真实登录和邮件发送接口调用。 +- [✓] 在 Ubuntu 22.04 测试机上使用独立 MySQL 数据库执行 Scert 迁移。 +- [✓] 在独立 MySQL 数据库中写入中文配置和域名测试数据。 +- [✓] 执行 Scert MySQL 备份,检查备份文件权限和内容可恢复性。 +- [✓] 将备份恢复到第二个独立 MySQL 数据库,并核对迁移、配置和域名数据。 +- [✓] 停止临时 MySQL 测试服务,确认原有 `Scert.service` 和 `5200` 监听不受影响。 + +### 51.2 临时邮件服务真实调用结果 + +- [x] 登录接口返回 HTTP 200,业务错误码为 `0`。 +- [x] 邮件发送接口返回 HTTP 200,业务错误码为 `0`。 +- [x] 请求使用 UTF-8 中文主题、纯文本正文、HTML 正文和外部收件人。 +- [x] 邮件服务实际登录响应只返回会话 Cookie,当前响应未返回 `smail_csrf` Cookie;在本次部署中,携带会话和同源请求头即可完成发送。 +- [!] 尚未从外部收件箱客户端确认最终投递、中文显示和邮件状态异步处理结果;API 返回成功只代表邮件已通过接口校验并创建发送任务。 +- [!] 需要在正式接入前确认临时服务部署版本是否与 `doc/后端接口说明文档.md` 中的 CSRF 约定一致,并保留无 CSRF Cookie 的兼容行为或补充服务端配置。 + +测试过程中未将密码、会话 Cookie 或令牌写入 Scert 配置、日志、Git 文件或本任务清单。 + +### 51.3 Ubuntu 22.04 MySQL 8.0 真实测试结果 + +测试机信息: + +```text +系统:Ubuntu 22.04.5 LTS +MySQL:8.0.46-0ubuntu0.22.04.3 +监听端口:3306 +连接方式:本机 Unix Socket,使用独立测试数据库 +``` + +- [✓] 创建独立数据库 `scert_real_test_20260828`,字符集为 `utf8mb4`;未修改原有数据库。 +- [✓] 使用当前 Scert 二进制和 MySQL DSN 启动临时服务,应用启动自动完成 1—4 号迁移。 +- [✓] 迁移后确认存在 `settings`、`domains`、`tasks`、`audit_logs`、`servers`、`domain_servers`、`task_attempts` 和 `schema_migrations` 表。 +- [✓] 写入中文设置项和域名记录,读取结果与写入内容一致。 +- [✓] 执行 `scert backup`,生成 `scert.json` 和 `scert.sql` 备份。 +- [✓] SQL 备份文件权限为 `600`。 +- [✓] 创建第二个独立数据库 `scert_real_restore_20260828`,执行 `scert restore` 后,迁移版本 1—4、中文设置项和域名记录均恢复正确。 +- [✓] 临时服务停止后,原有 `Scert.service` 仍为运行状态,原有 `5200` 端口保持监听,临时 `5290` 端口已关闭。 + +### 51.4 MySQL 5.7 兼容性状态 + +- [!] 本轮未找到可安全使用的 MySQL 5.7 实际服务授权账号,未对本机或测试机的 MySQL 5.7 实例进行登录、迁移、备份或恢复操作。 +- [✓] 已通过代码级迁移语句兼容性检查;当前实现避免使用 MySQL 5.7 不支持的 `ADD COLUMN IF NOT EXISTS`,并在迁移前查询字段和索引是否存在。 +- [!] MySQL 5.7 仍需使用独立测试库完成真实迁移、中文数据、备份、恢复和重复迁移幂等性验证后,才能标记为复审通过。 + +### 51.5 DNS、ACME 和远程部署边界 + +- [!] 当前没有获得可确认的真实测试域名和可执行的 DNS API 凭据,本轮未创建或清理 `_acme-challenge` 记录,未执行 Let’s Encrypt Staging 或 Production 申请。 +- [!] 当前未执行真实 SSH/SFTP 证书推送、Nginx/Caddy/Apache reload、失败回滚和部署后公网 HTTPS 校验。 +- [!] Ubuntu 测试机本轮使用的临时自签名证书只用于 HTTPS 服务生命周期验证,不能作为 Let’s Encrypt 证书链验收结果。 + +### 51.6 本轮复审结论 + +- [✓] 临时邮件服务的真实登录和发送接口调用通过,Scert 当前 HTTP 通知请求格式与该部署的接口行为兼容。 +- [✓] Ubuntu 22.04 + MySQL 8.0 的 Scert 迁移、中文数据读写、备份和恢复通过。 +- [x] 外部邮箱最终收件、MySQL 5.7 真实实例、DNS API、Let’s Encrypt、远程服务器部署和多类反向代理仍处于等待真实环境或凭据验证状态。 + +当前准确结论: + +```text +Scert 本地代码、Ubuntu 22.04 服务生命周期、HTTP 邮件接口调用和 MySQL 8.0 独立数据库流程已完成验证; +外部邮箱最终投递、MySQL 5.7 实例、DNS/ACME 证书申请、远程部署和生产级跨平台验收仍未完成。 +``` + +## 五十二、持续开发:MySQL 恢复失败保护(2026-08-28) + +### 52.1 本轮需求清单 + +- [✓] 复审当前未提交代码,确认不覆盖两个已有补丁文件,不执行文件删除和 Git 操作。 +- [✓] 检查 MySQL 备份和恢复流程的失败安全边界。 +- [✓] 补充 MySQL 恢复前快照和失败回滚保护。 +- [✓] 防止不同数据库类型的备份被错误恢复。 +- [✓] 完成 Go、前端和差异检查。 + +### 52.2 本轮代码调整 + +- [✓] MySQL 恢复前在配置的备份目录创建 `scert-before-restore-*` 快照目录。 +- [✓] 快照目录权限设置为 `700`,SQL 快照文件权限设置为 `600`。 +- [✓] MySQL 恢复失败时自动尝试恢复目标数据库快照。 +- [✓] MySQL 数据库回滚失败时,将原始恢复错误和回滚错误同时返回。 +- [✓] 配置文件恢复仍保留原有的失败回滚逻辑。 +- [✓] SQLite 非内存数据库恢复时强制要求备份目录包含 `scert.db`。 +- [✓] 备份配置与当前配置的数据库驱动不一致时拒绝恢复。 + +### 52.3 自动化验证 + +- [✓] `go test ./...` 通过。 +- [✓] `go test -race ./...` 通过。 +- [✓] `go vet ./...` 通过。 +- [✓] `go mod verify` 通过。 +- [✓] `npm.cmd run build` 通过。 +- [✓] `git diff --check` 通过;仅报告现有 Windows 工作区换行格式提示,没有发现空白错误。 + +### 52.4 复审边界 + +- [!] 本轮未对真实 MySQL 5.7 服务执行故障注入回滚测试,仍需独立测试库和明确授权账号。 +- [!] MySQL 恢复快照在恢复成功后保留,后续需要增加备份保留策略和管理员可控清理功能;本轮不自动删除快照。 +- [!] DNS/ACME、远程服务器部署、生产 HTTPS、Windows 实机和外部邮箱最终投递仍不属于本轮已完成验收范围。 + +### 52.5 本轮复审结论 + +本轮代码修改已完成并通过现有自动化验证。MySQL 恢复流程现在具备恢复前快照、失败回滚和数据库类型隔离保护;但真实 MySQL 5.7 故障注入以及完整生产环境验收仍保持阻塞状态,不能标记为整体项目完成。 + +## 五十三、持续开发:Scert-admin 校验码安全呈现(2026-08-28) + +### 53.1 本轮需求清单 + +- [✓] Scert-admin 不监听独立 TCP/UDP 端口,继续保持手动启动和停止策略。 +- [✓] 一次性校验码不得写入标准输出、systemd 日志、配置文件或审计日志。 +- [✓] Linux systemd 使用受保护的运行时目录保存一次性校验码。 +- [✓] 校验码文件仅允许服务运行用户和 root 读取,并在使用后销毁。 +- [✓] 补充服务停止、租约失效、成功消费和文件覆盖保护测试。 +- [!] Windows 受 ACL 保护的本地校验码呈现适配仍需单独实现和实机验收。 + +### 53.2 本轮代码调整 + +- [✓] `Scert-admin` 增加 `--code-output` 参数,支持指定一次性校验码文件路径。 +- [✓] Linux systemd 默认使用 `/run/scert-admin/reset-code`,并配置 `RuntimeDirectoryMode=0700`。 +- [✓] 一次性校验码文件采用排他创建和 `0600` 权限,禁止覆盖已有文件。 +- [✓] 状态文件只保存校验码 SHA-256 摘要和校验码文件路径,不保存明文校验码。 +- [✓] 服务停止、租约失效、校验码消费成功后自动销毁校验码文件。 +- [✓] 命令行只显示重置地址和受保护文件路径,不显示校验码明文。 +- [✓] 更新 Linux systemd unit、部署说明和 Scert-admin 运维说明。 + +### 53.3 自动化验证 + +- [✓] Scert-admin 控制器测试通过。 +- [✓] 校验码文件权限、内容、消费销毁、租约失效销毁和禁止覆盖测试通过。 +- [✓] 命令行输出测试确认不会泄露一次性校验码。 +- [✓] systemd unit 测试确认包含受保护运行时目录和 `--code-output` 参数。 + +### 53.4 复审边界 + +- [!] 本轮未在 Ubuntu 22.04 实机上验证 systemd `RuntimeDirectory` 实际权限、root/Scert 读取边界和 journal 输出;需要后续在测试机执行交互式验证。 +- [!] Windows 暂使用通用文件实现,尚未切换为 ACL 或命名管道保护方案,不能标记为跨平台安全验收通过。 + +### 53.5 本轮复审结论 + +Scert-admin 的 Linux 代码路径已经不再通过标准输出泄露一次性校验码,默认 systemd 部署改为受保护的 `/run/scert-admin/reset-code` 临时文件,并覆盖了生命周期销毁和命令行输出回归测试。Linux 实机权限边界与 Windows 受保护呈现仍保持待验证状态。 + +## 五十四、持续开发:校验码跨平台保护接入复审(2026-08-28) + +### 54.1 本轮需求清单 + +- [✓] 继续保留超级管理员、管理员、普通用户、多角色和权限控制逻辑,不改为单账户模式。 +- [✓] 一次性校验码不得写入标准输出、systemd journal、普通配置、审计日志或备份。 +- [✓] Linux 使用 `0600` 文件权限和受保护运行时目录保存一次性校验码。 +- [✓] Windows 使用当前服务账户、Local System 和本地管理员组构造受保护 ACL。 +- [✓] 校验码成功消费、服务停止、租约失效和过期消费时销毁临时文件。 +- [✓] 已有校验码文件不得被新的重置会话覆盖。 + +### 54.2 代码复审与调整 + +- [✓] 复审发现 Windows ACL 函数已实现但未接入实际写入流程。 +- [✓] `writeCodeFile` 在写入并同步校验码后调用 `protectCodeFile`,保护失败时沿用失败清理逻辑删除临时文件。 +- [✓] Windows ACL 使用受保护 DACL,服务账户仅获得读取和删除权限,Local System 与本地管理员组保留管理权限。 +- [✓] Linux 路径继续使用 `0600` 权限,不引入不必要的平台特定依赖。 +- [✓] 保留排他创建逻辑,避免覆盖已有校验码文件。 + +### 54.3 自动化验证 + +- [✓] `go test ./...` 通过。 +- [✓] `go test -race ./...` 通过。 +- [✓] `go vet ./...` 通过。 +- [✓] `go mod verify` 通过。 +- [✓] `GOOS=windows GOARCH=amd64 go build ./internal/admin ./cmd/scert-admin` 通过。 +- [✓] `npm.cmd run build` 通过。 +- [✓] `git diff --check` 未发现空白错误;换行格式提示属于 Windows 工作区提示。 + +### 54.4 复审边界 + +- [!] 尚未在真实 Windows 服务账户环境中验证 ACL 的实际读取、删除和拒绝其他账户读取效果。 +- [!] 尚未在 Ubuntu 22.04 实机中再次验证 systemd 运行时目录权限、journal 内容和停止服务后的文件销毁。 +- [!] 真实 ACME/DNS API、远程 SSH 部署、Nginx/Caddy/Apache、生产 HTTPS 和外部邮箱最终投递仍不属于本轮已完成验收范围。 + +### 54.5 本轮复审结论 + +Windows ACL 保护现在已经接入一次性校验码实际写入流程,失败会自动清理临时文件;Linux 文件权限和生命周期销毁逻辑保持通过。自动化构建与测试通过,但 Windows 权限实测和 Ubuntu 22.04 systemd 实机复审仍需单独完成,不能将跨平台生产安全验收标记为已完成。 + +## 五十五、Ubuntu 22.04 实机复审:Scert-admin 受保护校验码(2026-08-28) + +### 55.1 测试范围 + +- [✓] 在 Ubuntu 22.04.5 LTS 测试机 `192.168.2.3` 上部署本轮 Linux amd64 `Scert-admin` 构建产物。 +- [✓] 部署本轮 `Scert-admin.service`,执行 `systemctl daemon-reload` 和 `systemd-analyze verify`。 +- [✓] 测试机原有 `Scert-admin` 二进制和 unit 已创建带时间戳的 `/tmp` 备份,未删除原文件。 +- [✓] 验证手动启停、运行时目录权限、校验码文件权限、日志泄露、网络监听和停止后销毁行为。 + +### 55.2 实机验证结果 + +- [✓] `systemctl is-enabled Scert-admin` 返回 `static`,没有开机自启动注册。 +- [✓] `systemctl start Scert-admin` 后服务状态为 `active`。 +- [✓] `/run/scert-admin` 实际权限为 `700`,所有者为 `Scert:Scert`。 +- [✓] `/run/scert-admin/reset-code` 实际权限为 `600`,所有者为 `Scert:Scert`。 +- [✓] 本次新版服务启动后的最近日志未发现校验码明文。 +- [✓] 未发现 `Scert-admin` 独立 TCP/UDP 网络监听;核心服务继续使用既有 `5200` 监听。 +- [✓] `systemctl stop Scert-admin` 后服务变为 `inactive`,校验码文件和运行时目录均被清理。 + +### 55.3 测试机历史遗留说明 + +- [!] 测试机旧版服务在本次升级前的历史 journal 中曾保存过明文校验码;这属于旧版本遗留日志,不能通过本轮代码自动消除。 +- [!] 生产升级前应根据组织日志保留策略处理旧 journal,并确保升级后的服务不再写入明文校验码。 +- [!] `systemd-analyze verify` 同时报告了测试机其他 `snapd.service` 的未知配置项警告,与 Scert unit 无关;Scert unit 本身未产生语法错误。 + +### 55.4 当前复审结论 + +Linux Ubuntu 22.04 上的 `Scert-admin` 手动启停、无开机自启动、无独立网络监听、受保护运行时目录、校验码权限、日志不泄露和停止后销毁均已完成实机验证。Windows ACL 仍只完成代码接入、自动化交叉编译和静态复审,尚未完成 Windows 服务账户权限实测,因此整体跨平台安全验收仍不能标记为完成。 + +## 五十六、真实 ACME/DNS 测试:阿里云 DNS 与 Let’s Encrypt(2026-08-28) + +### 56.1 测试范围 + +- [✓] 使用项目现有 `go-acme/lego` 实现进行 DNS-01 验证。 +- [✓] 使用阿里云 DNS Provider 验证 RAM 凭据和 DNS 记录操作权限。 +- [✓] 测试域名 `salg.cn` 的 DNS TXT 记录创建、传播检查和清理。 +- [!] 测试域名 `zhuguang.asia` 暂未申请证书,不修改其现有 DNS 配置。 +- [✓] 证书申请使用独立临时进程和内存密钥,不写入 Scert 证书目录、配置、数据库或备份。 + +### 56.2 代码修正 + +- [✓] 修正 `backend/internal/certificate/lego.go`:ACME 账户邮箱仅用于账户注册,不再写入证书 CSR 的 `EmailAddresses` 字段。 +- [✓] 修正后通过 Let’s Encrypt Staging 的证书申请验证,确认不再触发 `CSR contains one or more email address fields` 错误。 + +### 56.3 实测结果 + +- [✓] `salg.cn` 阿里云 DNS API 测试成功,临时 `_acme-challenge` TXT 记录能够创建和清理。 +- [✓] `salg.cn` Let’s Encrypt Staging DNS-01 验证成功。 +- [✓] `salg.cn` Let’s Encrypt Staging 证书签发成功。 +- [✓] Staging 证书域名匹配成功,证书与私钥匹配成功。 +- [✓] Staging 证书链解析成功,共解析到 5 张证书。 +- [✓] Staging 证书有效期为 2026-08-28T15:49:14Z 至 2026-11-26T15:49:13Z。 +- [✓] 通过阿里云 DNS API 查询确认测试结束后 `_acme-challenge.salg.cn` TXT 记录数为 0。 +- [✓] `go test ./...`、`go vet ./...`、`go mod verify` 和 `npm.cmd run build` 全部通过。 + +### 56.4 `zhuguang.asia` 阻塞原因 + +- [!] `_acme-challenge.zhuguang.asia` 当前存在 CNAME 委派,目标为 `expired.hichina.com`。 +- [!] 阿里云 Provider 按 CNAME 委派查找目标 DNS 区域时,无法在当前阿里云账号中找到 `expired.hichina.com` 托管区域。 +- [!] 在用户修正或确认该 CNAME 委派前,不执行自动删除、替换或新增 DNS 记录。 + +### 56.5 Production 实测边界 + +- [!] `salg.cn` Production 申请已发起,但因递归 DNS 服务器在传播窗口内仍返回此前测试的旧 TXT 值,未能完成本次验证。 +- [✓] Production 失败后 lego 已执行 DNS-01 清理和授权停用,没有留下运行中的申请任务。 +- [!] 该失败暴露出 DNS 删除/新增后的缓存传播窗口约为 600 秒;后续应在生产流程中支持可配置传播等待时间、重试策略和失败后的明确诊断。 +- [!] 本轮未将生产证书保存到 Scert 默认目录,也未执行远程服务器部署或修改 Nginx、Caddy、Apache 配置。 + +### 56.6 本轮复审结论 + +阿里云 DNS Provider 的 RAM 权限、`salg.cn` 的 DNS-01 验证、lego Staging 证书申请、证书解析、域名匹配、私钥匹配和清理流程已完成真实验证。当前需要后续处理的事项为:修正 `zhuguang.asia` 的 CNAME 委派,以及在 DNS 传播延迟场景下完善 Production 申请的等待和重试策略。Production 证书签发、证书落盘、自动续期、远程部署和线上 HTTPS 校验仍不能标记为整体完成。 + + +## 五十七、DNS-01 传播等待与诊断配置(2026-08-29) + +### 57.1 需求清单 + +- [✓] 为 DNS-01 增加可配置的最大传播等待时间。 +- [✓] 为 DNS-01 增加可配置的传播检测间隔。 +- [✓] 保留旧配置兼容性,读取缺少新字段的配置时自动补齐默认值。 +- [✓] 对等待时间和检测间隔增加范围校验,避免无效参数进入证书申请流程。 +- [✓] 证书申请失败时输出本次使用的传播等待参数,便于诊断 DNS 缓存传播延迟。 + +### 57.2 实现清单 + +- [✓] 在 `ACMEConfig` 中增加 `propagation_timeout_secs`,默认值为 900 秒。 +- [✓] 在 `ACMEConfig` 中增加 `propagation_polling_interval_secs`,默认值为 10 秒。 +- [✓] 通过 `challenge.ProviderTimeout` 包装实际 DNS Provider,并注入 `go-acme/lego`。 +- [✓] 在 `scert config set` 支持修改上述两个配置项。 +- [✓] 增加默认值、旧配置归一化、范围校验和保存加载测试。 +- [✓] 增加 Provider 操作转发、参数读取、无效参数保护和空 Provider 测试。 +- [✓] 保持敏感 DNS 凭据仅在调用时解密,未改变明文配置阶段和加密持久化策略。 + +### 57.3 参数规则 + +| 配置项 | 默认值 | 允许范围 | 说明 | +|---|---:|---:|---| +| `acme.propagation_timeout_secs` | 900 秒 | 1 至 86400 秒 | DNS 记录发布后,lego 等待验证传播的最长时间 | +| `acme.propagation_polling_interval_secs` | 10 秒 | 大于 0 且不大于等待时间 | lego 检查 DNS 记录传播状态的间隔 | + +### 57.4 验证结果 + +- [✓] `go test -race ./...` 通过。 +- [✓] `go vet ./...` 通过。 +- [✓] `go mod verify` 通过。 +- [✓] 前端生产构建通过。 +- [✓] `git diff --check` 通过。 + +### 57.5 当前边界 + +- [!] 配置已接入真实 lego DNS-01 流程,但仍需使用真实 DNS Provider 和 Let's Encrypt Production 在公网传播延迟场景完成最终验收。 +- [!] 本轮未修改远程服务器部署、Nginx、Caddy、Apache 或证书文件替换逻辑。 + +## 五十八、Web 初始化接入 DNS-01 传播等待配置(2026-08-29) + +### 58.1 本轮需求清单 + +- [✓] Web 初始化向导可以配置 DNS-01 最大传播等待时间。 +- [✓] Web 初始化向导可以配置 DNS-01 传播检测间隔。 +- [✓] Web 表单显示默认值:最大等待 900 秒、检测间隔 10 秒。 +- [✓] 前端阻止小于 1 秒、超过 86400 秒或检测间隔大于最大等待时间的输入。 +- [✓] 配置完成前参数只保留在向导内存,提交时由后端统一校验并保存。 +- [✓] 兼容未提交这两个字段的旧调用,后端沿用配置默认值。 + +### 58.2 代码调整 + +- [✓] `backend/internal/httpapi/setup.go` 接收并返回两个 DNS 传播配置字段。 +- [✓] `backend/internal/setup/setup.go` 将 Web 初始化请求写入 `ACMEConfig`,保留零值缺省兼容行为。 +- [✓] `frontend/src/views/SetupWizard/SetupWizard.js` 增加表单状态、前端校验和提交字段。 +- [✓] `frontend/src/views/SetupWizard/SetupWizard.vue` 在 DNS 验证步骤增加两个中文配置项及说明。 +- [✓] 保持页面相关文件按 `src/views/SetupWizard/` 目录集中管理。 + +### 58.3 自动化验证 + +- [✓] 增加初始化层的非法传播参数回归测试。 +- [✓] 增加 Web 初始化接口保存传播参数回归测试。 +- [✓] `go test -race ./...` 通过。 +- [✓] `go vet ./...` 通过。 +- [✓] `go mod verify` 通过。 +- [✓] `npm.cmd run build` 通过。 +- [✓] `git diff --check` 通过。 +- [✓] 目标代码范围未发现连续问号、替换字符或错误换行标记。 + +### 58.4 复审边界 + +- [!] 本轮未使用浏览器 MCP 进行页面截图验收;本轮目标是配置链路接入,不包含布局和视觉改版。 +- [!] 真实 DNS Provider、Let's Encrypt Production 公网传播延迟和生产续期仍需在授权环境完成最终验收。 +- [!] 本轮未执行 Git 提交、推送、文件清理或删除。 +## 五十九、初始化向导通知布局与敏感凭据交互优化(2026-08-29) + +### 59.1 需求清单 + +- [x] 初始化向导第二步按服务配置、认证配置、敏感凭据、收发件人和投递策略分组显示。 +- [x] HTTP 通知的 Token、HMAC 密钥和会话凭据支持配置时明文查看与隐藏切换。 +- [x] 配置提交后由后端加密保存敏感凭据,普通配置文件不保存明文密钥。 +- [x] DNS 凭据字段使用不同的动态 ID,避免模板静态检查发现重复 ID。 +- [x] 页面显示文字保持中文,源码范围未发现 HTML 编码中文和替换字符。 + +### 59.2 实现与验证清单 + +- [x] 完成 `SetupWizard.vue` 中 DNS 普通凭据输入框动态 ID 修正。 +- [x] 完成前端生产构建验证:`npm.cmd run build`。 +- [x] 完成后端竞态测试:`go test -race ./...`。 +- [x] 完成后端静态检查:`go vet ./...`。 +- [x] 完成 Go 模块完整性检查:`go mod verify`。 +- [x] 完成 Git 差异格式检查:`git diff --check`。 +- [!] 浏览器 MCP 因共享 Chrome Profile 已被其他浏览器进程占用,本轮未完成真实截图验收;未强制关闭用户浏览器。 +- [!] 低高度桌面窗口下的初始化向导最终视觉效果仍需在 MCP 可用后复测。 + +### 59.3 当前状态 + +本轮代码调整和自动化检查已完成,相关任务标记为“已完成,等待复审”。浏览器 MCP 视觉验收属于外部运行环境阻塞,不影响前端构建和后端自动化检查结果;待独立浏览器窗口可用后,再对桌面宽屏、中等窗口和低高度窗口进行实际显示复审。 \ No newline at end of file diff --git a/frontend/src/views/SetupWizard/SetupWizard.css b/frontend/src/views/SetupWizard/SetupWizard.css index b492217..b74fcd2 100644 --- a/frontend/src/views/SetupWizard/SetupWizard.css +++ b/frontend/src/views/SetupWizard/SetupWizard.css @@ -1,258 +1,171 @@ -.setup-shell { - position: absolute; - top: 50%; - left: 50%; - width: min(calc(100% - 64px), 1360px); - height: auto; - max-height: calc(100dvh - 48px); - min-height: 0; - margin: 0; - display: grid; - grid-template-columns: minmax(280px, 0.62fr) minmax(0, 1.38fr); - overflow: hidden; - transform: translate(-50%, -50%); - border: 1px solid rgba(218, 226, 238, 0.92); - border-radius: 28px; - background: #fff; - color: #172033; - box-shadow: 0 28px 80px rgba(46, 73, 119, 0.16); -} -.setup-intro { - position: relative; - isolation: isolate; - min-width: 0; - overflow: hidden; - color: #fff; - background: - radial-gradient( - circle at 18% 12%, - rgba(111, 160, 255, 0.6), - transparent 32% - ), - linear-gradient(145deg, #132752, #244c92 62%, #2e64b8); -} -.setup-intro::before, -.setup-intro::after { - position: absolute; - z-index: -1; - display: block; - border-radius: 50%; - content: ""; - pointer-events: none; -} -.setup-intro::before { - top: -150px; - right: -120px; - width: 360px; - height: 360px; - background: rgba(111, 160, 255, 0.15); -} -.setup-intro::after { - bottom: -190px; - left: -140px; - width: 420px; - height: 420px; - background: rgba(4, 20, 60, 0.24); -} -.intro-inner { - position: relative; - z-index: 1; - height: 100%; - display: flex; - flex-direction: column; - justify-content: center; - padding: clamp(32px, 4vw, 58px); -} -.brand-mark { - display: block; - width: clamp(62px, 7vw, 96px); - height: clamp(62px, 7vw, 96px); - margin-bottom: clamp(14px, 2vw, 22px); - object-fit: contain; - filter: drop-shadow(0 14px 22px rgba(0, 0, 0, 0.2)); -} -.setup-eyebrow { - margin: 0 0 7px; - color: #446a9f; - font-size: 11px; - font-weight: 900; - letter-spacing: 0.14em; - text-transform: uppercase; -} -.setup-intro .setup-eyebrow { - color: #bad2ff; -} -.setup-intro h1 { - max-width: 430px; - margin: 0 0 14px; - font-size: clamp(28px, 2.75vw, 40px); - letter-spacing: -0.08em; - line-height: 1.12; -} -.intro-description { - max-width: 540px; - margin: 0; - color: #d7e4fb; - font-size: 13px; - line-height: 1.7; -} -.service-summary { - display: none; /* 服务说明移至对应配置步骤,不在品牌区重复提示 */ -} -.service-summary-unused { - display: grid; - gap: 8px; - margin-top: clamp(20px, 3vw, 34px); -} -.service-summary span { - padding: 10px 13px; - border: 1px solid rgba(255, 255, 255, 0.17); - border-radius: 11px; - background: rgba(255, 255, 255, 0.08); - color: #dce8fb; - font-size: 12px; -} -.service-summary strong { - color: #fff; -} -.warning-card { - display: grid; - gap: 5px; - margin-top: clamp(18px, 2.5vw, 28px); - padding: 13px; - border-left: 3px solid #ffd37a; - background: rgba(8, 21, 51, 0.25); - color: #dce8fb; - font-size: 11px; - line-height: 1.55; -} -.warning-card strong { - color: #ffe5ad; -} .setup-card { width: 100%; height: 100%; min-width: 0; min-height: 0; - display: flex; - flex-direction: column; - justify-content: center; - padding: clamp(28px, 3.2vw, 52px); - background: linear-gradient(145deg, #ffffff 0%, #fbfdff 100%); + display: grid; + grid-template-rows: auto auto minmax(0, 1fr) auto; + gap: 14px; + padding: 26px 30px 22px; + overflow: hidden; + color: #172033; + background: + radial-gradient(circle at 100% 0%, rgba(232, 240, 255, 0.72), transparent 32%), + linear-gradient(145deg, #ffffff 0%, #fbfdff 100%); } + .setup-card > header { - flex: 0 0 auto; + min-width: 0; display: flex; + align-items: center; justify-content: space-between; - align-items: flex-start; - margin-bottom: 11px; + gap: 16px; } + +.setup-eyebrow { + margin: 0 0 6px; + color: #4d76b7; + font-size: 11px; + font-weight: 900; + letter-spacing: 0.12em; + line-height: 1.2; +} + .setup-card h2 { margin: 0; - font-size: clamp(23px, 2.2vw, 32px); + color: #172033; + font-size: clamp(24px, 2.2vw, 32px); + letter-spacing: -0.05em; + line-height: 1.15; } + .local-badge { - padding: 6px 10px; - border-radius: 99px; + flex: 0 0 auto; + padding: 7px 11px; + border: 1px solid #d5e4ff; + border-radius: 999px; color: #2f63b2; - background: #e5efff; + background: #eaf2ff; font-size: 11px; font-weight: 800; + white-space: nowrap; } + .setup-progress { - flex: 0 0 auto; + min-width: 0; display: grid; - grid-template-columns: 1fr 18px 1fr 18px 1fr 18px 1fr; + grid-template-columns: minmax(0, 1fr) 24px minmax(0, 1fr) 24px minmax(0, 1fr) 24px minmax(0, 1fr); align-items: center; - gap: 5px; - margin-bottom: 12px; + gap: 7px; + margin: 0; + padding: 12px 14px; + border: 1px solid #e4ebf5; + border-radius: 16px; + background: rgba(247, 250, 254, 0.9); } + .progress-step { min-width: 0; display: grid; - grid-template-columns: auto 1fr; - column-gap: 7px; + grid-template-columns: auto minmax(0, 1fr); + column-gap: 8px; align-items: center; - color: #7a879d; + color: #8995a8; } + .progress-step b { grid-row: 1 / span 2; display: grid; place-items: center; - width: 28px; - height: 28px; - border: 3px solid #fff; + width: 30px; + height: 30px; + border: 2px solid #ffffff; border-radius: 50%; - color: #fff; + color: #ffffff; background: #315faa; font-size: 11px; - box-shadow: - 0 0 0 1px #315faa, - 0 5px 12px rgba(49, 95, 170, 0.16); + box-shadow: 0 0 0 1px #315faa, 0 5px 12px rgba(49, 95, 170, 0.16); } + .progress-step:not(.active):not(.complete) b { - color: #65748b; + color: #6b7890; background: #e4eaf3; + box-shadow: none; } + .progress-step.complete b { - border-color: #fff; background: #4b9b74; - box-shadow: - 0 0 0 1px #4b9b74, - 0 5px 12px rgba(75, 155, 116, 0.14); + box-shadow: 0 0 0 1px #4b9b74, 0 5px 12px rgba(75, 155, 116, 0.14); } -.progress-step strong { + +.progress-step strong, +.progress-step small { + min-width: 0; overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.progress-step strong { color: #32405a; font-size: 11px; - line-height: 1.15; - text-overflow: ellipsis; - white-space: nowrap; + line-height: 1.2; } + .progress-step small { - overflow: hidden; + margin-top: 2px; + color: #8995a8; font-size: 10px; - line-height: 1.15; - text-overflow: ellipsis; - white-space: nowrap; + line-height: 1.2; } + .setup-progress i { height: 1px; background: #d5deeb; } + .setup-form { + min-width: 0; min-height: 0; - flex: 0 1 auto; - display: flex; - flex-direction: column; - gap: 8px; + display: grid; + grid-template-rows: minmax(0, 1fr) auto; + gap: 10px; } + .setup-step-grid { + min-width: 0; min-height: 0; - flex: 0 1 auto; display: block; } + .setup-step-card { - height: auto; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + overflow: visible; } + fieldset { min-width: 0; min-height: 0; - overflow: hidden; margin: 0; - padding: 16px 17px; + padding: 18px 20px; border: 1px solid #dce5f1; - border-radius: 18px; - background: rgba(255, 255, 255, 0.96); + border-radius: 17px; + background: rgba(255, 255, 255, 0.97); box-shadow: 0 14px 32px rgba(31, 50, 87, 0.07); } + legend { max-width: 100%; - padding: 0 5px; + padding: 0 7px; color: #243653; font-size: 13px; font-weight: 900; + line-height: 1.2; } + legend span { display: inline-grid; place-items: center; @@ -260,18 +173,18 @@ legend span { height: 25px; margin-right: 7px; border-radius: 8px; - color: #fff; + color: #ffffff; background: linear-gradient(145deg, #3d70c1, #285398); font-size: 10px; box-shadow: 0 5px 12px rgba(49, 95, 170, 0.18); } + .setup-grid { + min-width: 0; display: grid; - gap: 7px; -} -.three-columns { - grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 9px 12px; } + .two-columns { grid-template-columns: repeat(2, minmax(0, 1fr)); } @@ -280,831 +193,444 @@ legend span { grid-template-columns: repeat(3, minmax(0, 1fr)); } -.compact-options { - gap: 6px; -} - -.compact-row { - min-height: 38px; - padding: 6px 8px; -} - -.compact-row span { - min-width: 0; -} - -.compact-row strong { - white-space: nowrap; -} - -.compact-row small { - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} label { min-width: 0; display: grid; - gap: 4px; + gap: 5px; margin-top: 8px; color: #34445f; font-size: 10px; font-weight: 800; + line-height: 1.25; } -.email-input-group { - min-width: 0; - display: grid; - grid-template-columns: minmax(0, 1fr) minmax(88px, 112px); - gap: 6px; -} -.email-input-group input, -.email-input-group select { - min-width: 0; - width: 100%; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} + input, select, textarea { min-width: 0; width: 100%; - padding: 0 9px; border: 1px solid #d4deeb; - border-radius: 8px; + border-radius: 9px; outline: 0; color: #172033; background: #fbfcfe; font: inherit; + font-size: 11px; font-weight: 500; + transition: border-color 0.18s ease, box-shadow 0.18s ease, background 0.18s ease; } + input, select { - height: 35px; + height: 37px; + padding: 0 10px; } + textarea { min-height: 54px; - padding-top: 7px; - padding-bottom: 7px; + padding: 8px 10px; resize: none; line-height: 1.35; } -input:focus, -select:focus, -textarea:focus { - border-color: #4f7ed5; - box-shadow: 0 0 0 3px rgba(79, 126, 213, 0.12); -} -label > small { - color: #53647b; - font-size: 9px; - font-weight: 500; - line-height: 1.35; -} -.provider-description, -.dns-verification-success { - display: grid; - gap: 4px; - margin-top: 10px; - padding: 10px 11px; - border-radius: 11px; - font-size: 10px; - line-height: 1.35; -} -.provider-description { - color: #435571; - background: #f4f7fb; -} -.provider-description.unavailable { - color: #805f20; - background: #fff8e8; -} -.provider-description strong, -.dns-verification-success strong { - font-size: 11px; -} -.reset-preview span { - overflow-wrap: anywhere; -} -.credential-grid { - margin-top: 0; -} -.dns-test-actions { - display: flex; - align-items: center; - gap: 8px; - margin-top: 8px; - color: #53647b; - font-size: 10px; - line-height: 1.35; -} -.dns-test-button { - flex: 0 0 auto; - min-width: 112px; - padding: 7px 9px; - border: 0; - border-radius: 8px; - color: #fff; - background: #315faa; - font-size: 10px; - font-weight: 900; -} -.inline-error { - margin: 7px 0 0; - padding: 7px 9px; - border: 1px solid #efc6c6; - border-radius: 8px; - color: #a33d3d; - background: #fff1f1; - font-size: 10px; -} -.dns-verification-success { - border: 1px solid #bfe7d1; - color: #24734b; - background: #effbf4; -} -.confirm-row { - grid-template-columns: auto 1fr; - align-items: flex-start; - padding: 9px 10px; - border-radius: 9px; - background: #f6f8fc; -} -.confirm-row input { - width: 16px; - height: 16px; - margin-top: 1px; - accent-color: #315faa; -} -.confirm-row strong, -.confirm-row small { - display: block; -} -.confirm-row small { - margin-top: 3px; - color: #53647b; - font-size: 9px; - font-weight: 500; - line-height: 1.35; -} -.target-switch { - display: inline-flex; - gap: 4px; - margin-top: 8px; - padding: 4px; - border-radius: 10px; - background: #edf2f8; -} -.target-switch button { - padding: 7px 11px; - border: 0; - border-radius: 7px; - color: #4d6078; - background: transparent; - font-size: 10px; - font-weight: 800; -} -.target-switch button.active { - color: #274f91; - background: #fff; - box-shadow: 0 3px 10px rgba(36, 64, 107, 0.1); -} -.setup-error, -.setup-success { - flex: 0 0 auto; - margin: 0; - padding: 7px 9px; - border-radius: 8px; - font-size: 10px; -} -.setup-error { - border: 1px solid #efc6c6; - color: #a33d3d; - background: #fff1f1; -} -.setup-success { - border: 1px solid #bfe7d1; - color: #24734b; - background: #effbf4; -} -footer { - flex: 0 0 auto; - display: flex; - justify-content: space-between; - align-items: center; - gap: 12px; - padding: 2px 1px 0; - color: #53647b; - font-size: 10px; - line-height: 1.35; -} -footer span { - min-width: 0; -} -.wizard-actions { - display: flex; - flex: 0 0 auto; - align-items: center; - gap: 7px; -} -footer button { - flex: 0 0 auto; - min-width: 154px; - padding: 10px 14px; - border: 0; - border-radius: 9px; - color: #fff; - background: #315faa; - font-size: 11px; - font-weight: 900; - box-shadow: 0 7px 16px rgba(49, 95, 170, 0.22); -} -footer .back-button { - min-width: 76px; - border: 1px solid #d5ddea; - color: #32405a; - background: #fff; - box-shadow: none; -} -button { - cursor: pointer; -} -button:disabled { - cursor: wait; - opacity: 0.62; -} -@media (max-height: 760px) and (min-width: 901px) { - .setup-card { - padding-top: 12px; - padding-bottom: 12px; - } - .setup-card > header { - margin-bottom: 6px; - } - .setup-progress { - margin-bottom: 7px; - } - fieldset { - padding: 9px 11px; - } - label { - margin-top: 5px; - } - .provider-description, - .dns-verification-success { - margin-top: 5px; - padding: 6px 8px; - } - .dns-test-actions { - margin-top: 5px; - } - footer { - font-size: 9px; - } -} -@media (max-width: 1200px) { - .setup-shell { - grid-template-columns: minmax(230px, 0.55fr) minmax(650px, 1.45fr); - } - .intro-inner { - padding: 24px; - } - .service-summary span { - font-size: 11px; - } -} -@media (max-width: 900px) { - .setup-shell { - grid-template-columns: 1fr; - grid-template-rows: auto auto; - border-radius: 20px; - } - .setup-intro { - min-height: 0; - } - .intro-inner { - display: grid; - grid-template-columns: auto minmax(0, 1fr); - align-items: center; - column-gap: 14px; - padding: 12px 20px; - } - .brand-mark { - grid-row: 1 / span 2; - width: 68px; - height: 68px; - margin: 0; - } - .intro-copy h1 { - margin-bottom: 4px; - font-size: 25px; - } - .intro-description { - font-size: 11px; - line-height: 1.35; - } - .service-summary { - display: none; - } - .warning-card { - display: none; - } - .setup-card { - padding: 12px 16px; - } -} -@media (max-height: 760px) { - .setup-shell { - max-height: calc(100dvh - 16px); - } -} -@media (max-width: 600px) { - .setup-shell { - width: calc(100% - 16px); - max-height: calc(100dvh - 16px); - min-height: 0; - grid-template-rows: auto auto; - } - .intro-inner { - padding: 8px 12px; - column-gap: 9px; - } - .brand-mark { - width: 52px; - height: 52px; - } - .setup-intro .setup-eyebrow { - margin-bottom: 3px; - font-size: 9px; - } - .intro-copy h1 { - font-size: 19px; - } - .intro-description { - font-size: 9px; - } - .setup-card { - padding: 8px 10px; - } - .setup-card > header { - margin-bottom: 5px; - } - .setup-card h2 { - font-size: 19px; - } - .local-badge { - padding: 4px 7px; - font-size: 9px; - } - .setup-progress { - gap: 3px; - margin-bottom: 6px; - } - .progress-step { - column-gap: 4px; - } - .progress-step b { - width: 20px; - height: 20px; - font-size: 9px; - } - .progress-step strong { - font-size: 9px; - } - .progress-step small { - display: none; - } - fieldset { - padding: 8px 8px; - border-radius: 10px; - } - legend { - font-size: 10px; - } - legend span { - width: 18px; - height: 18px; - margin-right: 3px; - border-radius: 5px; - font-size: 8px; - } - .setup-grid { - gap: 4px; - } - label { - gap: 2px; - margin-top: 4px; - font-size: 9px; - } - input, - select { - height: 26px; - padding: 0 6px; - font-size: 9px; - } - textarea { - min-height: 42px; - font-size: 9px; - } - label > small { - display: none; - } - .provider-description, - .dns-verification-success { - margin-top: 4px; - padding: 5px 6px; - font-size: 8px; - } - .provider-description span, - .dns-verification-success span { - display: none; - } - .provider-description strong, - .dns-verification-success strong { - font-size: 9px; - } - .dns-test-actions { - gap: 4px; - margin-top: 4px; - font-size: 8px; - } - .dns-test-button { - min-width: 88px; - padding: 5px 6px; - font-size: 8px; - } - .dns-test-actions > span { - display: none; - } - .target-switch { - margin-top: 4px; - } - .target-switch button { - padding: 4px 5px; - font-size: 8px; - } - .confirm-row { - padding: 5px 6px; - } - .confirm-row input { - width: 13px; - height: 13px; - } - .confirm-row small { - display: none; - } - footer { - gap: 5px; - font-size: 8px; - } - footer button { - min-width: 112px; - padding: 7px 8px; - font-size: 9px; - } -} -.reset-preview span { - display: block !important; -} -@media (max-width: 390px) { - .setup-card { - padding-left: 6px; - padding-right: 6px; - } - .setup-progress { - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 2px; - } - .setup-progress i { - display: none; - } - .progress-step { - grid-template-columns: auto 1fr; - } - .progress-step strong { - font-size: 8px; - } - .setup-step-grid { - gap: 3px; - } - fieldset { - padding: 6px 5px; - } - legend { - font-size: 9px; - } - .three-columns, - .two-columns { - gap: 3px; - } - label { - font-size: 8px; - } - input, - select { - height: 23px; - font-size: 8px; - } - textarea { - min-height: 36px; - } - .dns-test-button { - min-width: 75px; - } - footer { - font-size: 7px; - } - footer button { - min-width: 100px; - padding: 6px 5px; - font-size: 8px; - } -} -.setup-shell { - width: min(calc(100% - 48px), 1400px); - height: min(720px, calc(100dvh - 48px)); - grid-template-columns: clamp(250px, 23vw, 320px) minmax(0, 1fr); - border-radius: 28px; - box-shadow: - 0 32px 86px rgba(34, 60, 104, 0.18), - 0 4px 18px rgba(34, 60, 104, 0.06); -} - -.setup-intro { - background: - radial-gradient( - circle at 14% 10%, - rgba(121, 174, 255, 0.72), - transparent 26% - ), - radial-gradient( - circle at 100% 92%, - rgba(62, 126, 222, 0.48), - transparent 38% - ), - linear-gradient(155deg, #10234a 0%, #1d4383 55%, #2861b0 100%); -} - -.setup-intro::before { - top: -96px; - right: -134px; - width: 330px; - height: 330px; - border: 1px solid rgba(255, 255, 255, 0.1); - background: rgba(255, 255, 255, 0.025); - box-shadow: - 0 0 0 42px rgba(255, 255, 255, 0.025), - 0 0 0 86px rgba(255, 255, 255, 0.018); -} - -.setup-intro::after { - bottom: -150px; - left: -170px; - width: 390px; - height: 390px; - border: 1px solid rgba(255, 255, 255, 0.08); - background: rgba(4, 19, 50, 0.12); -} - -.intro-inner { - justify-content: flex-start; - padding: 44px 30px 32px; -} - -.brand-mark { - width: 86px; - height: 86px; - margin-bottom: 30px; -} - -.setup-intro .setup-eyebrow { - margin-bottom: 9px; - font-size: 10px; - letter-spacing: 0.18em; -} - -.setup-intro h1 { - max-width: 260px; - margin-bottom: 17px; - font-size: clamp(29px, 2.2vw, 35px); - letter-spacing: -0.055em; - line-height: 1.18; -} - -.intro-description { - max-width: 260px; - color: rgba(235, 243, 255, 0.84); - font-size: 12px; - line-height: 1.8; -} - -.warning-card { - margin-top: auto; - padding: 14px 15px; - border: 1px solid rgba(255, 255, 255, 0.1); - border-left: 3px solid #ffd36d; - border-radius: 0 13px 13px 0; - background: rgba(7, 24, 58, 0.28); -} - -.setup-card { - justify-content: stretch; - padding: 40px 46px 32px; - background: - radial-gradient( - circle at 100% 0%, - rgba(232, 240, 255, 0.72), - transparent 31% - ), - linear-gradient(145deg, #fff 0%, #fbfdff 100%); -} - -.setup-card > header { - align-items: center; - margin-bottom: 18px; -} - -.setup-card h2 { - font-size: 33px; -} - -.local-badge { - padding: 7px 12px; - border: 1px solid #d5e4ff; - background: rgba(233, 241, 255, 0.9); -} - -.setup-progress { - grid-template-columns: 1fr 24px 1fr 24px 1fr 24px 1fr; - gap: 7px; - margin-bottom: 20px; - padding: 13px 15px; - border: 1px solid #e5ecf6; - border-radius: 17px; - background: rgba(247, 250, 254, 0.88); -} - -.progress-step { - column-gap: 9px; -} - -.progress-step b { - width: 32px; - height: 32px; - font-size: 12px; -} - -.progress-step strong { - font-size: 12px; -} - -.progress-step small { - margin-top: 2px; -} - -.setup-form, -.setup-step-grid { - flex: 1 1 auto; -} - -.setup-step-card { - height: 100%; -} - -fieldset { - padding: 21px 23px; - border-radius: 19px; - box-shadow: 0 18px 44px rgba(32, 55, 94, 0.075); -} - -legend { - padding: 0 7px; - font-size: 14px; -} - -legend span { - width: 28px; - height: 28px; - margin-right: 8px; -} - -.setup-grid { - gap: 11px 14px; -} - -label { - gap: 7px; - margin-top: 9px; - font-size: 12px; -} - -input, -select, -textarea { - border-radius: 11px; - background: #fbfcff; - transition: - border-color 0.18s ease, - box-shadow 0.18s ease, - background 0.18s ease; -} - -input, -select { - height: 41px; - padding: 0 12px; - font-size: 12px; -} - -textarea { - padding: 10px 12px; - font-size: 12px; -} input:hover, select:hover, textarea:hover { border-color: #b8c9e1; - background: #fff; + background: #ffffff; } input:focus, select:focus, textarea:focus { - border-color: #4c7ac7; - background: #fff; - box-shadow: 0 0 0 4px rgba(76, 122, 199, 0.11); + border-color: #4f7ed5; + background: #ffffff; + box-shadow: 0 0 0 3px rgba(79, 126, 213, 0.12); +} + +label > small { + color: #53647b; + font-size: 9px; + font-weight: 500; + line-height: 1.35; +} + +.email-field { + min-width: 0; +} + +.email-input-group { + min-width: 0; + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(88px, 112px); + gap: 6px; +} + +.email-input-group input, +.email-input-group select { + min-width: 0; + width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.email-primary-grid, +.email-delivery-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.email-headers-field { + margin-top: 9px; +} + +.email-headers-field textarea { + min-height: 48px; +} + +.notification-credential-field { + min-width: 0; + display: grid; + gap: 5px; + grid-column: 1 / -1; + margin-top: 1px; +} + +.notification-credential-field .credential-visibility-row { + margin-top: 0; +} + +.notification-credential-field textarea { + min-height: 58px; + font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace; + font-size: 10px; + line-height: 1.45; +} + +.notification-credential-field > small { + color: #53647b; + font-size: 9px; + font-weight: 500; + line-height: 1.35; +} + +.compact-options { + gap: 7px; +} + +.compact-row { + min-height: 37px; + grid-template-columns: auto minmax(0, 1fr); + align-items: flex-start; + margin-top: 8px; + padding: 7px 9px; + border-radius: 9px; + background: #f6f8fc; +} + +.compact-row input, +.confirm-row input { + width: 16px; + height: 16px; + margin: 1px 0 0; + accent-color: #315faa; +} + +.compact-row span, +.confirm-row span { + min-width: 0; +} + +.compact-row strong, +.compact-row small, +.confirm-row strong, +.confirm-row small { + display: block; +} + +.compact-row strong, +.confirm-row strong { + color: #34445f; + font-size: 10px; + line-height: 1.25; + white-space: nowrap; +} + +.compact-row small, +.confirm-row small { + margin-top: 3px; + overflow: hidden; + color: #53647b; + font-size: 9px; + font-weight: 500; + line-height: 1.35; + text-overflow: ellipsis; + white-space: nowrap; +} + +.confirm-row { + min-width: 0; + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: flex-start; + margin-top: 9px; + padding: 9px 10px; + border-radius: 9px; + background: #f6f8fc; +} + +.provider-description, +.dns-verification-success { + min-width: 0; + display: grid; + gap: 4px; + margin-top: 9px; + padding: 9px 11px; + border-radius: 10px; + font-size: 10px; + line-height: 1.35; +} + +.provider-description { + color: #435571; + background: #f4f7fb; +} + +.provider-description.unavailable { + color: #805f20; + background: #fff8e8; +} + +.provider-description strong, +.dns-verification-success strong { + font-size: 11px; +} + +.provider-description span, +.dns-verification-success span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.reset-preview { + display: flex; + align-items: center; + gap: 8px; + white-space: nowrap; +} + +.reset-preview strong, +.reset-preview span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.reset-preview strong { + flex: 0 0 auto; +} + +.reset-preview span:first-of-type { + flex: 0 1 auto; + color: #315faa; + font-weight: 800; +} + +.reset-preview span:last-of-type { + flex: 1 1 auto; +} + +.credential-grid { + margin-top: 0; +} + +.credential-visibility-row { + grid-column: 1 / -1; + min-width: 0; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-top: 8px; + padding: 7px 9px; + border: 1px solid #dbe5f1; + border-radius: 8px; + color: #34445f; + background: #f7faff; + font-size: 10px; + font-weight: 800; +} + +.credential-visibility-control { + display: inline-flex; + align-items: center; + gap: 5px; + margin: 0; + color: #315faa; + font-size: 10px; + font-weight: 700; + white-space: nowrap; +} + +.credential-visibility-control input { + width: 14px; + height: 14px; + margin: 0; +} + +.dns-test-actions { + min-width: 0; + display: flex; + align-items: center; + gap: 9px; + margin-top: 9px; + color: #53647b; + font-size: 10px; + line-height: 1.35; +} + +.dns-test-actions > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dns-test-button { + flex: 0 0 auto; + min-width: 112px; + padding: 8px 10px; + border: 0; + border-radius: 8px; + color: #ffffff; + background: linear-gradient(135deg, #3568b9, #28569d); + font-size: 10px; + font-weight: 900; + box-shadow: 0 7px 16px rgba(49, 95, 170, 0.2); +} + +.inline-error, +.setup-error, +.setup-success { + min-width: 0; + margin: 0; + padding: 8px 10px; + border-radius: 8px; + font-size: 10px; + line-height: 1.4; +} + +.inline-error, +.setup-error { + border: 1px solid #efc6c6; + color: #a33d3d; + background: #fff1f1; +} + +.setup-success, +.dns-verification-success { + border: 1px solid #bfe7d1; + color: #24734b; + background: #effbf4; } .target-switch { + width: fit-content; + display: inline-flex; + gap: 4px; + margin-top: 8px; padding: 4px; border: 1px solid #e1e8f3; - border-radius: 12px; + border-radius: 11px; background: #f3f6fb; } .target-switch button { - border-radius: 9px; + padding: 7px 11px; + border: 0; + border-radius: 8px; + color: #4d6078; + background: transparent; + font-size: 10px; + font-weight: 800; + white-space: nowrap; +} + +.target-switch button.active { + color: #274f91; + background: #ffffff; + box-shadow: 0 3px 10px rgba(36, 64, 107, 0.1); } footer { - min-height: 48px; - padding-top: 4px; - font-size: 11px; + min-width: 0; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 14px; + padding: 0 1px; + color: #53647b; + font-size: 10px; + line-height: 1.35; +} + +footer > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.wizard-actions { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: 7px; } footer button { - min-width: 164px; - padding: 11px 18px; - border-radius: 11px; + min-width: 154px; + padding: 10px 14px; + border: 0; + border-radius: 9px; + color: #ffffff; background: linear-gradient(135deg, #3568b9, #28569d); - font-size: 12px; - box-shadow: 0 9px 20px rgba(49, 95, 170, 0.24); - transition: - transform 0.18s ease, - box-shadow 0.18s ease, - filter 0.18s ease; + font-size: 11px; + font-weight: 900; + box-shadow: 0 8px 18px rgba(49, 95, 170, 0.22); + transition: transform 0.18s ease, box-shadow 0.18s ease, filter 0.18s ease; } -footer button:not(:disabled):hover { +footer button:not(:disabled):hover, +.dns-test-button:not(:disabled):hover { transform: translateY(-1px); filter: brightness(1.04); - box-shadow: 0 12px 24px rgba(49, 95, 170, 0.28); + box-shadow: 0 11px 22px rgba(49, 95, 170, 0.27); } footer .back-button { - min-width: 88px; - background: #fff; + min-width: 84px; + border: 1px solid #d5ddea; + color: #32405a; + background: #ffffff; + box-shadow: none; +} + +button { + cursor: pointer; +} + +button:disabled { + cursor: wait; + opacity: 0.62; } @media (max-width: 1200px) and (min-width: 901px) { - .setup-shell { - height: min(680px, calc(100dvh - 32px)); - grid-template-columns: clamp(230px, 25vw, 280px) minmax(0, 1fr); - } - - .intro-inner { - padding: 32px 23px 25px; - } - - .brand-mark { - width: 74px; - height: 74px; - margin-bottom: 23px; - } - - .setup-intro h1 { - font-size: 28px; - } - .setup-card { - padding: 28px 28px 22px; - } - - .setup-card > header, - .setup-progress { - margin-bottom: 13px; + padding: 22px 24px 18px; + gap: 11px; } .setup-progress { @@ -1112,43 +638,26 @@ footer .back-button { } fieldset { - padding: 16px 17px; - } - - input, - select { - height: 37px; + padding: 15px 17px; } } -@media (max-height: 760px) and (min-width: 901px) { - .setup-shell { - height: calc(100dvh - 24px); - } - - .intro-inner { - padding-top: 24px; - padding-bottom: 20px; - } - - .brand-mark { - width: 66px; - height: 66px; - margin-bottom: 17px; - } - - .warning-card { - padding: 9px 11px; - } - +@media (max-height: 800px) and (min-width: 901px) { .setup-card { - padding-top: 20px; - padding-bottom: 16px; + padding-top: 18px; + padding-bottom: 15px; + gap: 9px; } - .setup-card > header, .setup-progress { - margin-bottom: 9px; + padding-top: 8px; + padding-bottom: 8px; + margin-bottom: 0; + } + + .progress-step b { + width: 26px; + height: 26px; } fieldset { @@ -1157,6 +666,7 @@ footer .back-button { } label { + gap: 3px; margin-top: 5px; } @@ -1164,434 +674,354 @@ footer .back-button { select { height: 33px; } + + textarea { + min-height: 44px; + padding-top: 6px; + padding-bottom: 6px; + } + + .notification-credential-field textarea { + min-height: 46px; + } + + .provider-description, + .dns-verification-success, + .dns-test-actions { + margin-top: 6px; + } + + footer button { + padding-top: 8px; + padding-bottom: 8px; + } } @media (max-width: 900px) { - .setup-shell { - width: min(calc(100% - 24px), 760px); - height: calc(100dvh - 24px); - max-height: none; - grid-template-columns: 1fr; - grid-template-rows: 108px minmax(0, 1fr); - border-radius: 23px; - } - - .intro-inner { - display: grid; - grid-template-columns: auto minmax(0, 1fr); - align-items: center; - column-gap: 17px; - padding: 17px 23px; - } - - .brand-mark { - grid-row: 1 / span 2; - width: 70px; - height: 70px; - margin: 0; - } - - .setup-intro .setup-eyebrow { - margin-bottom: 3px; - } - - .setup-intro h1 { - max-width: none; - margin-bottom: 3px; - font-size: 25px; - } - - .intro-description { - max-width: none; - font-size: 10px; - line-height: 1.4; - } - - .warning-card { - display: none; - } - .setup-card { - padding: 16px 20px 13px; - } - - .setup-card > header, - .setup-progress { - margin-bottom: 9px; - } - - .setup-card h2 { - font-size: 25px; + padding: 16px 18px 14px; + gap: 9px; } .setup-progress { + gap: 4px; padding: 8px 9px; } + .progress-step { + column-gap: 6px; + } + + .progress-step b { + width: 25px; + height: 25px; + font-size: 10px; + } + + .progress-step strong { + font-size: 10px; + } + + .progress-step small { + display: none; + } + fieldset { - padding: 11px 13px; + padding: 12px 13px; } - label { - margin-top: 4px; - } - - input, - select { - height: 33px; - } -} - -@media (max-width: 600px) { - .setup-shell { - width: calc(100% - 12px); - height: calc(100dvh - 12px); - grid-template-rows: 80px minmax(0, 1fr); - border-radius: 17px; - } - - .intro-inner { - column-gap: 10px; - padding: 8px 13px; - } - - .brand-mark { - width: 52px; - height: 52px; - } - - .setup-intro h1 { - font-size: 19px; - } - - .intro-description { + footer { + gap: 9px; font-size: 9px; } + footer button { + min-width: 128px; + padding: 9px 11px; + } +} + +@media (max-width: 640px) { .setup-card { - padding: 8px 9px 7px; + padding: 10px 10px 9px; } .setup-card h2 { - font-size: 19px; + font-size: 20px; + } + + .local-badge { + padding: 5px 8px; + font-size: 9px; } .setup-progress { - border-radius: 10px; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 3px; + padding: 6px; + } + + .setup-progress i { + display: none; + } + + .progress-step { + grid-template-columns: auto minmax(0, 1fr); + column-gap: 4px; } .progress-step b { width: 21px; height: 21px; + font-size: 9px; + } + + .progress-step strong { + font-size: 9px; } fieldset { - padding: 7px; + padding: 8px; + border-radius: 11px; + } + + legend { + font-size: 10px; + } + + legend span { + width: 19px; + height: 19px; + margin-right: 4px; + border-radius: 6px; + font-size: 8px; + } + + .two-columns, + .three-columns, + .email-primary-grid, + .email-delivery-grid { + grid-template-columns: minmax(0, 1fr); + } + + .email-field { + grid-column: auto; } input, select { - height: 26px; - } - .email-field { - grid-column: 1 / -1; - } - - - .email-input-group { - grid-template-columns: minmax(0, 1fr) minmax(74px, 92px); - gap: 5px; - } - - footer { - min-height: 34px; - } -} - -@media (max-width: 600px) { - .setup-card footer { - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - align-items: center; - gap: 6px; - min-height: 34px; - height: auto; - } - - .setup-card footer > span { - min-width: 0; - overflow: hidden; - font-size: 8px; - line-height: 1.25; - } - - .setup-card .wizard-actions { - min-width: 0; - gap: 4px; - } - - .setup-card footer button { - min-width: 0; - width: auto; - padding: 6px 8px; - font-size: 9px; - } - - .setup-card footer .back-button { - min-width: 0; - } -} - -@media (max-width: 390px) { - .setup-card footer { - gap: 4px; - } - - .setup-card footer > span { - font-size: 7px; - line-height: 1.2; - } - - .setup-card footer button { - padding: 5px 6px; - font-size: 8px; - } -} -/* 移动端步骤内容压缩,确保复杂配置步骤完整显示 */ -@media (max-width: 600px) { - .setup-card { - overflow: hidden; - } - - .setup-step-card { - height: auto; - overflow: visible; - } - - .setup-step-card .setup-grid { - gap: 2px 5px; - } - - .setup-step-card label { - gap: 1px; - margin-top: 2px; - } - - .setup-step-card input, - .setup-step-card select { - height: 24px; - } - - .setup-step-card textarea { - min-height: 30px; height: 30px; - padding-top: 4px; - padding-bottom: 4px; - } - - .setup-step-card .provider-description { - margin-top: 2px; - padding-top: 4px; - padding-bottom: 4px; - } - - .setup-step-card .reset-preview span:first-of-type { - display: block !important; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .setup-step-card .reset-preview span:last-of-type { - display: none !important; - } - - .setup-step-card .dns-test-actions { - margin-top: 2px; - } -} - -@media (max-width: 390px) { - .setup-step-card .setup-grid { - gap: 1px 4px; - } - - .setup-step-card label { - gap: 1px; - margin-top: 1px; - } - - .setup-step-card input, - .setup-step-card select { - height: 22px; - } - - .setup-step-card textarea { - min-height: 26px; - height: 26px; - } -} - - -@media (min-width: 901px) { - .setup-notification-step:has(#email-http-enabled:checked) > .email-primary-grid, - .setup-notification-step:has(#email-http-enabled:checked) > .email-delivery-grid { - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 4px 7px; - } - - .setup-notification-step:has(#email-http-enabled:checked) { - padding: 12px 14px; - } - - .setup-notification-step:has(#email-http-enabled:checked) legend { - font-size: 11px; - } - - .setup-notification-step:has(#email-http-enabled:checked) label { - gap: 2px; - margin-top: 2px; - font-size: 9px; - } - - .setup-notification-step:has(#email-http-enabled:checked) label > span { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .setup-notification-step:has(#email-http-enabled:checked) input, - .setup-notification-step:has(#email-http-enabled:checked) select { - height: 26px; padding: 0 8px; font-size: 10px; } - .setup-notification-step:has(#email-http-enabled:checked) textarea { - min-height: 30px; - height: 30px; - padding: 4px 8px; + textarea { + min-height: 42px; font-size: 10px; } - .setup-notification-step:has(#email-http-enabled:checked) .provider-description { - overflow: hidden; - margin-top: 3px; - padding: 4px 8px; - font-size: 9px; - line-height: 1.25; - white-space: nowrap; - text-overflow: ellipsis; + .notification-credential-field textarea { + min-height: 42px; } - .setup-notification-step:has(#email-http-enabled:checked) .email-option-grid { - gap: 4px; - margin-top: 3px; - } - - .setup-notification-step:has(#email-http-enabled:checked) .compact-row { - min-height: 26px; - padding: 4px 6px; - } -} - - -@media (min-width: 901px) and (max-height: 800px) { - .setup-notification-step:has(#email-http-enabled:checked) label { - gap: 1px; - margin-top: 1px; - font-size: 8px; - } - - .setup-notification-step:has(#email-http-enabled:checked) input, - .setup-notification-step:has(#email-http-enabled:checked) select { - height: 22px; - padding: 0 6px; - font-size: 9px; - } - - .setup-notification-step:has(#email-http-enabled:checked) textarea { - min-height: 24px; - height: 24px; - padding: 3px 6px; - font-size: 9px; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview { - display: flex; - align-items: center; - height: 28px; - margin-top: 2px; - padding: 3px 6px; - gap: 5px; - font-size: 8px; - line-height: 1.15; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview strong, - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview span { - display: inline !important; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview span { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview strong { - flex: 0 0 auto; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview span:first-of-type { - flex: 0 1 auto; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview span:last-of-type { - flex: 1 1 auto; - } - - .setup-notification-step:has(#email-http-enabled:checked) .email-option-grid { + label { gap: 3px; - margin-top: 2px; + margin-top: 5px; + font-size: 9px; } - .setup-notification-step:has(#email-http-enabled:checked) .compact-row { - min-height: 22px; - padding: 2px 4px; - } -} - - -@media (min-width: 901px) { - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview { - display: flex; - align-items: center; - height: 30px; - gap: 6px; + label > small { + display: none; } - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview strong, - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview span { - display: inline !important; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview strong { - flex: 0 0 auto; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview span:first-of-type { - flex: 0 1 auto; - } - - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview span:last-of-type { - flex: 1 1 auto; - } -} - -@media (min-width: 901px) and (max-height: 800px) { - .setup-notification-step:has(#email-http-enabled:checked) .reset-preview { - height: 28px; + .email-input-group { + grid-template-columns: minmax(0, 1fr) minmax(78px, 96px); gap: 5px; } + + .provider-description, + .dns-verification-success { + padding: 6px 8px; + font-size: 9px; + } + + .provider-description span, + .dns-verification-success span, + .dns-test-actions > span { + display: none; + } + + .dns-test-actions { + margin-top: 5px; + } + + .dns-test-button { + min-width: 96px; + padding: 6px 8px; + font-size: 9px; + } + + .reset-preview { + gap: 5px; + font-size: 9px; + } + + footer { + grid-template-columns: minmax(0, 1fr) auto; + gap: 6px; + font-size: 8px; + } + + footer > span { + white-space: normal; + } + + .wizard-actions { + gap: 4px; + } + + footer button { + min-width: 92px; + padding: 7px 8px; + font-size: 9px; + } + + footer .back-button { + min-width: 58px; + } } + +/* 初始化第二步采用分组网格,避免通知配置在低高度窗口中纵向堆叠。 */ +.setup-notification-step { + display: flex; + flex-direction: column; + min-height: 0; +} + +.notification-layout { + min-width: 0; + min-height: 0; + display: grid; + gap: 7px; +} + +.notification-row { + min-width: 0; + display: grid; + align-items: end; + gap: 8px 10px; +} + +.notification-row label { + min-width: 0; + margin-top: 0; +} + +.notification-service-row, +.notification-api-row, +.notification-sender-row { + grid-template-columns: repeat(3, minmax(0, 1fr)); +} + +.notification-auth-row { + grid-template-columns: repeat(3, minmax(0, 1fr)); +} + +.notification-delivery-row { + grid-template-columns: repeat(4, minmax(0, 1fr)); +} + +.notification-auth-note { + min-width: 0; + min-height: 34px; + display: flex; + align-items: center; + padding: 0 10px; + border: 1px dashed #d5dfed; + border-radius: 9px; + color: #687891; + background: #f8fafd; + font-size: 9px; + line-height: 1.35; +} + +.setup-notification-step input, +.setup-notification-step select { + height: 34px; +} + +.setup-notification-step textarea { + min-height: 48px; +} + +.notification-credential-field { + margin-top: 0; +} + +.notification-credential-field textarea { + min-height: 50px; +} + +.reset-preview { + min-height: 30px; + margin-top: 0; + padding-top: 6px; + padding-bottom: 6px; +} + +.notification-bottom-row { + min-width: 0; + display: grid; + grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr); + align-items: stretch; + gap: 10px; +} + +.notification-bottom-row .email-headers-field { + min-width: 0; + margin-top: 0; +} + +.notification-bottom-row .email-option-grid { + min-width: 0; + align-items: stretch; + gap: 6px; +} + +.notification-bottom-row .compact-row { + min-height: 34px; + margin-top: 0; + padding: 6px 8px; +} + +@media (max-width: 900px) and (min-width: 641px) { + .notification-service-row, + .notification-api-row, + .notification-auth-row, + .notification-sender-row { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .notification-delivery-row { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .notification-bottom-row { + grid-template-columns: minmax(0, 1fr); + } +} + +@media (max-width: 640px) { + .notification-service-row, + .notification-api-row, + .notification-auth-row, + .notification-sender-row, + .notification-delivery-row, + .notification-bottom-row { + grid-template-columns: minmax(0, 1fr); + } + + .notification-bottom-row .email-option-grid { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } +} \ No newline at end of file diff --git a/frontend/src/views/SetupWizard/SetupWizard.js b/frontend/src/views/SetupWizard/SetupWizard.js index 5be8b74..e8ca844 100644 --- a/frontend/src/views/SetupWizard/SetupWizard.js +++ b/frontend/src/views/SetupWizard/SetupWizard.js @@ -27,6 +27,9 @@ export function useSetupWizard(props, emit) { const dnsTestError = ref(""); const dnsProviders = ref([]); const dnsCredentials = ref({}); + const dnsCredentialsVisible = ref(true); + const emailCredentials = ref(""); + const emailCredentialsVisible = ref(true); const dnsTestDomain = ref(props.status.web_hostname || ""); const dnsVerification = ref(null); const verificationClock = ref(Date.now()); @@ -60,6 +63,9 @@ export function useSetupWizard(props, emit) { email_retry_intervals_secs: "30,120,600", recipients: "", dns_provider: props.status.dns_provider || "cloudflare", + propagation_timeout_secs: props.status.propagation_timeout_secs || 900, + propagation_polling_interval_secs: + props.status.propagation_polling_interval_secs || 10, certificate_root: props.status.certificate_root || "", web_hostname: props.status.web_hostname || "", web_public_ip: props.status.web_public_ip || "", @@ -70,6 +76,30 @@ export function useSetupWizard(props, emit) { const targetLabel = computed(() => targetType.value === "hostname" ? "管理页面域名" : "公网 IP 地址", ); + const emailCredentialLabel = computed(() => { + switch (form.value.email_http_auth_mode) { + case "bearer": + return "Bearer Token 凭据(JSON)"; + case "hmac_sha256": + return "HMAC-SHA256 凭据(JSON)"; + case "session": + return "登录会话凭据(JSON)"; + default: + return "HTTP 通知凭据"; + } + }); + const emailCredentialPlaceholder = computed(() => { + switch (form.value.email_http_auth_mode) { + case "bearer": + return '{"token":"请输入 Bearer Token"}'; + case "hmac_sha256": + return '{"secret":"请输入签名密钥"}'; + case "session": + return '{"account":"请输入账号","password":"请输入密码"}'; + default: + return "无需填写凭据"; + } + }); const resetURLPreview = computed(() => { const rawHost = targetType.value === "hostname" @@ -191,6 +221,33 @@ export function useSetupWizard(props, emit) { return payload; } + function maskCredential(value) { + const text = String(value || ""); + if (!text) return ""; + return "•".repeat(Math.min(Math.max(text.length, 8), 64)); + } + + function emailCredentialPayload() { + if ( + !form.value.email_http_enabled || + form.value.email_http_auth_mode === "none" + ) { + return {}; + } + const text = emailCredentials.value.trim(); + if (!text) return {}; + const parsed = JSON.parse(text); + if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") { + throw new Error("HTTP 通知凭据必须是 JSON 对象。"); + } + for (const [key, value] of Object.entries(parsed)) { + if (!key.trim() || typeof value !== "string" || !value.trim()) { + throw new Error("HTTP 通知凭据的字段和值必须是非空文本。"); + } + } + return parsed; + } + async function testDNS() { dnsTestError.value = ""; resultMessage.value = ""; @@ -280,11 +337,24 @@ export function useSetupWizard(props, emit) { if ( form.value.email_http_enabled && form.value.email_http_auth_mode !== "none" && - !form.value.email_http_credential_ref.trim() + !form.value.email_http_credential_ref.trim() && + !emailCredentials.value.trim() ) { - error.value = "启用 HTTP 通知认证后必须填写凭据引用。"; + error.value = "启用 HTTP 通知认证后必须填写明文凭据或已有凭据引用。"; return false; } + if ( + form.value.email_http_enabled && + form.value.email_http_auth_mode !== "none" && + emailCredentials.value.trim() + ) { + try { + emailCredentialPayload(); + } catch (err) { + error.value = err.message || "HTTP 通知凭据格式无效。"; + return false; + } + } if (form.value.email_http_headers.trim()) { try { const headers = JSON.parse(form.value.email_http_headers); @@ -299,6 +369,26 @@ export function useSetupWizard(props, emit) { } if (currentStep.value === 3) { + const propagationTimeout = Number(form.value.propagation_timeout_secs); + const propagationInterval = Number( + form.value.propagation_polling_interval_secs, + ); + if ( + !Number.isInteger(propagationTimeout) || + propagationTimeout < 1 || + propagationTimeout > 86400 + ) { + error.value = "DNS 传播最大等待时间必须在 1 至 86400 秒之间。"; + return false; + } + if ( + !Number.isInteger(propagationInterval) || + propagationInterval < 1 || + propagationInterval > propagationTimeout + ) { + error.value = "DNS 传播检测间隔必须大于 0 且不超过最大等待时间。"; + return false; + } const provider = selectedDNSProvider.value; if (!provider) { error.value = "请选择 DNS 服务商。"; @@ -398,6 +488,12 @@ export function useSetupWizard(props, emit) { error.value = "必须先完成 DNS API 在线验证;验证结果已过期时请重新测试。"; return; } + try { + emailCredentialPayload(); + } catch (err) { + error.value = err.message || "HTTP 通知凭据格式无效。"; + return; + } const hostname = targetType.value === "hostname" ? form.value.web_hostname.trim() : ""; const publicIP = @@ -422,9 +518,10 @@ export function useSetupWizard(props, emit) { email_endpoint: form.value.email_endpoint, email_http_path: form.value.email_http_path, email_http_login_path: form.value.email_http_login_path, - email_http_auth_mode: form.value.email_http_auth_mode, - email_http_credential_ref: form.value.email_http_credential_ref, - email_http_headers: emailHeaders(), + email_http_auth_mode: form.value.email_http_auth_mode, + email_http_credential_ref: form.value.email_http_credential_ref, + email_http_credentials: emailCredentialPayload(), + email_http_headers: emailHeaders(), email_event_mode: form.value.email_event_mode, email_include_deployment_details: form.value.email_include_deployment_details, @@ -441,6 +538,12 @@ export function useSetupWizard(props, emit) { dns_credential_ref: dnsVerification.value.credential_ref, dns_verification_token: dnsVerification.value.verification_token, dns_test_domain: dnsTestDomain.value.trim(), + propagation_timeout_secs: Number( + form.value.propagation_timeout_secs, + ), + propagation_polling_interval_secs: Number( + form.value.propagation_polling_interval_secs, + ), certificate_root: form.value.certificate_root, web_hostname: hostname, web_public_ip: publicIP, @@ -492,6 +595,10 @@ export function useSetupWizard(props, emit) { dnsTestError, dnsProviders, dnsCredentials, + dnsCredentialsVisible, + maskCredential, + emailCredentials, + emailCredentialsVisible, dnsTestDomain, dnsVerification, currentStep, @@ -501,6 +608,8 @@ export function useSetupWizard(props, emit) { selectedEmailDomain, emailLocalPart, targetLabel, + emailCredentialLabel, + emailCredentialPlaceholder, resetURLPreview, selectedDNSProvider, dnsVerificationValid, diff --git a/frontend/src/views/SetupWizard/SetupWizard.vue b/frontend/src/views/SetupWizard/SetupWizard.vue index bad2f40..d0eacfe 100644 --- a/frontend/src/views/SetupWizard/SetupWizard.vue +++ b/frontend/src/views/SetupWizard/SetupWizard.vue @@ -22,6 +22,8 @@ const { dnsTestError, dnsProviders, dnsCredentials, + dnsCredentialsVisible, + maskCredential, dnsTestDomain, dnsVerification, currentStep, @@ -172,162 +174,268 @@ const { -