From 7f0af703ed226527e2f7acba74de9c842ace1c13 Mon Sep 17 00:00:00 2001 From: xuans Date: Sun, 30 Aug 2026 17:44:54 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=20Scert=20=E5=89=8D=E5=90=8E?= =?UTF-8?q?=E7=AB=AF=E4=B8=8E=E9=83=A8=E7=BD=B2=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- backend/README.md | 18 +- backend/internal/app/app.go | 8 + backend/internal/app/app_test.go | 29 + backend/internal/certificate/lifecycle.go | 474 +++++++++-- .../certificate/lifecycle_version_test.go | 131 ++- backend/internal/certificate/service.go | 38 + backend/internal/certificate/service_test.go | 59 +- backend/internal/cli/operations.go | 79 +- backend/internal/cli/root.go | 125 ++- backend/internal/cli/root_test.go | 7 +- backend/internal/cli/service.go | 102 +++ backend/internal/config/config.go | 28 + backend/internal/dnsprovider/catalog.go | 4 +- .../internal/dnsprovider/cname_provider.go | 38 + .../dnsprovider/cname_provider_test.go | 105 +++ backend/internal/dnsprovider/errors.go | 9 + backend/internal/dnsprovider/lego_factory.go | 23 + backend/internal/dnsprovider/tester.go | 165 +++- backend/internal/dnsprovider/tester_test.go | 99 ++- .../httpapi/certificate_restore_api.go | 37 + .../httpapi/certificate_restore_api_test.go | 116 +++ backend/internal/httpapi/frontend.go | 89 ++ backend/internal/httpapi/frontend_test.go | 73 ++ backend/internal/httpapi/renewal_api.go | 23 + backend/internal/httpapi/reset.go | 2 +- backend/internal/httpapi/server.go | 86 +- backend/internal/httpapi/server_test.go | 16 +- backend/internal/httpapi/settings_api.go | 348 ++++++++ backend/internal/httpapi/settings_api_test.go | 211 +++++ backend/internal/httpapi/settings_secrets.go | 54 ++ backend/internal/httpapi/setup.go | 106 ++- backend/internal/httpapi/setup_test.go | 92 ++- backend/internal/notification/service.go | 31 +- backend/internal/notification/service_test.go | 77 ++ backend/internal/notification/smtp.go | 228 ++++++ backend/internal/notification/smtp_test.go | 365 +++++++++ backend/internal/passwordpolicy/password.go | 2 +- .../internal/passwordpolicy/password_test.go | 2 + backend/internal/servicehost/linux.go | 81 ++ backend/internal/servicehost/service.go | 65 ++ backend/internal/servicehost/service_test.go | 47 ++ backend/internal/servicehost/unsupported.go | 15 + backend/internal/servicehost/windows.go | 90 ++ backend/internal/setup/dns_verification.go | 56 +- .../internal/setup/dns_verification_test.go | 39 +- backend/internal/setup/setup.go | 23 +- backend/service/handler_test.go | 17 + backend/service/runtime.go | 90 ++ backend/service/runtime_test.go | 68 ++ deploy/README.md | 99 ++- deploy/install-linux.sh | 12 +- deploy/install-windows.ps1 | 192 +++++ deploy/systemd/Scert服务管理说明.md | 1 + desktop/.gitignore | 8 + desktop/README.md | 23 + desktop/frontend/dist/index.html | 14 + desktop/frontend/package-lock.json | 11 + desktop/frontend/package.json | 8 + desktop/go.mod | 131 +++ desktop/go.sum | 571 +++++++++++++ desktop/main.go | 81 ++ desktop/main_test.go | 63 ++ desktop/scripts/build-frontend.mjs | 24 + desktop/wails.json | 14 + doc/SSL服务程序技术架构设计文档.md | 31 +- doc/SSL服务程序需求确认文档.md | 36 +- doc/Scert开发任务清单.md | 231 ++++++ doc/邮件通知配置说明.md | 6 +- frontend/src/App.js | 23 + frontend/src/App.vue | 5 +- frontend/src/views/Dashboard/Dashboard.css | 221 ++++- frontend/src/views/Dashboard/Dashboard.js | 390 ++++++++- frontend/src/views/Dashboard/Dashboard.vue | 356 ++++++-- frontend/src/views/Login/Login.js | 2 +- frontend/src/views/Login/Login.vue | 8 +- .../src/views/PasswordReset/PasswordReset.css | 53 ++ .../src/views/PasswordReset/PasswordReset.js | 57 +- .../src/views/PasswordReset/PasswordReset.vue | 79 +- .../src/views/SetupWizard/SetupWizard.css | 392 ++++++++- frontend/src/views/SetupWizard/SetupWizard.js | 264 +++++- .../src/views/SetupWizard/SetupWizard.vue | 770 +++++++++++------- .../views/SuperAdminReset/SuperAdminReset.js | 6 +- .../views/SuperAdminReset/SuperAdminReset.vue | 6 +- frontend/vite.config.js | 48 +- 85 files changed, 7530 insertions(+), 800 deletions(-) create mode 100644 backend/internal/app/app_test.go create mode 100644 backend/internal/cli/service.go create mode 100644 backend/internal/dnsprovider/cname_provider.go create mode 100644 backend/internal/dnsprovider/cname_provider_test.go create mode 100644 backend/internal/dnsprovider/errors.go create mode 100644 backend/internal/httpapi/certificate_restore_api.go create mode 100644 backend/internal/httpapi/certificate_restore_api_test.go create mode 100644 backend/internal/httpapi/frontend.go create mode 100644 backend/internal/httpapi/frontend_test.go create mode 100644 backend/internal/httpapi/renewal_api.go create mode 100644 backend/internal/httpapi/settings_api.go create mode 100644 backend/internal/httpapi/settings_api_test.go create mode 100644 backend/internal/httpapi/settings_secrets.go create mode 100644 backend/internal/notification/smtp.go create mode 100644 backend/internal/notification/smtp_test.go create mode 100644 backend/internal/servicehost/linux.go create mode 100644 backend/internal/servicehost/service.go create mode 100644 backend/internal/servicehost/service_test.go create mode 100644 backend/internal/servicehost/unsupported.go create mode 100644 backend/internal/servicehost/windows.go create mode 100644 backend/service/handler_test.go create mode 100644 backend/service/runtime.go create mode 100644 backend/service/runtime_test.go create mode 100644 deploy/install-windows.ps1 create mode 100644 desktop/.gitignore create mode 100644 desktop/README.md create mode 100644 desktop/frontend/dist/index.html create mode 100644 desktop/frontend/package-lock.json create mode 100644 desktop/frontend/package.json create mode 100644 desktop/go.mod create mode 100644 desktop/go.sum create mode 100644 desktop/main.go create mode 100644 desktop/main_test.go create mode 100644 desktop/scripts/build-frontend.mjs create mode 100644 desktop/wails.json diff --git a/README.md b/README.md index 1c6cee7..134f146 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Scert 是一个统一管理 SSL 证书、自动续期并部署到多台服务器 ## 项目目录 - `backend`:Go 核心服务、CLI、数据库和 HTTP API。 -- `frontend`:Vue Web 管理界面占位结构。 +- `frontend`:Vue Web 管理界面。 - `doc`:需求确认、技术架构和开发任务清单。 ## 开发基线 @@ -18,7 +18,7 @@ Scert 是一个统一管理 SSL 证书、自动续期并部署到多台服务器 ## 开发状态 -首轮基础骨架已经完成并等待复审。当前已完成配置、日志、数据库迁移、域名 Repository、基础 HTTP API、CLI 和前端占位页面;完整证书生命周期功能按 `doc/Scert开发任务清单.md` 继续开发。 +当前已完成配置、日志、数据库迁移、域名与服务器管理、管理员认证、DNS API 在线测试、lego DNS-01、证书申请与导入、自动续期、SSH 部署、通知、设置接口和 Web 管理页面;真实 DNS、ACME、远程服务器及平台安装验收仍需在授权环境完成。 详细内容请先阅读: diff --git a/backend/README.md b/backend/README.md index caaf4c5..ccb4bcf 100644 --- a/backend/README.md +++ b/backend/README.md @@ -1,6 +1,6 @@ # Scert -Scert 是面向 Windows 和 Linux 的 SSL 证书管理服务。当前代码处于首轮基础骨架阶段,已建立配置、数据库、日志、CLI、HTTP API 和前端占位结构。 +Scert 是面向 Windows 和 Linux 的 SSL 证书管理服务。当前代码已覆盖核心证书生命周期、DNS-01、自动续期、SSH 部署、通知、认证和 Web 管理流程。 ## 当前已实现 @@ -12,7 +12,7 @@ Scert 是面向 Windows 和 Linux 的 SSL 证书管理服务。当前代码处 - 域名基础模型与 Repository。 - 健康检查、状态和域名基础 API。 - 中文 CLI:`version`、`help`、`init`、`status`、`serve`、`domain list`、`domain add`。 -- Vue 前端状态占位页面。 +- Vue 前端管理页面。 ## 首轮运行 @@ -34,7 +34,13 @@ go run ./cmd/scert serve --base-dir C:\ScertData - `POST /api/v1/domains` - `DELETE /api/v1/domains/:id` -当前 `serve` 是 HTTP 基础骨架。HTTPS 双模式、ACME 证书申请、DNS-01、远程部署等功能按开发任务清单在后续阶段实现。 +当前 `serve` 已接入配置加载、数据库迁移、认证、DNS 在线测试、ACME 证书申请、自动续期、证书导入、SSH 部署和通知流程。HTTPS 生产切换、真实 DNS/ACME 申请、远程服务器及平台安装仍需授权环境验收。 + +### 开发阶段使用 9003 端口 + +反向代理开发测试时,将配置中的服务地址设为 `127.0.0.1`、端口设为 `9003`,并将 `https_mode` 设为 `proxy`。Scert 只提供本机内部 HTTPS,公网 HTTPS 由 Nginx 监听 `443` 并转发到 `https://127.0.0.1:9003`。端口可通过配置文件 `server.port` 或初始化参数 `--server-port` 修改;修改后需要重启服务。 + +SMTP 通知是 Scert 的出站连接,不需要为 Scert 开放 SMTP 入站端口。公网防火墙通常只需放行 Nginx 使用的 `443`,若配置 HTTP 跳转再放行 `80`;内部端口 `9003` 不应对公网开放。 ## 测试和构建 @@ -62,10 +68,10 @@ Remove-Item Env:GOARCH - 数据库密码不得写入 Git、脚本参数或日志。 - MySQL 客户端和服务实例必须使用明确路径、端口和 DSN,不能通过 PATH 中的单个 `mysql` 命令判断版本。 -## 当前未实现 +## 当前生产验收边界 -ACME/lego 实际申请、DNS 服务商 API、自动续期、SSH/SFTP 部署、Nginx/Caddy/Apache reload、完整 Web 管理界面、Wails 桌面版、Windows Service 和 Linux systemd 均未在首轮基础骨架中宣称完成。 +代码层已实现 ACME/lego 申请、第一批 DNS Provider、CNAME 委派、自动续期、证书导入、SSH/SFTP 部署、Nginx/Caddy/Apache reload、通知和 Web 管理接口。以下项目不能仅凭本地自动化测试宣称生产完成:真实 DNS 权限与公网传播、Let’s Encrypt Production 签发、真实远程服务器部署、Windows Service、Linux systemd 实机安装、Wails 桌面封装、Windows ACL、MySQL 真实实例和最终 HTTPS 到达性验收。 ## 首轮复审状态 -2026 年 8 月 26 日已完成首轮代码复审。`gofmt`、`go vet`、`go test`、竞态检测、Windows amd64 构建、Linux amd64 交叉构建、CLI 和 HTTP 实际流程均通过。MySQL 5.7/8.0 仅完成代码层实现和客户端版本确认,真实实例连接与迁移仍需明确 DSN、端口和凭据后验证。 \ No newline at end of file +2026 年 8 月 26 日已完成首轮代码复审。`gofmt`、`go vet`、`go test`、竞态检测、Windows amd64 构建、Linux amd64 交叉构建、CLI 和 HTTP 实际流程均通过。MySQL 5.7/8.0 仅完成代码层实现和客户端版本确认,真实实例连接与迁移仍需明确 DSN、端口和凭据后验证。 diff --git a/backend/internal/app/app.go b/backend/internal/app/app.go index a7c90a0..9d3ce8d 100644 --- a/backend/internal/app/app.go +++ b/backend/internal/app/app.go @@ -116,6 +116,12 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string result, err := workflow.DeployCurrent(ctx, domainID) return result.Certificate, result.Deployment, err }, + RestoreCertificateVersion: func(ctx context.Context, domainID, version string) (certificate.IssueResult, error) { + return certificates.RestoreVersion(ctx, domainID, version) + }, + RunRenewal: func(ctx context.Context) (certificate.RenewalReport, error) { + return renewal.RunOnce(ctx) + }, CurrentCertificate: certificates, ResetStatePath: admin.StatePath(cfg.Paths.Data), Audit: auditRepo, @@ -123,7 +129,9 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string }) return &App{ Config: cfg, Logger: logger, Database: db, Repository: repo, + Servers: serverRepo, Tasks: taskRepo, + Deployment: deploymentService, SecretStore: secretStore, SSHKeys: sshKeys, DNSVerification: dnsVerification, HTTP: server, Certificates: certificates, Workflow: workflow, diff --git a/backend/internal/app/app_test.go b/backend/internal/app/app_test.go new file mode 100644 index 0000000..faa4d82 --- /dev/null +++ b/backend/internal/app/app_test.go @@ -0,0 +1,29 @@ +package app + +import ( + "context" + "path/filepath" + "testing" + + "git.pcux.cn/xuans/Scert/backend/internal/config" +) + +func TestNewWiresApplicationServices(t *testing.T) { + baseDir := t.TempDir() + cfg := config.Default(baseDir) + application, err := NewWithConfigPath(context.Background(), cfg, filepath.Join(cfg.Paths.Config, "scert.json")) + if err != nil { + t.Fatalf("初始化应用失败:%v", err) + } + defer application.Close() + + if application.Repository == nil || application.Servers == nil || application.Tasks == nil { + t.Fatal("数据库仓储未完整注入应用实例") + } + if application.Deployment == nil || application.Certificates == nil || application.Workflow == nil || application.Renewal == nil { + t.Fatal("证书申请、部署或续期服务未完整注入应用实例") + } + if application.SecretStore == nil || application.SSHKeys == nil || application.DNSVerification == nil || application.HTTP == nil { + t.Fatal("敏感信息、SSH、DNS 或 HTTP 服务未完整注入应用实例") + } +} diff --git a/backend/internal/certificate/lifecycle.go b/backend/internal/certificate/lifecycle.go index 445255f..0bccf82 100644 --- a/backend/internal/certificate/lifecycle.go +++ b/backend/internal/certificate/lifecycle.go @@ -14,6 +14,7 @@ import ( "path/filepath" "runtime" "sort" + "strconv" "strings" "time" ) @@ -39,20 +40,21 @@ type Resource struct { } type SavedResource struct { - Domain string `json:"domain"` - CertificateType string `json:"certificate_type,omitempty"` - Version string `json:"version,omitempty"` - SANs []string `json:"sans,omitempty"` - SerialNumber string `json:"serial_number,omitempty"` - FingerprintSHA256 string `json:"fingerprint_sha256,omitempty"` - ChainLength int `json:"chain_length,omitempty"` - Directory string `json:"directory"` - CertificatePath string `json:"certificate_path"` - FullChainPath string `json:"fullchain_path"` - PrivateKeyPath string `json:"private_key_path"` - NotBefore time.Time `json:"not_before"` - NotAfter time.Time `json:"not_after"` - BackupDirectory string `json:"backup_directory,omitempty"` + Domain string `json:"domain"` + CertificateType string `json:"certificate_type,omitempty"` + CertificateIdentifier string `json:"certificate_identifier,omitempty"` + Version string `json:"version,omitempty"` + SANs []string `json:"sans,omitempty"` + SerialNumber string `json:"serial_number,omitempty"` + FingerprintSHA256 string `json:"fingerprint_sha256,omitempty"` + ChainLength int `json:"chain_length,omitempty"` + Directory string `json:"directory"` + CertificatePath string `json:"certificate_path"` + FullChainPath string `json:"fullchain_path"` + PrivateKeyPath string `json:"private_key_path"` + NotBefore time.Time `json:"not_before"` + NotAfter time.Time `json:"not_after"` + BackupDirectory string `json:"backup_directory,omitempty"` } type FileStore struct { @@ -158,7 +160,7 @@ func (s FileStore) Save(ctx context.Context, domain string, resource Resource) ( return s.save(ctx, domain, "", resource) } -// SaveForType 按证书类型保存当前证书和历史版本。 +// SaveForType 按证书类型保存唯一的当前证书版本。 func (s FileStore) SaveForType(ctx context.Context, domain, certificateType string, resource Resource) (SavedResource, error) { return s.save(ctx, domain, certificateType, resource) } @@ -183,59 +185,66 @@ func (s FileStore) save(ctx context.Context, domain, certificateType string, res return SavedResource{}, errors.New("证书存储根目录不能为空") } baseDirectory := filepath.Join(root, directoryName(primary)) + typeDirectory := baseDirectory directory := baseDirectory + certificateIdentifier := "" if certificateType != "" { certificateType = strings.ToLower(strings.TrimSpace(certificateType)) if certificateType != "single" && certificateType != "wildcard" && certificateType != "san" { return SavedResource{}, fmt.Errorf("证书类型无效:%s", certificateType) } - directory = filepath.Join(baseDirectory, certificateType) + typeDirectory = filepath.Join(baseDirectory, certificateType) + directory = typeDirectory + if certificateType == "san" { + certificateIdentifier = sanCertificateIdentifier(resource.Domains) + directory = filepath.Join(typeDirectory, certificateIdentifier) + } } + activeDirectory := directory currentDirectory := directory + version := "" if certificateType != "" { - currentDirectory = filepath.Join(directory, "current") + activeDirectory, err = s.activeCertificateDirectoryForType(typeDirectory, certificateType) + if err != nil { + return SavedResource{}, err + } + if !directoryContainsCertificateFiles(activeDirectory) { + activeDirectory = "" + } + now := time.Now().UTC() + if s.Now != nil { + now = s.Now().UTC() + } + version, err = nextCertificateVersion(directory, now) + if err != nil { + return SavedResource{}, err + } + currentDirectory = filepath.Join(directory, version) + } + backupDirectory := "" + if activeDirectory != "" { + backupDirectory, err = s.backupExisting(activeDirectory, primary) + if err != nil { + return SavedResource{}, err + } } if err := os.MkdirAll(currentDirectory, 0o700); err != nil { return SavedResource{}, fmt.Errorf("创建证书目录失败:%w", err) } - backupDirectory, err := s.backupExisting(currentDirectory, primary) - if err != nil { - return SavedResource{}, err - } fullChain := resource.Certificate if len(resource.IssuerCertificate) > 0 && !bytes.Contains(resource.Certificate, resource.IssuerCertificate) { fullChain = append(append([]byte(nil), resource.Certificate...), resource.IssuerCertificate...) } - version := "" - if certificateType != "" { - now := time.Now - if s.Now != nil { - now = s.Now - } - version = now().UTC().Format("20060102-150405.000000000") - versionDirectory := filepath.Join(directory, "versions", version) - for suffix := 1; ; suffix++ { - if _, statErr := os.Stat(versionDirectory); errors.Is(statErr, os.ErrNotExist) { - break - } else if statErr != nil { - return SavedResource{}, fmt.Errorf("读取证书版本目录失败:%w", statErr) - } - version = fmt.Sprintf("%s-%02d", now().UTC().Format("20060102-150405.000000000"), suffix) - versionDirectory = filepath.Join(directory, "versions", version) - } - if err := os.MkdirAll(versionDirectory, 0o700); err != nil { - return SavedResource{}, fmt.Errorf("创建证书版本目录失败:%w", err) - } - if err := writeCertificateFiles(versionDirectory, resource.Certificate, fullChain, resource.PrivateKey); err != nil { - return SavedResource{}, err - } - } if err := writeCertificateFiles(currentDirectory, resource.Certificate, fullChain, resource.PrivateKey); err != nil { + if certificateType != "" { + _ = os.RemoveAll(currentDirectory) + } return SavedResource{}, err } leaf, _ := parseLeafCertificate(resource.Certificate) result := SavedResource{ - Domain: primary, CertificateType: certificateType, Version: version, SANs: append([]string(nil), resource.Domains...), + Domain: primary, CertificateType: certificateType, CertificateIdentifier: certificateIdentifier, + Version: version, SANs: append([]string(nil), resource.Domains...), Directory: currentDirectory, CertificatePath: filepath.Join(currentDirectory, "cert.pem"), FullChainPath: filepath.Join(currentDirectory, "fullchain.pem"), PrivateKeyPath: filepath.Join(currentDirectory, "key.pem"), NotBefore: resource.NotBefore, NotAfter: resource.NotAfter, BackupDirectory: backupDirectory, @@ -247,15 +256,20 @@ func (s FileStore) save(ctx context.Context, domain, certificateType string, res } metadata, err := json.MarshalIndent(result, "", " ") if err != nil { + if certificateType != "" { + _ = os.RemoveAll(currentDirectory) + } return SavedResource{}, fmt.Errorf("生成证书元数据失败:%w", err) } if err := atomicWrite(filepath.Join(currentDirectory, "metadata.json"), metadata, 0o600); err != nil { + if certificateType != "" { + _ = os.RemoveAll(currentDirectory) + } return SavedResource{}, fmt.Errorf("写入证书元数据失败:%w", err) } - if certificateType != "" { - versionMetadata := filepath.Join(directory, "versions", version, "metadata.json") - if err := atomicWrite(versionMetadata, metadata, 0o600); err != nil { - return SavedResource{}, fmt.Errorf("写入历史证书元数据失败:%w", err) + if certificateType != "" && activeDirectory != "" && activeDirectory != currentDirectory { + if err := removeCertificateDirectory(activeDirectory, typeDirectory); err != nil { + return SavedResource{}, fmt.Errorf("清理旧当前证书目录失败:%w", err) } } return result, nil @@ -309,7 +323,16 @@ func (s FileStore) backupExisting(directory, domain string) (string, error) { if s.Now != nil { now = s.Now } - backupDirectory := filepath.Join(backupRoot, directoryName(domain), now().UTC().Format("20060102-150405.000000000")) + backupBase := filepath.Join(backupRoot, directoryName(domain), now().UTC().Format("20060102-150405.000000000")) + backupDirectory := backupBase + for suffix := 1; ; suffix++ { + if _, statErr := os.Stat(backupDirectory); errors.Is(statErr, os.ErrNotExist) { + break + } else if statErr != nil { + return "", fmt.Errorf("读取证书备份目录失败:%w", statErr) + } + backupDirectory = fmt.Sprintf("%s-%02d", backupBase, suffix) + } if err := os.MkdirAll(filepath.Dir(backupDirectory), 0o700); err != nil { return "", fmt.Errorf("创建证书备份目录失败:%w", err) } @@ -395,6 +418,200 @@ func directoryName(domain string) string { return name } +func nextCertificateVersion(directory string, now time.Time) (string, error) { + date := now.UTC().Format("20060102") + major := 1 + minor := -1 + entries, err := os.ReadDir(directory) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return "", fmt.Errorf("读取证书类型目录失败:%w", err) + } + for _, entry := range entries { + if !entry.IsDir() { + continue + } + entryDate, entryMajor, entryMinor, valid := parseCertificateVersion(entry.Name()) + if !valid || entryDate != date { + continue + } + if entryMajor > major || entryMajor == major && entryMinor > minor { + major = entryMajor + minor = entryMinor + } + } + if minor < 0 { + minor = 0 + } else { + minor++ + } + return fmt.Sprintf("%s-V%d.%d", date, major, minor), nil +} + +func parseCertificateVersion(version string) (string, int, int, bool) { + if len(version) < len("20060102-V1.0") || filepath.Base(version) != version || strings.ContainsAny(version, `/\\`) { + return "", 0, 0, false + } + if version[8:10] != "-V" { + return "", 0, 0, false + } + date := version[:8] + for _, r := range date { + if r < '0' || r > '9' { + return "", 0, 0, false + } + } + parts := strings.Split(version[10:], ".") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", 0, 0, false + } + major, err := strconv.Atoi(parts[0]) + if err != nil || major < 1 { + return "", 0, 0, false + } + minor, err := strconv.Atoi(parts[1]) + if err != nil || minor < 0 { + return "", 0, 0, false + } + return date, major, minor, true +} + +func (s FileStore) activeCertificateDirectory(directory string) (string, error) { + entries, err := os.ReadDir(directory) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return directory, nil + } + return "", fmt.Errorf("读取证书类型目录失败:%w", err) + } + active := "" + for _, entry := range entries { + if !entry.IsDir() { + continue + } + candidate := filepath.Join(directory, entry.Name()) + if _, _, _, valid := parseCertificateVersion(entry.Name()); valid && newerCertificateDirectory(candidate, active) { + active = candidate + } + } + if active != "" { + return active, nil + } + legacyCurrent := filepath.Join(directory, "current") + if info, statErr := os.Stat(legacyCurrent); statErr == nil && info.IsDir() { + return legacyCurrent, nil + } else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) { + return "", fmt.Errorf("读取旧版当前证书目录失败:%w", statErr) + } + return directory, nil +} + +func sanCertificateIdentifier(domains []string) string { + sum := sha256.Sum256([]byte(strings.Join(domains, "\n"))) + return fmt.Sprintf("san-%x", sum[:8]) +} + +func directoryContainsCertificateFiles(directory string) bool { + if strings.TrimSpace(directory) == "" { + return false + } + for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} { + if info, err := os.Stat(filepath.Join(directory, name)); err == nil && !info.IsDir() { + return true + } + } + return false +} + +func newerCertificateDirectory(candidate, current string) bool { + if current == "" { + return true + } + candidateDate, candidateMajor, candidateMinor, candidateValid := parseCertificateVersion(filepath.Base(candidate)) + currentDate, currentMajor, currentMinor, currentValid := parseCertificateVersion(filepath.Base(current)) + if !candidateValid { + return false + } + if !currentValid { + return true + } + if candidateDate != currentDate { + return candidateDate > currentDate + } + if candidateMajor != currentMajor { + return candidateMajor > currentMajor + } + if candidateMinor != currentMinor { + return candidateMinor > currentMinor + } + return candidate > current +} + +func (s FileStore) activeCertificateDirectoryForType(typeDirectory, certificateType string) (string, error) { + active, err := s.activeCertificateDirectory(typeDirectory) + if err != nil { + return "", err + } + if certificateType != "san" || directoryContainsCertificateFiles(active) { + return active, nil + } + entries, err := os.ReadDir(typeDirectory) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return typeDirectory, nil + } + return "", err + } + for _, entry := range entries { + if !entry.IsDir() || entry.Name() == "current" { + continue + } + if !strings.HasPrefix(entry.Name(), "san-") { + continue + } + if _, _, _, valid := parseCertificateVersion(entry.Name()); valid { + continue + } + candidate, candidateErr := s.activeCertificateDirectory(filepath.Join(typeDirectory, entry.Name())) + if candidateErr != nil { + return "", candidateErr + } + if directoryContainsCertificateFiles(candidate) && newerCertificateDirectory(candidate, active) { + active = candidate + } + } + return active, nil +} +func removeCertificateDirectory(directory, certificateTypeDirectory string) error { + directory = filepath.Clean(directory) + certificateTypeDirectory = filepath.Clean(certificateTypeDirectory) + parentDirectory := filepath.Dir(directory) + if parentDirectory != certificateTypeDirectory && filepath.Dir(parentDirectory) != certificateTypeDirectory { + return errors.New("旧证书目录超出证书类型目录") + } + name := filepath.Base(directory) + if name != "current" { + if err := validateCertificateVersion(name); err != nil { + return err + } + } + if err := os.RemoveAll(directory); err != nil { + return err + } + if parentDirectory != certificateTypeDirectory { + entries, err := os.ReadDir(parentDirectory) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil + } + return err + } + if len(entries) == 0 { + return os.Remove(parentDirectory) + } + } + return nil +} + func validDomain(value string) bool { value = strings.TrimPrefix(value, "*.") if len(value) < 3 || len(value) > 253 || !strings.Contains(value, ".") { @@ -413,7 +630,7 @@ func validDomain(value string) bool { return true } -// CurrentDirectory returns the active certificate directory for a domain and certificate type. +// CurrentDirectory 返回当前唯一使用的证书版本目录。 func (s FileStore) CurrentDirectory(domain, certificateType string) (string, error) { primary := strings.TrimSpace(domain) if _, err := NormalizeDomains([]string{primary}); err != nil { @@ -427,7 +644,8 @@ func (s FileStore) CurrentDirectory(domain, certificateType string) (string, err if root == "." || root == "" { return "", errors.New("证书存储根目录不能为空") } - return filepath.Join(root, directoryName(primary), certificateType, "current"), nil + directory := filepath.Join(root, directoryName(primary), certificateType) + return s.activeCertificateDirectoryForType(directory, certificateType) } // LoadCurrent reads the active certificate files and metadata. @@ -485,41 +703,113 @@ func (s FileStore) LoadCurrent(ctx context.Context, domain, certificateType stri return saved, resource, nil } -// ListVersions returns all stored certificate versions in descending order. +// LoadVersion 仅允许读取当前使用的版本,保留该方法用于兼容已有接口。 +func (s FileStore) LoadVersion(ctx context.Context, domain, certificateType, version string) (SavedResource, Resource, error) { + if err := ctx.Err(); err != nil { + return SavedResource{}, Resource{}, err + } + if err := validateCertificateVersion(version); err != nil { + return SavedResource{}, Resource{}, err + } + directory, err := s.CurrentDirectory(domain, certificateType) + if err != nil { + return SavedResource{}, Resource{}, err + } + if filepath.Base(directory) != version { + return SavedResource{}, Resource{}, errors.New("指定版本不是当前使用的证书版本") + } + certificateData, err := os.ReadFile(filepath.Join(directory, "cert.pem")) + if err != nil { + return SavedResource{}, Resource{}, fmt.Errorf("读取当前证书失败:%w", err) + } + fullChainData, err := os.ReadFile(filepath.Join(directory, "fullchain.pem")) + if err != nil { + return SavedResource{}, Resource{}, fmt.Errorf("读取当前完整证书链失败:%w", err) + } + privateKeyData, err := os.ReadFile(filepath.Join(directory, "key.pem")) + if err != nil { + return SavedResource{}, Resource{}, fmt.Errorf("读取当前私钥失败:%w", err) + } + var saved SavedResource + metadata, err := os.ReadFile(filepath.Join(directory, "metadata.json")) + if err != nil { + return SavedResource{}, Resource{}, fmt.Errorf("读取当前证书元数据失败:%w", err) + } + if err := json.Unmarshal(metadata, &saved); err != nil { + return SavedResource{}, Resource{}, fmt.Errorf("解析当前证书元数据失败:%w", err) + } + if saved.Version != version { + return SavedResource{}, Resource{}, errors.New("当前证书版本标识不一致") + } + domains := saved.SANs + if len(domains) == 0 { + domains = []string{domain} + } + resource, err := ValidateResourceForDomains(Resource{ + Domains: domains, + Certificate: certificateData, + IssuerCertificate: fullChainData, + PrivateKey: privateKeyData, + }, domains) + if err != nil { + return SavedResource{}, Resource{}, fmt.Errorf("当前证书校验失败:%w", err) + } + saved.Directory = directory + saved.CertificatePath = filepath.Join(directory, "cert.pem") + saved.FullChainPath = filepath.Join(directory, "fullchain.pem") + saved.PrivateKeyPath = filepath.Join(directory, "key.pem") + saved.BackupDirectory = "" + resource.IssuerCertificate = nil + return saved, resource, nil +} + +// RestoreVersion 已停用,正式证书目录只保留当前使用的版本。 +func (s FileStore) RestoreVersion(ctx context.Context, domain, certificateType, version string) (SavedResource, error) { + if err := ctx.Err(); err != nil { + return SavedResource{}, err + } + if err := validateCertificateVersion(version); err != nil { + return SavedResource{}, err + } + return SavedResource{}, errors.New("当前仅保留当前使用的证书版本,不支持历史版本恢复") +} + +// ListVersions 返回当前唯一使用的证书版本,保留该方法用于兼容已有接口。 func (s FileStore) ListVersions(ctx context.Context, domain, certificateType string) ([]SavedResource, error) { if err := ctx.Err(); err != nil { return nil, err } - current, err := s.CurrentDirectory(domain, certificateType) + directory, err := s.CurrentDirectory(domain, certificateType) if err != nil { return nil, err } - certificateDirectory := filepath.Dir(current) - versionsDirectory := filepath.Join(certificateDirectory, "versions") - entries, err := os.ReadDir(versionsDirectory) - if err != nil { - if errors.Is(err, os.ErrNotExist) { + if _, statErr := os.Stat(filepath.Join(directory, "metadata.json")); statErr != nil { + if errors.Is(statErr, os.ErrNotExist) { return []SavedResource{}, nil } - return nil, fmt.Errorf("读取证书版本失败:%w", err) + return nil, fmt.Errorf("读取当前证书版本失败:%w", statErr) } - versions := make([]SavedResource, 0, len(entries)) - for _, entry := range entries { - if !entry.IsDir() { - continue - } - metadata, readErr := os.ReadFile(filepath.Join(versionsDirectory, entry.Name(), "metadata.json")) - if readErr != nil { - return nil, fmt.Errorf("读取证书版本元数据失败:%w", readErr) - } - var item SavedResource - if err := json.Unmarshal(metadata, &item); err != nil { - return nil, fmt.Errorf("解析证书版本元数据失败:%w", err) - } - versions = append(versions, item) + saved, _, err := s.LoadCurrent(ctx, domain, certificateType) + if err != nil { + return nil, err } - sort.SliceStable(versions, func(i, j int) bool { return versions[i].Version > versions[j].Version }) - return versions, nil + return []SavedResource{saved}, nil +} + +func validateCertificateVersion(version string) error { + if _, _, _, valid := parseCertificateVersion(version); !valid { + return errors.New("证书版本标识无效,应使用 YYYYMMDD-Vx.x 格式") + } + return nil +} + +func removeCertificateFiles(directory string) error { + for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} { + if err := os.Remove(filepath.Join(directory, name)); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + return nil } // RollbackSavedResource 在初始化后续阶段失败时恢复证书目录。 @@ -543,6 +833,9 @@ func RollbackSavedResource(ctx context.Context, saved SavedResource) error { if err := restoreCertificateFiles(directory, backupDirectory); err != nil { return fmt.Errorf("恢复原证书失败:%w", err) } + if err := rewriteRestoredMetadata(directory); err != nil { + return fmt.Errorf("更新回滚证书元数据失败:%w", err) + } return nil } for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} { @@ -551,6 +844,11 @@ func RollbackSavedResource(ctx context.Context, saved SavedResource) error { return fmt.Errorf("清理失败证书文件 %s 失败:%w", name, err) } } + if _, _, _, valid := parseCertificateVersion(filepath.Base(directory)); valid { + if err := os.Remove(directory); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("清理失败证书目录失败:%w", err) + } + } return nil } @@ -577,3 +875,25 @@ func restoreCertificateFiles(directory, backupDirectory string) error { } return nil } + +func rewriteRestoredMetadata(directory string) error { + path := filepath.Join(directory, "metadata.json") + data, err := os.ReadFile(path) + if err != nil { + return err + } + var saved SavedResource + if err := json.Unmarshal(data, &saved); err != nil { + return err + } + saved.Directory = directory + saved.CertificatePath = filepath.Join(directory, "cert.pem") + saved.FullChainPath = filepath.Join(directory, "fullchain.pem") + saved.PrivateKeyPath = filepath.Join(directory, "key.pem") + saved.BackupDirectory = "" + data, err = json.MarshalIndent(saved, "", " ") + if err != nil { + return err + } + return atomicWrite(path, data, 0o600) +} diff --git a/backend/internal/certificate/lifecycle_version_test.go b/backend/internal/certificate/lifecycle_version_test.go index b6592ac..c4f6379 100644 --- a/backend/internal/certificate/lifecycle_version_test.go +++ b/backend/internal/certificate/lifecycle_version_test.go @@ -10,7 +10,7 @@ import ( "time" ) -func TestFileStoreVersionedLayoutAndHistory(t *testing.T) { +func TestFileStoreUsesSingleDatedCurrentVersion(t *testing.T) { root := t.TempDir() store := FileStore{ Root: filepath.Join(root, "ssl"), @@ -26,25 +26,28 @@ func TestFileStoreVersionedLayoutAndHistory(t *testing.T) { if err != nil { t.Fatalf("保存第二版证书失败:%v", err) } - if first.Version == second.Version { - t.Fatalf("重复保存不应覆盖历史版本:%q", first.Version) + if first.Version != "20260827-V1.0" || second.Version != "20260827-V1.1" { + t.Fatalf("证书版本命名错误:first=%q second=%q", first.Version, second.Version) } - wantCurrent := filepath.Join(root, "ssl", "example.com", "single", "current") + wantCurrent := filepath.Join(root, "ssl", "example.com", "single", second.Version) if second.Directory != wantCurrent { t.Fatalf("当前目录错误:got=%q want=%q", second.Directory, wantCurrent) } - for _, path := range []string{ - filepath.Join(wantCurrent, "cert.pem"), - filepath.Join(wantCurrent, "fullchain.pem"), - filepath.Join(wantCurrent, "key.pem"), - filepath.Join(wantCurrent, "metadata.json"), - filepath.Join(root, "ssl", "example.com", "single", "versions", first.Version, "metadata.json"), - filepath.Join(root, "ssl", "example.com", "single", "versions", second.Version, "metadata.json"), - } { - if _, err := os.Stat(path); err != nil { - t.Fatalf("证书文件不存在:%s:%v", path, err) + if _, err := os.Stat(first.Directory); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("旧当前版本目录仍存在:%v", err) + } + for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} { + if _, err := os.Stat(filepath.Join(wantCurrent, name)); err != nil { + t.Fatalf("当前证书文件不存在:%s:%v", name, err) } } + entries, err := os.ReadDir(filepath.Dir(wantCurrent)) + if err != nil { + t.Fatalf("读取证书类型目录失败:%v", err) + } + if len(entries) != 1 || entries[0].Name() != second.Version { + t.Fatalf("正式证书目录应只保留一个版本:%v", entries) + } if runtime.GOOS != "windows" { info, err := os.Stat(second.PrivateKeyPath) if err != nil { @@ -56,44 +59,47 @@ func TestFileStoreVersionedLayoutAndHistory(t *testing.T) { } versions, err := store.ListVersions(context.Background(), "example.com", "single") if err != nil { - t.Fatalf("读取证书版本失败:%v", err) + t.Fatalf("读取当前证书版本失败:%v", err) } - if len(versions) != 2 || versions[0].Version != second.Version || versions[1].Version != first.Version { - t.Fatalf("证书版本历史错误:%+v", versions) + if len(versions) != 1 || versions[0].Version != second.Version { + t.Fatalf("当前证书版本列表错误:%+v", versions) } metadata, loaded, err := store.LoadCurrent(context.Background(), "example.com", "single") if err != nil { t.Fatalf("读取当前证书失败:%v", err) } - if metadata.Version != second.Version || len(loaded.Certificate) == 0 || len(loaded.PrivateKey) == 0 { + if metadata.Version != second.Version || metadata.Directory != second.Directory || len(loaded.Certificate) == 0 || len(loaded.PrivateKey) == 0 { t.Fatalf("当前证书内容错误:metadata=%+v", metadata) } } -func TestFileStoreListVersionsReturnsEmptyWhenNoHistory(t *testing.T) { +func TestFileStoreListVersionsReturnsEmptyWhenNoCurrentCertificate(t *testing.T) { store := FileStore{Root: t.TempDir()} versions, err := store.ListVersions(context.Background(), "example.com", "san") if err != nil { - t.Fatalf("无版本记录时查询失败:%v", err) + t.Fatalf("无当前证书时查询失败:%v", err) } if versions == nil || len(versions) != 0 { - t.Fatalf("无版本记录时应返回空列表:%+v", versions) + t.Fatalf("无当前证书时应返回空列表:%+v", versions) } } -func TestRollbackSavedResourceRestoresPreviousCertificate(t *testing.T) { +func TestRollbackSavedResourceRestoresPreviousCertificateInCurrentDirectory(t *testing.T) { root := t.TempDir() store := FileStore{ Root: filepath.Join(root, "ssl"), BackupRoot: filepath.Join(root, "backups"), Now: func() time.Time { return time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC) }, } - resource := testResource(t, "example.com") - first, err := store.SaveForType(context.Background(), "example.com", "single", resource) + first, err := store.SaveForType(context.Background(), "example.com", "single", testResource(t, "example.com")) if err != nil { t.Fatalf("保存初始证书失败:%v", err) } - second, err := store.SaveForType(context.Background(), "example.com", "single", resource) + firstCertificate, err := os.ReadFile(first.CertificatePath) + if err != nil { + t.Fatalf("读取初始证书失败:%v", err) + } + second, err := store.SaveForType(context.Background(), "example.com", "single", testResource(t, "example.com")) if err != nil { t.Fatalf("保存新证书失败:%v", err) } @@ -103,11 +109,19 @@ func TestRollbackSavedResourceRestoresPreviousCertificate(t *testing.T) { if err := RollbackSavedResource(context.Background(), second); err != nil { t.Fatalf("回滚证书失败:%v", err) } - if _, err := os.Stat(first.FullChainPath); err != nil { + currentCertificate, err := os.ReadFile(second.CertificatePath) + if err != nil { t.Fatalf("回滚后当前证书不存在:%v", err) } - if _, err := os.Stat(second.PrivateKeyPath); err != nil { - t.Fatalf("回滚后当前私钥不存在:%v", err) + if string(currentCertificate) != string(firstCertificate) { + t.Fatal("回滚后当前证书内容不匹配") + } + current, _, err := store.LoadCurrent(context.Background(), "example.com", "single") + if err != nil { + t.Fatalf("读取回滚后的当前证书失败:%v", err) + } + if current.Version != first.Version || current.Directory != second.Directory { + t.Fatalf("回滚后的当前元数据错误:%+v", current) } } @@ -124,9 +138,62 @@ func TestRollbackSavedResourceClearsNewCertificateFiles(t *testing.T) { if err := RollbackSavedResource(context.Background(), saved); err != nil { t.Fatalf("清理失败证书失败:%v", err) } - for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} { - if _, err := os.Stat(filepath.Join(saved.Directory, name)); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("回滚后文件仍存在:%s,错误:%v", name, err) - } + if _, err := os.Stat(saved.Directory); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("回滚后当前版本目录仍存在:%v", err) + } +} + +func TestFileStoreDoesNotRestoreHistoricalVersion(t *testing.T) { + store := FileStore{Root: t.TempDir()} + if _, err := store.RestoreVersion(context.Background(), "example.com", "single", "20260830-V1.0"); err == nil { + t.Fatal("仅保留当前版本时不应支持历史版本恢复") + } +} + +func TestFileStoreUsesStableSANIdentifierAndRemovesPreviousIdentifier(t *testing.T) { + root := t.TempDir() + store := FileStore{ + Root: filepath.Join(root, "ssl"), + BackupRoot: filepath.Join(root, "backups"), + Now: func() time.Time { return time.Date(2026, 8, 30, 12, 0, 0, 0, time.UTC) }, + } + firstResource := testResource(t, "example.com") + firstResource.Domains = []string{"example.com", "www.example.com"} + first, err := store.SaveForType(context.Background(), "example.com", "san", firstResource) + if err != nil { + t.Fatalf("save first SAN certificate: %v", err) + } + if first.CertificateIdentifier == "" { + t.Fatal("SAN certificate identifier should be stored") + } + if first.Version != "20260830-V1.0" { + t.Fatalf("unexpected first SAN version: %s", first.Version) + } + wantFirst := filepath.Join(root, "ssl", "example.com", "san", first.CertificateIdentifier, first.Version) + if first.Directory != wantFirst { + t.Fatalf("unexpected first SAN directory: got=%q want=%q", first.Directory, wantFirst) + } + + secondResource := firstResource + secondResource.Domains = []string{"api.example.com", "example.com"} + second, err := store.SaveForType(context.Background(), "example.com", "san", secondResource) + if err != nil { + t.Fatalf("save second SAN certificate: %v", err) + } + if second.CertificateIdentifier == first.CertificateIdentifier { + t.Fatal("different SAN sets should use different identifiers") + } + if second.Version != "20260830-V1.0" { + t.Fatalf("unexpected second SAN version: %s", second.Version) + } + if _, err := os.Stat(first.Directory); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("previous SAN certificate directory still exists: %v", err) + } + entries, err := os.ReadDir(filepath.Join(root, "ssl", "example.com", "san")) + if err != nil { + t.Fatalf("read SAN directory: %v", err) + } + if len(entries) != 1 || entries[0].Name() != second.CertificateIdentifier { + t.Fatalf("SAN directory should keep only the active identifier: %v", entries) } } diff --git a/backend/internal/certificate/service.go b/backend/internal/certificate/service.go index 7f2666d..6ef5db2 100644 --- a/backend/internal/certificate/service.go +++ b/backend/internal/certificate/service.go @@ -386,3 +386,41 @@ func (s *Service) ListVersions(ctx context.Context, domainID string) ([]SavedRes } return s.store.ListVersions(ctx, item.Name, string(item.CertificateType)) } + +// RestoreVersion 将指定历史版本恢复为当前证书,并更新域名证书状态。 +func (s *Service) RestoreVersion(ctx context.Context, domainID, version string) (IssueResult, error) { + if s == nil || s.repository == nil { + return IssueResult{}, errors.New("证书服务未初始化") + } + item, err := s.repository.GetByID(ctx, strings.TrimSpace(domainID)) + if err != nil { + return IssueResult{}, fmt.Errorf("读取域名配置失败:%w", err) + } + domains, err := requestedDomains(item) + if err != nil { + return IssueResult{}, err + } + _, resource, err := s.store.LoadVersion(ctx, item.Name, string(item.CertificateType), strings.TrimSpace(version)) + if err != nil { + return IssueResult{}, err + } + if _, err := ValidateResourceForDomains(resource, domains); err != nil { + return IssueResult{}, fmt.Errorf("历史证书不匹配当前域名配置:%w", err) + } + saved, err := s.store.RestoreVersion(ctx, item.Name, string(item.CertificateType), strings.TrimSpace(version)) + if err != nil { + return IssueResult{}, err + } + if _, err := ValidateResourceForDomains(resource, domains); err != nil { + return IssueResult{}, fmt.Errorf("恢复后证书校验失败:%w", err) + } + if err := s.repository.UpdateCertificateState(ctx, item.ID, "valid", &saved.NotAfter); err != nil { + rollbackErr := RollbackSavedResource(context.Background(), saved) + if rollbackErr != nil { + return IssueResult{}, errors.Join(err, rollbackErr) + } + return IssueResult{}, fmt.Errorf("certificate state update failed after restore: %w", err) + } + saved.SANs = append([]string(nil), domains...) + return IssueResult{DomainID: item.ID, Domains: domains, Saved: saved}, nil +} diff --git a/backend/internal/certificate/service_test.go b/backend/internal/certificate/service_test.go index ef708ad..2f7666c 100644 --- a/backend/internal/certificate/service_test.go +++ b/backend/internal/certificate/service_test.go @@ -22,8 +22,9 @@ import ( ) type serviceRepository struct { - item domain.Domain - states []string + item domain.Domain + states []string + updateErr error } func (r *serviceRepository) GetByID(_ context.Context, _ string) (domain.Domain, error) { @@ -31,6 +32,9 @@ func (r *serviceRepository) GetByID(_ context.Context, _ string) (domain.Domain, } func (r *serviceRepository) UpdateCertificateState(_ context.Context, _ string, status string, expiresAt *time.Time) error { + if status == "valid" && r.updateErr != nil { + return r.updateErr + } r.states = append(r.states, status) r.item.Status = status r.item.ExpiresAt = expiresAt @@ -212,6 +216,55 @@ func TestServiceRejectsOwnedCertificateForWrongDomain(t *testing.T) { } } +func TestServiceRestoreVersionRollsBackFilesWhenStateUpdateFails(t *testing.T) { + root := t.TempDir() + cfg := certificateTestConfig(root) + item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSingle, nil, true, domain.ACMEEnvironmentStaging, "cloudflare") + if err != nil { + t.Fatal(err) + } + store := FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup} + first, err := store.SaveForType(context.Background(), item.Name, "single", testResource(t, "example.com")) + if err != nil { + t.Fatal(err) + } + second, err := store.SaveForType(context.Background(), item.Name, "single", testResource(t, "example.com")) + if err != nil { + t.Fatal(err) + } + beforeCertificate, err := os.ReadFile(second.CertificatePath) + if err != nil { + t.Fatal(err) + } + beforeKey, err := os.ReadFile(second.PrivateKeyPath) + if err != nil { + t.Fatal(err) + } + repository := &serviceRepository{item: item, updateErr: errors.New("simulated state update failure")} + service := NewService(cfg, repository, nil, nil, nil) + if _, err := service.RestoreVersion(context.Background(), item.ID, first.Version); err == nil { + t.Fatal("state update failure should be returned") + } + afterCertificate, err := os.ReadFile(second.CertificatePath) + if err != nil { + t.Fatal(err) + } + afterKey, err := os.ReadFile(second.PrivateKeyPath) + if err != nil { + t.Fatal(err) + } + if string(afterCertificate) != string(beforeCertificate) || string(afterKey) != string(beforeKey) { + t.Fatal("certificate files were not rolled back after state update failure") + } + current, _, err := store.LoadCurrent(context.Background(), item.Name, string(item.CertificateType)) + if err != nil { + t.Fatal(err) + } + if current.Version != second.Version { + t.Fatalf("current metadata was not rolled back: got=%s want=%s", current.Version, second.Version) + } +} + func certificateTestConfig(root string) config.Config { cfg := config.Default(root) cfg.Paths.Certificate = filepath.Join(root, "ssl") @@ -261,7 +314,7 @@ func TestServiceIssuesSetupCertificateWithTypedLayout(t *testing.T) { if err != nil { t.Fatalf("申请初始化证书失败:%v", err) } - wantDirectory := filepath.Join(cfg.Paths.Certificate, "scert.example.com", "single", "current") + wantDirectory := filepath.Join(cfg.Paths.Certificate, "scert.example.com", "single", saved.Version) if saved.Directory != wantDirectory { t.Fatalf("初始化证书目录错误:got=%q want=%q", saved.Directory, wantDirectory) } diff --git a/backend/internal/cli/operations.go b/backend/internal/cli/operations.go index 6d8fd4c..f3b6888 100644 --- a/backend/internal/cli/operations.go +++ b/backend/internal/cli/operations.go @@ -16,8 +16,8 @@ import ( "github.com/spf13/cobra" "git.pcux.cn/xuans/Scert/backend/internal/app" - "git.pcux.cn/xuans/Scert/backend/internal/config" + "git.pcux.cn/xuans/Scert/backend/internal/secretstore" ) func newCertificateCommand() *cobra.Command { @@ -203,7 +203,7 @@ func newLogsCommand() *cobra.Command { func newConfigCommand() *cobra.Command { command := &cobra.Command{Use: "config", Short: "查看和修改服务配置"} - command.AddCommand(newConfigShowCommand(), newConfigSetCommand(), newConfigValidateCommand()) + command.AddCommand(newConfigShowCommand(), newConfigSetCommand(), newConfigSetSecretCommand(), newConfigValidateCommand()) return command } @@ -221,6 +221,60 @@ func newConfigShowCommand() *cobra.Command { } } +func newConfigSetSecretCommand() *cobra.Command { + var key, value string + command := &cobra.Command{ + Use: "set-secret", + Short: "安全更新 SMTP 敏感凭据", + RunE: func(cmd *cobra.Command, args []string) error { + if key != "notification.smtp_password" { + return fmt.Errorf("不支持更新的敏感配置项:%s", key) + } + if value == "" { + var err error + value, err = ask(bufio.NewReader(cmd.InOrStdin()), cmd.OutOrStdout(), "请输入新的 SMTP 密码或授权码", "") + if err != nil { + return err + } + } + if value == "" { + return errors.New("SMTP 密码不能为空") + } + cfg, err := loadConfig() + if err != nil { + return err + } + username := strings.TrimSpace(cfg.Notification.SMTPUsername) + if username == "" { + return errors.New("填写 SMTP 密码前必须配置 SMTP 用户名") + } + store, err := secretstore.Open(cfg.Paths.Config) + if err != nil { + return fmt.Errorf("初始化 SMTP 凭据存储失败:%w", err) + } + ref, err := newSMTPCredentialReference() + if err != nil { + return err + } + if err := store.Put(cmd.Context(), ref, map[string]string{"username": username, "password": value}); err != nil { + return fmt.Errorf("保存 SMTP 凭据失败:%w", err) + } + cfg.Notification.SMTPCredentialRef = ref + if err := cfg.Save(resolveConfigPath()); err != nil { + cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cleanupCancel() + _ = store.Delete(cleanupContext, ref) + return err + } + _, err = fmt.Fprintln(cmd.OutOrStdout(), "SMTP 凭据已加密更新。") + return err + }, + } + command.Flags().StringVar(&key, "key", "", "敏感配置项名称") + command.Flags().StringVar(&value, "value", "", "SMTP 密码;留空时交互输入") + _ = command.MarkFlagRequired("key") + return command +} func newConfigValidateCommand() *cobra.Command { return &cobra.Command{ Use: "validate", @@ -551,6 +605,27 @@ func setConfigValue(cfg *config.Config, key, value string) error { return fmt.Errorf("SMTP 通知开关格式无效:%w", err) } cfg.Notification.SMTPEnabled = parsed + + case "notification.smtp_host": + cfg.Notification.SMTPHost = value + case "notification.smtp_port": + parsed, err := parseInt() + if err != nil { + return fmt.Errorf("SMTP 端口格式无效:%w", err) + } + cfg.Notification.SMTPPort = parsed + case "notification.smtp_username": + cfg.Notification.SMTPUsername = value + case "notification.smtp_mode": + cfg.Notification.SMTPMode = value + case "notification.smtp_allow_plaintext_auth": + parsed, err := parseBool() + if err != nil { + return fmt.Errorf("SMTP 明文认证开关格式无效:%w", err) + } + cfg.Notification.SMTPAllowPlaintextAuth = parsed + case "notification.smtp_password": + return errors.New("SMTP 密码属于敏感信息,请使用 scert config set-secret --key notification.smtp_password") case "notification.provider": cfg.Notification.Provider = value case "notification.endpoint": diff --git a/backend/internal/cli/root.go b/backend/internal/cli/root.go index 3079fc8..1984d29 100644 --- a/backend/internal/cli/root.go +++ b/backend/internal/cli/root.go @@ -3,6 +3,8 @@ package cli import ( "bufio" "context" + "crypto/rand" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -72,7 +74,7 @@ func newRootCommand() *cobra.Command { &cobra.Command{Use: "version", Short: "显示版本信息", Run: func(cmd *cobra.Command, args []string) { cmd.Printf("Scert %s\n", version) }}, newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(), newCertificateCommand(), newRenewCommand(), newDeployCommand(), newLogsCommand(), newConfigCommand(), newBackupCommand(), newRestoreCommand(), - newServerCommand(), newSSHKeyCommand(), + newServerCommand(), newSSHKeyCommand(), newServiceCommand(), ) localizeHelpFlags(root) return root @@ -117,11 +119,12 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command var ( adminUsername, adminEmail, adminPassword, emailProvider, emailEndpoint string emailHTTPPath, emailHTTPLoginPath, emailHTTPAuthMode, emailHTTPCredentialRef, emailHTTPHeaders string + emailSMTPHost, emailSMTPUsername, emailSMTPPassword, emailSMTPMode string emailEventMode, emailSenderName, emailSenderEmail, emailRetryIntervals string recipients, dnsProvider, dnsCredentialRef, certificateRoot string webHostname, webPublicIP, httpsMode string - serverPort, emailTimeoutSecs, emailRetryCount int - emailHTTPEnabled, emailIncludeDeploymentDetails bool + serverPort, emailTimeoutSecs, emailRetryCount, emailSMTPPort int + emailHTTPEnabled, emailSMTPEnabled, emailSMTPAllowPlaintextAuth, emailIncludeDeploymentDetails bool emailIncludeCertificateSerial, emailIncludeManagementURL bool dnsVerified, webEnabled bool ) @@ -143,8 +146,11 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command } input := setup.Input{ AdminUsername: adminUsername, AdminEmail: adminEmail, AdminPassword: adminPassword, ServerPort: serverPort, - EmailHTTPEnabled: emailHTTPEnabled, - EmailProvider: emailProvider, EmailEndpoint: emailEndpoint, + EmailHTTPEnabled: emailHTTPEnabled, EmailSMTPEnabled: emailSMTPEnabled, + EmailSMTPHost: emailSMTPHost, EmailSMTPPort: emailSMTPPort, EmailSMTPUsername: emailSMTPUsername, + EmailSMTPPassword: emailSMTPPassword, + EmailSMTPMode: emailSMTPMode, EmailSMTPAllowPlaintextAuth: emailSMTPAllowPlaintextAuth, + EmailProvider: emailProvider, EmailEndpoint: emailEndpoint, EmailHTTPPath: emailHTTPPath, EmailHTTPLoginPath: emailHTTPLoginPath, EmailHTTPAuthMode: emailHTTPAuthMode, EmailHTTPCredentialRef: emailHTTPCredentialRef, EmailHTTPHeaders: emailHeaders, EmailEventMode: emailEventMode, EmailIncludeDeploymentDetails: emailIncludeDeploymentDetails, @@ -161,10 +167,19 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command return err } } - cleanupSecret, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout()) + cleanupDNS, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout()) if err != nil { return err } + cleanupSMTP, err := prepareSMTPCredentials(cmd.Context(), cfg, &input) + if err != nil { + cleanupDNS() + return err + } + cleanupSecret := func() { + cleanupSMTP() + cleanupDNS() + } if err := setup.Apply(&cfg, input); err != nil { cleanupSecret() return err @@ -185,6 +200,13 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command command.Flags().StringVar(&adminPassword, "admin-password", "", "超级管理员密码(仅建议临时使用参数,优先交互输入)") command.Flags().IntVar(&serverPort, "server-port", 8080, "Scert 主服务端口") command.Flags().BoolVar(&emailHTTPEnabled, "email-http-enabled", false, "是否启用 HTTP 邮件通知") + command.Flags().BoolVar(&emailSMTPEnabled, "email-smtp-enabled", false, "是否启用 SMTP 邮件通知") + command.Flags().StringVar(&emailSMTPHost, "email-smtp-host", "", "SMTP 服务器主机") + command.Flags().IntVar(&emailSMTPPort, "email-smtp-port", 587, "SMTP 服务器端口") + command.Flags().StringVar(&emailSMTPUsername, "email-smtp-username", "", "SMTP 用户名") + command.Flags().StringVar(&emailSMTPPassword, "email-smtp-password", "", "SMTP 密码(仅建议临时使用参数,优先交互输入)") + command.Flags().StringVar(&emailSMTPMode, "email-smtp-mode", "starttls", "SMTP 连接模式:plain、starttls、implicit_tls") + command.Flags().BoolVar(&emailSMTPAllowPlaintextAuth, "email-smtp-allow-plaintext-auth", false, "是否允许 SMTP 明文连接认证") command.Flags().StringVar(&emailHTTPPath, "email-http-path", "/api/email/send", "HTTP 邮件通知请求路径") command.Flags().StringVar(&emailHTTPLoginPath, "email-http-login-path", "/api/login", "HTTP 会话认证登录请求路径") command.Flags().StringVar(&emailHTTPAuthMode, "email-http-auth-mode", "none", "HTTP 邮件通知认证方式:none、bearer、hmac_sha256、session") @@ -262,14 +284,52 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input, return err } value.ServerPort = port - value.EmailProvider, err = ask(reader, output, "第三方邮箱服务标识", "") + value.EmailHTTPEnabled, err = askYesNo(reader, output, "是否启用 HTTP 邮件通知?", false) if err != nil { return err } - value.EmailEndpoint, err = ask(reader, output, "第三方邮箱 API 地址", "") + if value.EmailHTTPEnabled { + value.EmailProvider, err = ask(reader, output, "第三方邮箱服务标识", "") + if err != nil { + return err + } + value.EmailEndpoint, err = ask(reader, output, "第三方邮箱 API 地址", "") + if err != nil { + return err + } + } + value.EmailSMTPEnabled, err = askYesNo(reader, output, "是否启用 SMTP 邮件通知?", false) if err != nil { return err } + if value.EmailSMTPEnabled { + value.EmailSMTPHost, err = ask(reader, output, "SMTP 服务器主机 *", "") + if err != nil { + return err + } + value.EmailSMTPPort, err = askInt(reader, output, "SMTP 服务器端口 *", 587) + if err != nil { + return err + } + value.EmailSMTPUsername, err = ask(reader, output, "SMTP 用户名 *", "") + if err != nil { + return err + } + value.EmailSMTPPassword, err = ask(reader, output, "SMTP 密码或授权码 *", "") + if err != nil { + return err + } + value.EmailSMTPMode, err = ask(reader, output, "SMTP 连接模式(plain/starttls/implicit_tls)", "starttls") + if err != nil { + return err + } + if value.EmailSMTPMode == "plain" { + value.EmailSMTPAllowPlaintextAuth, err = askYesNo(reader, output, "是否允许 SMTP 明文认证?", false) + if err != nil { + return err + } + } + } receiver, err := ask(reader, output, "通知收件人(逗号分隔)", "") if err != nil { return err @@ -328,6 +388,55 @@ func askDNSCredentials(reader *bufio.Reader, output io.Writer, providerID string return credentials, nil } +func prepareSMTPCredentials(ctx context.Context, cfg config.Config, input *setup.Input) (func(), error) { + if input == nil { + return func() {}, errors.New("初始化输入不能为空") + } + if !input.EmailSMTPEnabled { + return func() {}, nil + } + if strings.TrimSpace(input.EmailSMTPCredentialRef) != "" { + return func() {}, nil + } + if strings.TrimSpace(input.EmailSMTPUsername) == "" { + return func() {}, errors.New("启用 SMTP 通知后必须填写 SMTP 用户名") + } + if input.EmailSMTPPassword == "" { + return func() {}, errors.New("启用 SMTP 通知后必须填写 SMTP 密码") + } + if cfg.Paths.Config == "" { + return func() {}, errors.New("SMTP 敏感凭据存储目录不能为空") + } + store, err := secretstore.Open(cfg.Paths.Config) + if err != nil { + return func() {}, fmt.Errorf("初始化 SMTP 凭据存储失败:%w", err) + } + reference, err := newSMTPCredentialReference() + if err != nil { + return func() {}, err + } + if err := store.Put(ctx, reference, map[string]string{ + "username": strings.TrimSpace(input.EmailSMTPUsername), + "password": input.EmailSMTPPassword, + }); err != nil { + return func() {}, fmt.Errorf("保存 SMTP 凭据失败:%w", err) + } + input.EmailSMTPCredentialRef = reference + return func() { + cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cleanupCancel() + _ = store.Delete(cleanupContext, reference) + }, nil +} + +func newSMTPCredentialReference() (string, error) { + buffer := make([]byte, 18) + if _, err := rand.Read(buffer); err != nil { + return "", fmt.Errorf("生成 SMTP 凭据引用失败:%w", err) + } + return "secret://notification/smtp/" + hex.EncodeToString(buffer), nil +} + func prepareDNSCredentials(ctx context.Context, cfg config.Config, input *setup.Input, output io.Writer) (func(), error) { if input == nil { return func() {}, errors.New("初始化输入不能为空") diff --git a/backend/internal/cli/root_test.go b/backend/internal/cli/root_test.go index 8db6a71..f243149 100644 --- a/backend/internal/cli/root_test.go +++ b/backend/internal/cli/root_test.go @@ -187,7 +187,7 @@ func TestAskDNSProviderUsesNumberedSelection(t *testing.T) { func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) { var output bytes.Buffer - provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("4\n1\n")), &output) + provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("9\n1\n")), &output) if err != nil { t.Fatalf("DNS 服务商选择失败:%v", err) } @@ -198,6 +198,7 @@ func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) { t.Fatalf("选择未开放服务商时未给出提示:%s", output.String()) } } + func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) { baseDir := t.TempDir() blockedParent := filepath.Join(baseDir, "blocked") @@ -236,9 +237,9 @@ type cliFakeDNSCredentialTester struct { credentials map[string]string } -func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) error { +func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) (setup.DNSVerificationReport, error) { f.credentials = credentials - return nil + return setup.DNSVerificationReport{}, nil } func TestPrepareDNSCredentialsEncryptsAndClearsInput(t *testing.T) { diff --git a/backend/internal/cli/service.go b/backend/internal/cli/service.go new file mode 100644 index 0000000..8ff8d51 --- /dev/null +++ b/backend/internal/cli/service.go @@ -0,0 +1,102 @@ +package cli + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + "git.pcux.cn/xuans/Scert/backend/internal/servicehost" +) + +func newServiceCommand() *cobra.Command { + var name string + var displayName string + var description string + var executable string + var serviceConfig string + var workDir string + + command := &cobra.Command{ + Use: "service", + Short: "管理系统服务", + } + install := &cobra.Command{ + Use: "install", + Short: "注册 Scert 系统服务", + RunE: func(cmd *cobra.Command, _ []string) error { + executablePath, directory, configPath, err := servicePaths(executable, workDir, serviceConfig) + if err != nil { + return err + } + return servicehost.Install(cmd.Context(), servicehost.Options{ + Name: name, DisplayName: displayName, Description: description, + Executable: executablePath, ConfigPath: configPath, WorkDir: directory, + }) + }, + } + uninstall := &cobra.Command{ + Use: "uninstall", + Short: "取消注册 Scert 系统服务", + RunE: func(cmd *cobra.Command, _ []string) error { + return servicehost.Uninstall(cmd.Context(), name) + }, + } + start := &cobra.Command{ + Use: "start", + Short: "启动 Scert 系统服务", + RunE: func(cmd *cobra.Command, _ []string) error { + return servicehost.Start(cmd.Context(), name) + }, + } + stop := &cobra.Command{ + Use: "stop", + Short: "停止 Scert 系统服务", + RunE: func(cmd *cobra.Command, _ []string) error { + return servicehost.Stop(cmd.Context(), name) + }, + } + for _, child := range []*cobra.Command{install, uninstall, start, stop} { + command.AddCommand(child) + } + command.PersistentFlags().StringVar(&name, "name", "Scert", "系统服务名称") + install.Flags().StringVar(&displayName, "display-name", "Scert SSL 证书管理服务", "系统服务显示名称") + install.Flags().StringVar(&description, "description", "Scert SSL 证书管理服务", "系统服务描述") + install.Flags().StringVar(&executable, "executable", "", "服务程序路径,默认使用当前 scert 程序") + install.Flags().StringVar(&serviceConfig, "service-config", "", "服务配置文件路径,默认使用当前配置") + install.Flags().StringVar(&workDir, "work-dir", "", "服务工作目录,默认使用程序目录") + return command +} + +func servicePaths(executable, workDir, serviceConfig string) (string, string, string, error) { + if executable == "" { + current, err := os.Executable() + if err != nil { + return "", "", "", fmt.Errorf("读取当前程序路径失败:%w", err) + } + executable = current + } + executable, err := filepath.Abs(executable) + if err != nil { + return "", "", "", fmt.Errorf("解析服务程序路径失败:%w", err) + } + if workDir == "" { + workDir = filepath.Dir(executable) + } + workDir, err = filepath.Abs(workDir) + if err != nil { + return "", "", "", fmt.Errorf("解析服务工作目录失败:%w", err) + } + if serviceConfig == "" { + serviceConfig = resolveConfigPath() + } + serviceConfig, err = filepath.Abs(serviceConfig) + if err != nil { + return "", "", "", fmt.Errorf("解析服务配置路径失败:%w", err) + } + return executable, workDir, serviceConfig, nil +} + +var _ = context.Background diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 61040d3..82ba5b9 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -108,6 +108,12 @@ type NotificationConfig struct { TimeoutSecs int `json:"timeout_secs"` RetryCount int `json:"retry_count"` RetryIntervalsSecs []int `json:"retry_intervals_secs"` + SMTPHost string `json:"smtp_host"` + SMTPPort int `json:"smtp_port"` + SMTPUsername string `json:"smtp_username"` + SMTPCredentialRef string `json:"smtp_credential_ref"` + SMTPMode string `json:"smtp_mode"` + SMTPAllowPlaintextAuth bool `json:"smtp_allow_plaintext_auth"` } func Default(baseDir string) Config { @@ -141,6 +147,8 @@ func Default(baseDir string) Config { TimeoutSecs: 10, RetryCount: 3, RetryIntervalsSecs: []int{30, 120, 600}, + SMTPPort: 587, + SMTPMode: "starttls", }, } } @@ -250,6 +258,12 @@ func (c *Config) Normalize() { if c.Notification.HTTPHeaders == nil { c.Notification.HTTPHeaders = map[string]string{} } + if c.Notification.SMTPPort == 0 { + c.Notification.SMTPPort = 587 + } + if c.Notification.SMTPMode == "" { + c.Notification.SMTPMode = "starttls" + } } func (c Config) Save(path string) error { if err := c.Validate(); err != nil { @@ -391,6 +405,20 @@ func (c Config) Validate() error { if c.Notification.EventMode != "detailed" && c.Notification.EventMode != "unified" { return fmt.Errorf("通知事件模式无效:%s", c.Notification.EventMode) } + if c.Notification.SMTPMode != "plain" && c.Notification.SMTPMode != "starttls" && c.Notification.SMTPMode != "implicit_tls" { + return fmt.Errorf("\u0053\u004d\u0054\u0050 \u8fde\u63a5\u6a21\u5f0f\u65e0\u6548\uff1a%s", c.Notification.SMTPMode) + } + if c.Notification.SMTPEnabled { + if strings.TrimSpace(c.Notification.SMTPHost) == "" { + return fmt.Errorf("\u542f\u7528 SMTP \u901a\u77e5\u65f6\u5fc5\u987b\u914d\u7f6e SMTP \u4e3b\u673a") + } + if c.Notification.SMTPPort < 1 || c.Notification.SMTPPort > 65535 { + return fmt.Errorf("SMTP \u7aef\u53e3\u65e0\u6548\uff1a%d", c.Notification.SMTPPort) + } + if strings.TrimSpace(c.Notification.SMTPUsername) != "" && strings.TrimSpace(c.Notification.SMTPCredentialRef) == "" { + return fmt.Errorf("SMTP \u914d\u7f6e\u7528\u6237\u540d\u540e\u5fc5\u987b\u914d\u7f6e\u52a0\u5bc6\u51ed\u636e\u5f15\u7528") + } + } if strings.TrimSpace(c.Notification.HTTPPath) == "" || !strings.HasPrefix(strings.TrimSpace(c.Notification.HTTPPath), "/") { return fmt.Errorf("HTTP 通知请求路径必须以 / 开头") } diff --git a/backend/internal/dnsprovider/catalog.go b/backend/internal/dnsprovider/catalog.go index 9fa83e8..67103f7 100644 --- a/backend/internal/dnsprovider/catalog.go +++ b/backend/internal/dnsprovider/catalog.go @@ -65,10 +65,12 @@ var descriptors = map[string]Descriptor{ }, }, CNAME: { - ID: CNAME, Name: "CNAME 委派", Description: "需要先配置委派目标和目标 DNS 服务商,后续任务接入自动验证。", + ID: CNAME, Name: "CNAME 委派", Description: "使用已配置的 CNAME 将 DNS-01 挑战转发到专用验证域,并由目标 DNS 服务商创建和清理 TXT 记录。", + Available: true, CredentialFields: []CredentialField{ {Name: "delegated_domain", Label: "专用验证域", Required: true, Placeholder: "例如 acme.example.com"}, {Name: "delegated_provider", Label: "委派目标 DNS 服务商", Required: true}, + {Name: "delegated_credentials_json", Label: "委派凭据 JSON", Secret: true, Required: true, Placeholder: "例如 {\"api_token\":\"...\"}"}, }, }, HuaweiCloud: { diff --git a/backend/internal/dnsprovider/cname_provider.go b/backend/internal/dnsprovider/cname_provider.go new file mode 100644 index 0000000..ef0b07d --- /dev/null +++ b/backend/internal/dnsprovider/cname_provider.go @@ -0,0 +1,38 @@ +package dnsprovider + +import ( + "context" + "strings" + + "github.com/go-acme/lego/v5/challenge" +) + +// cnameDelegationProvider 将原始域名的 DNS-01 挑战转发到专用验证域。 +// 委派域上的 TXT 记录由目标 Provider 管理,原始域名上的 CNAME 记录由用户提前配置。 +type cnameDelegationProvider struct { + delegatedDomain string + target challenge.Provider +} + +func newCNAMEDelegationProvider(delegatedDomain string, target challenge.Provider) (challenge.Provider, error) { + delegatedDomain = normalizeProviderDomain(delegatedDomain) + if delegatedDomain == "" { + return nil, ErrInvalidDelegatedDomain + } + if target == nil { + return nil, ErrDelegatedProviderUnavailable + } + return &cnameDelegationProvider{delegatedDomain: delegatedDomain, target: target}, nil +} + +func (p *cnameDelegationProvider) Present(ctx context.Context, _ string, token, keyAuth string) error { + return p.target.Present(ctx, p.delegatedDomain, token, keyAuth) +} + +func (p *cnameDelegationProvider) CleanUp(ctx context.Context, _ string, token, keyAuth string) error { + return p.target.CleanUp(ctx, p.delegatedDomain, token, keyAuth) +} + +func normalizeProviderDomain(value string) string { + return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), ".")) +} diff --git a/backend/internal/dnsprovider/cname_provider_test.go b/backend/internal/dnsprovider/cname_provider_test.go new file mode 100644 index 0000000..a2ecbff --- /dev/null +++ b/backend/internal/dnsprovider/cname_provider_test.go @@ -0,0 +1,105 @@ +package dnsprovider + +import ( + "context" + "errors" + "testing" + + "github.com/go-acme/lego/v5/challenge" +) + +type delegationRecordingProvider struct { + presentDomain string + cleanupDomain string + presentToken string + cleanupToken string + presentErr error + cleanupErr error +} + +func (p *delegationRecordingProvider) Present(_ context.Context, domain, token, _ string) error { + p.presentDomain = domain + p.presentToken = token + return p.presentErr +} + +func (p *delegationRecordingProvider) CleanUp(_ context.Context, domain, token, _ string) error { + p.cleanupDomain = domain + p.cleanupToken = token + return p.cleanupErr +} + +var _ challenge.Provider = (*delegationRecordingProvider)(nil) + +func TestCNAMEDelegationProviderForwardsChallengeDomain(t *testing.T) { + target := &delegationRecordingProvider{} + provider, err := newCNAMEDelegationProvider(" ACME.Example.com. ", target) + if err != nil { + t.Fatalf("创建 CNAME 委派 Provider 失败:%v", err) + } + ctx := context.Background() + if err := provider.Present(ctx, "www.example.net", "token", "key-auth"); err != nil { + t.Fatalf("转发创建 TXT 记录失败:%v", err) + } + if target.presentDomain != "acme.example.com" || target.presentToken != "token" { + t.Fatalf("创建记录未转发到规范化委派域:domain=%q token=%q", target.presentDomain, target.presentToken) + } + if err := provider.CleanUp(ctx, "www.example.net", "token", "key-auth"); err != nil { + t.Fatalf("转发清理 TXT 记录失败:%v", err) + } + if target.cleanupDomain != "acme.example.com" || target.cleanupToken != "token" { + t.Fatalf("清理记录未转发到规范化委派域:domain=%q token=%q", target.cleanupDomain, target.cleanupToken) + } +} + +func TestCNAMEDelegationProviderPropagatesTargetErrors(t *testing.T) { + presentErr := errors.New("创建失败") + cleanupErr := errors.New("清理失败") + target := &delegationRecordingProvider{presentErr: presentErr, cleanupErr: cleanupErr} + provider, err := newCNAMEDelegationProvider("acme.example.com", target) + if err != nil { + t.Fatalf("创建 CNAME 委派 Provider 失败:%v", err) + } + if err := provider.Present(context.Background(), "example.com", "token", "key-auth"); !errors.Is(err, presentErr) { + t.Fatalf("创建错误未透传:%v", err) + } + if err := provider.CleanUp(context.Background(), "example.com", "token", "key-auth"); !errors.Is(err, cleanupErr) { + t.Fatalf("清理错误未透传:%v", err) + } +} + +func TestLegoFactoryCreatesCNAMEDelegationProvider(t *testing.T) { + provider, err := NewLegoFactory().Create(CNAME, map[string]string{ + "delegated_domain": "acme.example.com", + "delegated_provider": Cloudflare, + "delegated_credentials_json": `{"api_token":"test-token"}`, + }) + if err != nil { + t.Fatalf("创建 CNAME 委派 Provider 失败:%v", err) + } + if provider == nil { + t.Fatal("CNAME 委派 Provider 不应为空") + } +} + +func TestLegoFactoryRejectsRecursiveCNAMEDelegation(t *testing.T) { + _, err := NewLegoFactory().Create(CNAME, map[string]string{ + "delegated_domain": "acme.example.com", + "delegated_provider": CNAME, + "delegated_credentials_json": `{}`, + }) + if !errors.Is(err, ErrDelegatedProviderUnavailable) { + t.Fatalf("递归 CNAME 委派应被拒绝:%v", err) + } +} + +func TestLegoFactoryRejectsInvalidCNAMEDelegationCredentials(t *testing.T) { + _, err := NewLegoFactory().Create(CNAME, map[string]string{ + "delegated_domain": "acme.example.com", + "delegated_provider": Cloudflare, + "delegated_credentials_json": `[]`, + }) + if !errors.Is(err, ErrInvalidDelegatedCredentials) { + t.Fatalf("非对象 CNAME 凭据应被拒绝:%v", err) + } +} diff --git a/backend/internal/dnsprovider/errors.go b/backend/internal/dnsprovider/errors.go new file mode 100644 index 0000000..740d82f --- /dev/null +++ b/backend/internal/dnsprovider/errors.go @@ -0,0 +1,9 @@ +package dnsprovider + +import "errors" + +var ( + ErrInvalidDelegatedDomain = errors.New("CNAME 委派域名无效") + ErrInvalidDelegatedCredentials = errors.New("CNAME 委派凭据无效") + ErrDelegatedProviderUnavailable = errors.New("CNAME 委派目标 Provider 不可用") +) diff --git a/backend/internal/dnsprovider/lego_factory.go b/backend/internal/dnsprovider/lego_factory.go index f2d992e..6207995 100644 --- a/backend/internal/dnsprovider/lego_factory.go +++ b/backend/internal/dnsprovider/lego_factory.go @@ -15,6 +15,8 @@ import ( "github.com/go-acme/lego/v5/providers/dns/tencentcloud" "golang.org/x/oauth2/google" gdns "google.golang.org/api/dns/v1" + + "git.pcux.cn/xuans/Scert/backend/internal/domain" ) type LegoFactory struct{} @@ -37,6 +39,27 @@ func (LegoFactory) Create(providerID string, credentials map[string]string) (cha return nil, err } switch providerID { + case CNAME: + delegatedDomain := normalizeProviderDomain(cleaned["delegated_domain"]) + if delegatedDomain == "" || strings.HasPrefix(delegatedDomain, "*.") || !domain.IsValidName(delegatedDomain) { + return nil, ErrInvalidDelegatedDomain + } + delegatedProvider := strings.ToLower(strings.TrimSpace(cleaned["delegated_provider"])) + if delegatedProvider == CNAME || delegatedProvider == Other || delegatedProvider == "" { + return nil, fmt.Errorf("%w: %s", ErrDelegatedProviderUnavailable, delegatedProvider) + } + var delegatedCredentials map[string]string + if err := json.Unmarshal([]byte(cleaned["delegated_credentials_json"]), &delegatedCredentials); err != nil { + return nil, fmt.Errorf("%w: %v", ErrInvalidDelegatedCredentials, err) + } + if delegatedCredentials == nil { + return nil, ErrInvalidDelegatedCredentials + } + target, err := (LegoFactory{}).Create(delegatedProvider, delegatedCredentials) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrDelegatedProviderUnavailable, err) + } + return newCNAMEDelegationProvider(delegatedDomain, target) case Cloudflare: cfg := cloudflare.NewDefaultConfig() cfg.AuthToken = cleaned["api_token"] diff --git a/backend/internal/dnsprovider/tester.go b/backend/internal/dnsprovider/tester.go index e619693..19fd37f 100644 --- a/backend/internal/dnsprovider/tester.go +++ b/backend/internal/dnsprovider/tester.go @@ -7,55 +7,190 @@ import ( "errors" "fmt" "strings" + "time" "github.com/go-acme/lego/v5/challenge" + "github.com/go-acme/lego/v5/challenge/dns01" + "github.com/go-acme/lego/v5/challenge/dnspersist01" "git.pcux.cn/xuans/Scert/backend/internal/domain" + "git.pcux.cn/xuans/Scert/backend/internal/setup" ) type Factory interface { Create(providerID string, credentials map[string]string) (challenge.Provider, error) } -type Tester struct { - factory Factory +type TXTResolver interface { + LookupTXT(ctx context.Context, fqdn string) ([]string, error) } +type Tester struct { + factory Factory + resolver TXTResolver +} + +const dnsCleanupTimeout = 30 * time.Second + func NewTester(factory Factory) *Tester { - return &Tester{factory: factory} + return NewTesterWithResolver(factory, legoTXTResolver{}) } -func (t *Tester) Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) error { - if t == nil || t.factory == nil { - return errors.New("DNS 验证服务未初始化") +func NewTesterWithResolver(factory Factory, resolver TXTResolver) *Tester { + return &Tester{factory: factory, resolver: resolver} +} + +type VerificationError struct { + Report setup.DNSVerificationReport + Err error +} + +func (e *VerificationError) Error() string { + if e == nil || e.Err == nil { + return "DNS API 在线验证失败" + } + return e.Err.Error() +} + +func (e *VerificationError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + +func (t *Tester) Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) (setup.DNSVerificationReport, error) { + return t.VerifyWithReport(ctx, providerID, testDomain, credentials) +} + +func (t *Tester) VerifyWithReport(ctx context.Context, providerID, testDomain string, credentials map[string]string) (setup.DNSVerificationReport, error) { + report := setup.DNSVerificationReport{} + if t == nil || t.factory == nil || t.resolver == nil { + return report, errors.New("DNS 验证服务未初始化") } testDomain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(testDomain), ".")) if !domain.IsValidName(testDomain) { - return fmt.Errorf("DNS 测试域名格式无效:%s", testDomain) + return report, fmt.Errorf("DNS 测试域名格式无效:%s", testDomain) } cleaned, err := ValidateCredentials(providerID, credentials) if err != nil { - return err + return report, err } provider, err := t.factory.Create(providerID, cleaned) if err != nil { - return err + return report, err } token, err := randomValue(24) if err != nil { - return fmt.Errorf("生成 DNS 测试标识失败:%w", err) + return report, fmt.Errorf("生成 DNS 测试标识失败:%w", err) } keyAuth, err := randomValue(48) if err != nil { - return fmt.Errorf("生成 DNS 测试授权值失败:%w", err) + return report, fmt.Errorf("生成 DNS 测试授权值失败:%w", err) } + challengeInfo := dns01.GetChallengeInfo(ctx, testDomain, keyAuth) + report.RecordName = challengeInfo.EffectiveFQDN if err := provider.Present(ctx, testDomain, token, keyAuth); err != nil { - return fmt.Errorf("创建 DNS 测试记录失败:%w", err) + report.Stages = append(report.Stages, setup.DNSVerificationStage{ + Name: "创建记录", Status: "failed", Message: "调用 DNS API 创建临时 TXT 记录失败。", + }) + return report, &VerificationError{Report: report, Err: fmt.Errorf("创建 DNS 测试记录失败:%w", err)} } - if err := provider.CleanUp(ctx, testDomain, token, keyAuth); err != nil { - return fmt.Errorf("DNS 测试记录已创建,但自动清理失败:%w", err) + report.Stages = append(report.Stages, setup.DNSVerificationStage{ + Name: "创建记录", Status: "completed", Message: "已调用 DNS API 创建临时 TXT 记录。", + }) + + if err := waitForTXT(ctx, t.resolver, report.RecordName, challengeInfo.Value); err != nil { + report.Stages = append(report.Stages, setup.DNSVerificationStage{ + Name: "查询记录", Status: "failed", Message: "公网 DNS 查询未确认 TXT 记录已生效。", + }) + cleanupErr := cleanupChallenge(ctx, provider, testDomain, token, keyAuth) + if cleanupErr != nil { + report.Stages = append(report.Stages, setup.DNSVerificationStage{ + Name: "清理记录", Status: "failed", Message: "测试记录清理失败,请检查 DNS API 权限。", + }) + return report, &VerificationError{Report: report, Err: fmt.Errorf("DNS 测试记录未通过公网查询,且自动清理失败:%w", cleanupErr)} + } + report.Stages = append(report.Stages, setup.DNSVerificationStage{ + Name: "清理记录", Status: "completed", Message: "已清理未通过查询确认的临时 TXT 记录。", + }) + return report, &VerificationError{Report: report, Err: fmt.Errorf("DNS 测试记录未通过公网查询:%w", err)} } - return nil + report.Stages = append(report.Stages, setup.DNSVerificationStage{ + Name: "查询记录", Status: "completed", Message: "公网 DNS 查询已确认 TXT 记录生效。", + }) + + if err := cleanupChallenge(ctx, provider, testDomain, token, keyAuth); err != nil { + report.Stages = append(report.Stages, setup.DNSVerificationStage{ + Name: "清理记录", Status: "failed", Message: "测试记录已创建并确认生效,但自动清理失败。", + }) + return report, &VerificationError{Report: report, Err: fmt.Errorf("DNS 测试记录已创建并确认生效,但自动清理失败:%w", err)} + } + report.Stages = append(report.Stages, setup.DNSVerificationStage{ + Name: "清理记录", Status: "completed", Message: "已调用 DNS API 清理临时 TXT 记录。", + }) + if values, err := t.resolver.LookupTXT(ctx, report.RecordName); err == nil && containsTXT(values, challengeInfo.Value) { + report.Stages[len(report.Stages)-1] = setup.DNSVerificationStage{ + Name: "清理记录", Status: "warning", Message: "清理请求已成功,但公网 DNS 仍能查询到旧记录,可能正在等待缓存刷新。", + } + } + return report, nil +} + +func cleanupChallenge(ctx context.Context, provider challenge.Provider, testDomain, token, keyAuth string) error { + cleanupBase := context.WithoutCancel(ctx) + cleanupCtx, cancel := context.WithTimeout(cleanupBase, dnsCleanupTimeout) + defer cancel() + return provider.CleanUp(cleanupCtx, testDomain, token, keyAuth) +} + +type legoTXTResolver struct{} + +func (legoTXTResolver) LookupTXT(ctx context.Context, fqdn string) ([]string, error) { + result, err := dnspersist01.DefaultClient().LookupTXT(ctx, fqdn) + if err != nil { + return nil, err + } + values := make([]string, 0, len(result.Records)) + for _, record := range result.Records { + values = append(values, record.Value) + } + return values, nil +} + +func waitForTXT(ctx context.Context, resolver TXTResolver, fqdn, expected string) error { + if resolver == nil { + return errors.New("TXT 查询服务未初始化") + } + deadline := time.NewTimer(30 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + for { + values, err := resolver.LookupTXT(ctx, fqdn) + if err == nil && containsTXT(values, expected) { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-deadline.C: + if err != nil { + return fmt.Errorf("查询 TXT 记录失败:%w", err) + } + return errors.New("查询结果中未找到测试 TXT 值") + case <-ticker.C: + } + } +} + +func containsTXT(values []string, expected string) bool { + for _, value := range values { + if strings.TrimSpace(value) == expected { + return true + } + } + return false } func randomValue(size int) (string, error) { diff --git a/backend/internal/dnsprovider/tester_test.go b/backend/internal/dnsprovider/tester_test.go index 15d1ec9..a5653ce 100644 --- a/backend/internal/dnsprovider/tester_test.go +++ b/backend/internal/dnsprovider/tester_test.go @@ -3,9 +3,11 @@ package dnsprovider import ( "context" "errors" + "strings" "testing" "github.com/go-acme/lego/v5/challenge" + "github.com/go-acme/lego/v5/challenge/dns01" ) type fakeFactory struct { @@ -18,38 +20,69 @@ func (f fakeFactory) Create(string, map[string]string) (challenge.Provider, erro } type fakeProvider struct { - presented bool - cleaned bool - presentErr error - cleanupErr error + presented bool + cleaned bool + cleanupSawCanceled bool + presentErr error + cleanupErr error + domain string + keyAuth string } -func (p *fakeProvider) Present(context.Context, string, string, string) error { +type fakeTXTResolver struct { + provider *fakeProvider +} + +func (r fakeTXTResolver) LookupTXT(ctx context.Context, _ string) ([]string, error) { + if r.provider == nil || r.provider.domain == "" || r.provider.keyAuth == "" { + return nil, errors.New("测试 DNS 记录尚未创建") + } + return []string{dns01.GetChallengeInfo(ctx, r.provider.domain, r.provider.keyAuth).Value}, nil +} + +func (p *fakeProvider) Present(_ context.Context, domain, _, keyAuth string) error { p.presented = true + p.domain = domain + p.keyAuth = keyAuth return p.presentErr } -func (p *fakeProvider) CleanUp(context.Context, string, string, string) error { +func (p *fakeProvider) CleanUp(ctx context.Context, _ string, _ string, _ string) error { p.cleaned = true + p.cleanupSawCanceled = ctx.Err() != nil return p.cleanupErr } +type missingTXTResolver struct{} + +func (missingTXTResolver) LookupTXT(context.Context, string) ([]string, error) { + return nil, nil +} + func TestTesterCreatesAndCleansChallengeRecord(t *testing.T) { provider := &fakeProvider{} - tester := NewTester(fakeFactory{provider: provider}) - err := tester.Verify(t.Context(), Cloudflare, "example.com", map[string]string{"api_token": "secret-token"}) + tester := NewTesterWithResolver(fakeFactory{provider: provider}, fakeTXTResolver{provider: provider}) + report, err := tester.Verify(t.Context(), Cloudflare, "example.com", map[string]string{"api_token": "secret-token"}) if err != nil { t.Fatalf("DNS 测试失败:%v", err) } if !provider.presented || !provider.cleaned { t.Fatalf("DNS 测试未完整执行:presented=%v cleaned=%v", provider.presented, provider.cleaned) } + if report.RecordName == "" || len(report.Stages) != 3 { + t.Fatalf("DNS 测试阶段报告不完整:%+v", report) + } + for index, stage := range report.Stages { + if stage.Status != "completed" && !(index == 2 && stage.Status == "warning") { + t.Fatalf("DNS 测试阶段状态异常:%+v", report.Stages) + } + } } func TestTesterDoesNotCleanupWhenPresentFails(t *testing.T) { provider := &fakeProvider{presentErr: errors.New("拒绝访问")} tester := NewTester(fakeFactory{provider: provider}) - err := tester.Verify(t.Context(), Cloudflare, "example.com", map[string]string{"api_token": "secret-token"}) + _, err := tester.Verify(t.Context(), Cloudflare, "example.com", map[string]string{"api_token": "secret-token"}) if err == nil { t.Fatal("创建测试记录失败时应返回错误") } @@ -58,6 +91,39 @@ func TestTesterDoesNotCleanupWhenPresentFails(t *testing.T) { } } +func TestTesterCleansUpWithIndependentContextAfterQueryCancellation(t *testing.T) { + provider := &fakeProvider{} + tester := NewTesterWithResolver(fakeFactory{provider: provider}, missingTXTResolver{}) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err := tester.Verify(ctx, Cloudflare, "example.com", map[string]string{"api_token": "secret-token"}) + if err == nil { + t.Fatal("公网查询被取消时应返回错误") + } + if !provider.cleaned { + t.Fatal("公网查询被取消时仍应尝试清理测试记录") + } + if provider.cleanupSawCanceled { + t.Fatal("清理测试记录不应继承已取消的请求上下文") + } +} + +func TestTesterReportsCleanupFailureAfterQueryFailure(t *testing.T) { + provider := &fakeProvider{cleanupErr: errors.New("权限不足")} + tester := NewTesterWithResolver(fakeFactory{provider: provider}, missingTXTResolver{}) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + report, err := tester.Verify(ctx, Cloudflare, "example.com", map[string]string{"api_token": "secret-token"}) + if err == nil || !strings.Contains(err.Error(), "自动清理失败") { + t.Fatalf("查询失败且清理失败时应返回组合诊断:%v", err) + } + if len(report.Stages) != 3 || report.Stages[1].Status != "failed" || report.Stages[2].Status != "failed" { + t.Fatalf("查询和清理失败阶段报告不完整:%+v", report.Stages) + } +} + func TestValidateCredentialsRejectsUnknownField(t *testing.T) { _, err := ValidateCredentials(Cloudflare, map[string]string{"api_token": "token", "unexpected": "value"}) if err == nil { @@ -65,10 +131,13 @@ func TestValidateCredentialsRejectsUnknownField(t *testing.T) { } } -func TestUnavailableProviderReturnsTypedError(t *testing.T) { - _, err := NewLegoFactory().Create(CNAME, map[string]string{"delegated_domain": "acme.example.com", "delegated_provider": "cloudflare"}) - if !errors.Is(err, ErrProviderUnavailable) { - t.Fatalf("未开放适配器应返回指定错误:%v", err) +func TestCNAMEProviderIsAvailable(t *testing.T) { + descriptor, err := GetDescriptor(CNAME) + if err != nil { + t.Fatalf("failed to read CNAME descriptor: %v", err) + } + if !descriptor.Available { + t.Fatal("CNAME delegation adapter should be available") } } @@ -95,7 +164,7 @@ func TestLegoFactoryCreatesConfiguredProviders(t *testing.T) { }, }, { - name: "华为云无效区域校验", + name: "DNSPod", providerID: HuaweiCloud, credentials: map[string]string{ "access_key_id": "id", @@ -104,7 +173,7 @@ func TestLegoFactoryCreatesConfiguredProviders(t *testing.T) { }, }, { - name: "腾讯云", + name: "华为云无效区域校验", providerID: TencentCloud, credentials: map[string]string{ "secret_id": "id", diff --git a/backend/internal/httpapi/certificate_restore_api.go b/backend/internal/httpapi/certificate_restore_api.go new file mode 100644 index 0000000..5d6995e --- /dev/null +++ b/backend/internal/httpapi/certificate_restore_api.go @@ -0,0 +1,37 @@ +package httpapi + +import ( + "errors" + "net/http" + "strings" + + "github.com/gin-gonic/gin" + + "git.pcux.cn/xuans/Scert/backend/internal/repository" +) + +func (s *Server) restoreCertificateVersion(c *gin.Context) { + if s.restoreVersion == nil { + s.writeError(c, http.StatusNotImplemented, "证书恢复接口尚未配置", errors.New("证书恢复流程未配置")) + return + } + version := strings.TrimSpace(c.Param("version")) + result, err := s.restoreVersion(c.Request.Context(), strings.TrimSpace(c.Param("id")), version) + if err != nil { + if s.audit != nil { + _ = s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{ + Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "failed", + Message: "恢复证书历史版本失败:" + err.Error(), + }) + } + s.writeError(c, certificateErrorStatus(err), "恢复证书历史版本失败", err) + return + } + if s.audit != nil { + _ = s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{ + Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "success", + Message: "已恢复证书历史版本:" + version, + }) + } + c.JSON(http.StatusOK, result) +} diff --git a/backend/internal/httpapi/certificate_restore_api_test.go b/backend/internal/httpapi/certificate_restore_api_test.go new file mode 100644 index 0000000..74fd508 --- /dev/null +++ b/backend/internal/httpapi/certificate_restore_api_test.go @@ -0,0 +1,116 @@ +package httpapi + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "git.pcux.cn/xuans/Scert/backend/internal/certificate" + "git.pcux.cn/xuans/Scert/backend/internal/config" + "git.pcux.cn/xuans/Scert/backend/internal/domain" + "git.pcux.cn/xuans/Scert/backend/internal/repository" +) + +type restoreCertificateReader struct { + versions []certificate.SavedResource +} + +func (r restoreCertificateReader) Current(context.Context, string) (certificate.IssueResult, error) { + return certificate.IssueResult{}, nil +} + +func (r restoreCertificateReader) ListVersions(context.Context, string) ([]certificate.SavedResource, error) { + return r.versions, nil +} + +type restoreAuditRepository struct { + items []repository.AuditLog +} + +func (r *restoreAuditRepository) CreateAuditLog(_ context.Context, item repository.AuditLog) error { + r.items = append(r.items, item) + return nil +} + +func newRestoreAPITestServer(t *testing.T, restore func(context.Context, string, string) (certificate.IssueResult, error)) (*Server, *restoreAuditRepository) { + t.Helper() + audit := &restoreAuditRepository{} + cfg := config.Default(t.TempDir()) + cfg.SetupReady = true + server := New(Dependencies{ + Config: cfg, + Repository: &stubDomainRepository{}, + CurrentCertificate: restoreCertificateReader{}, + RestoreCertificateVersion: restore, + Audit: audit, + }) + server.authSessions["test-session"] = authSession{ + Username: "admin", + Role: "super_admin", + ExpiresAt: time.Now().Add(time.Hour), + } + return server, audit +} + +func TestRestoreCertificateVersionAPIRecordsSuccessAudit(t *testing.T) { + called := false + server, audit := newRestoreAPITestServer(t, func(_ context.Context, domainID, version string) (certificate.IssueResult, error) { + called = true + if domainID != "domain-1" || version != "20260830-120000" { + t.Fatalf("unexpected restore request: %s %s", domainID, version) + } + return certificate.IssueResult{DomainID: domainID, Saved: certificate.SavedResource{Version: version}}, nil + }) + request := httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/certificate/versions/20260830-120000/restore", nil) + request.AddCookie(&http.Cookie{Name: authCookieName, Value: "test-session"}) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "20260830-120000") { + t.Fatalf("unexpected success response: %d %s", response.Code, response.Body.String()) + } + if !called { + t.Fatal("restore callback was not called") + } + if len(audit.items) != 1 || audit.items[0].Status != "success" || audit.items[0].Action != "certificate_version_restore" { + t.Fatalf("success audit was not recorded: %+v", audit.items) + } +} + +func TestRestoreCertificateVersionAPIRecordsFailureAudit(t *testing.T) { + server, audit := newRestoreAPITestServer(t, func(context.Context, string, string) (certificate.IssueResult, error) { + return certificate.IssueResult{}, errors.New("simulated restore failure") + }) + request := httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/certificate/versions/bad/restore", nil) + request.AddCookie(&http.Cookie{Name: authCookieName, Value: "test-session"}) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusUnprocessableEntity { + t.Fatalf("unexpected failure response: %d %s", response.Code, response.Body.String()) + } + if len(audit.items) != 1 || audit.items[0].Status != "failed" || audit.items[0].Action != "certificate_version_restore" { + t.Fatalf("failure audit was not recorded: %+v", audit.items) + } +} + +func TestListCertificateVersionsAPIRequiresAuthentication(t *testing.T) { + cfg := config.Default(t.TempDir()) + cfg.SetupReady = true + server := New(Dependencies{ + Config: cfg, + Repository: &stubDomainRepository{}, + CurrentCertificate: restoreCertificateReader{versions: []certificate.SavedResource{{Domain: "example.com", Version: "v1"}}}, + }) + request := httptest.NewRequest(http.MethodGet, "/api/v1/domains/domain-1/certificate/versions", nil) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated version request should be rejected: %d", response.Code) + } +} + +var _ repository.DomainRepository = (*stubDomainRepository)(nil) +var _ = domain.Domain{} diff --git a/backend/internal/httpapi/frontend.go b/backend/internal/httpapi/frontend.go new file mode 100644 index 0000000..0627d47 --- /dev/null +++ b/backend/internal/httpapi/frontend.go @@ -0,0 +1,89 @@ +package httpapi + +import ( + "net/http" + "os" + pathpkg "path" + "path/filepath" + "strings" + + "github.com/gin-gonic/gin" +) + +// frontend 为浏览器提供前端静态文件,并为 Vue 的 history 路由回退到 index.html。 +func (s *Server) frontend(c *gin.Context) { + if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead { + c.Status(http.StatusNotFound) + return + } + + s.configMu.RLock() + enabled := s.config.Web.Enabled + s.configMu.RUnlock() + if !enabled || strings.TrimSpace(s.frontendDir) == "" { + c.Status(http.StatusNotFound) + return + } + + requestPath := pathpkg.Clean("/" + strings.TrimPrefix(c.Request.URL.Path, "/")) + if requestPath == "." || requestPath == "/" { + requestPath = "/" + } + if isCoreRequestPath(requestPath) { + c.Status(http.StatusNotFound) + return + } + + staticDir, err := filepath.Abs(s.frontendDir) + if err != nil { + c.Status(http.StatusNotFound) + return + } + relativePath := strings.TrimPrefix(requestPath, "/") + candidate := filepath.Join(staticDir, filepath.FromSlash(relativePath)) + if !isWithinDirectory(staticDir, candidate) { + c.Status(http.StatusNotFound) + return + } + + if info, statErr := os.Stat(candidate); statErr == nil && info.Mode().IsRegular() { + serveFrontendFile(c, candidate) + return + } + + if requestPath != "/" && filepath.Ext(requestPath) != "" { + c.Status(http.StatusNotFound) + return + } + + indexPath := filepath.Join(staticDir, "index.html") + if info, statErr := os.Stat(indexPath); statErr != nil || !info.Mode().IsRegular() { + c.Status(http.StatusNotFound) + return + } + serveFrontendFile(c, indexPath) +} + +func serveFrontendFile(c *gin.Context, path string) { + c.Header("Cache-Control", "no-cache") + if filepath.Base(path) != "index.html" { + c.Header("Cache-Control", "public, max-age=31536000, immutable") + } + http.ServeFile(c.Writer, c.Request, path) +} + +func isCoreRequestPath(path string) bool { + return path == "/api" || + strings.HasPrefix(path, "/api/") || + path == "/healthz" || + path == "/reset" || + strings.HasPrefix(path, "/reset/") +} + +func isWithinDirectory(directory, candidate string) bool { + relative, err := filepath.Rel(directory, candidate) + if err != nil { + return false + } + return relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) +} diff --git a/backend/internal/httpapi/frontend_test.go b/backend/internal/httpapi/frontend_test.go new file mode 100644 index 0000000..49d1081 --- /dev/null +++ b/backend/internal/httpapi/frontend_test.go @@ -0,0 +1,73 @@ +package httpapi + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "git.pcux.cn/xuans/Scert/backend/internal/config" +) + +func TestFrontendServesAssetsAndHistoryRoutes(t *testing.T) { + staticDir := t.TempDir() + if err := os.WriteFile(filepath.Join(staticDir, "index.html"), []byte("Scert"), 0o644); err != nil { + t.Fatalf("写入前端入口失败:%v", err) + } + if err := os.Mkdir(filepath.Join(staticDir, "assets"), 0o755); err != nil { + t.Fatalf("创建静态资源目录失败:%v", err) + } + if err := os.WriteFile(filepath.Join(staticDir, "assets", "app.js"), []byte("console.log('ok')"), 0o644); err != nil { + t.Fatalf("写入静态资源失败:%v", err) + } + + cfg := config.Default(t.TempDir()) + server := New(Dependencies{Config: cfg, FrontendDir: staticDir}) + + tests := []struct { + name string + method string + path string + wantStatus int + wantBody string + }{ + {name: "root", method: http.MethodGet, path: "/", wantStatus: http.StatusOK, wantBody: "Scert"}, + {name: "history route", method: http.MethodGet, path: "/login", wantStatus: http.StatusOK, wantBody: "Scert"}, + {name: "asset", method: http.MethodGet, path: "/assets/app.js", wantStatus: http.StatusOK, wantBody: "console.log"}, + {name: "missing asset", method: http.MethodGet, path: "/assets/missing.js", wantStatus: http.StatusNotFound}, + {name: "unknown api", method: http.MethodGet, path: "/api/unknown", wantStatus: http.StatusNotFound}, + {name: "post fallback", method: http.MethodPost, path: "/login", wantStatus: http.StatusNotFound}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + request := httptest.NewRequest(test.method, test.path, nil) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != test.wantStatus { + t.Fatalf("状态码 = %d,期望 %d,响应:%s", response.Code, test.wantStatus, response.Body.String()) + } + if test.wantBody != "" && !strings.Contains(response.Body.String(), test.wantBody) { + t.Fatalf("响应未包含 %q:%s", test.wantBody, response.Body.String()) + } + }) + } +} + +func TestFrontendRespectsWebEnabled(t *testing.T) { + staticDir := t.TempDir() + if err := os.WriteFile(filepath.Join(staticDir, "index.html"), []byte("Scert"), 0o644); err != nil { + t.Fatalf("写入前端入口失败:%v", err) + } + cfg := config.Default(t.TempDir()) + cfg.Web.Enabled = false + server := New(Dependencies{Config: cfg, FrontendDir: staticDir}) + + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil)) + if response.Code != http.StatusNotFound { + t.Fatalf("关闭 Web 后根路径应返回 404:%d", response.Code) + } +} diff --git a/backend/internal/httpapi/renewal_api.go b/backend/internal/httpapi/renewal_api.go new file mode 100644 index 0000000..d45b16e --- /dev/null +++ b/backend/internal/httpapi/renewal_api.go @@ -0,0 +1,23 @@ +package httpapi + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" +) + +func (s *Server) runRenewalNow(c *gin.Context) { + if s.runRenewal == nil { + s.writeError(c, http.StatusNotImplemented, "续期服务未配置", errors.New("续期工作流未配置")) + return + } + report, err := s.runRenewal(c.Request.Context()) + response := gin.H{"report": report} + if err != nil { + response["error"] = err.Error() + c.JSON(http.StatusConflict, response) + return + } + c.JSON(http.StatusOK, response) +} diff --git a/backend/internal/httpapi/reset.go b/backend/internal/httpapi/reset.go index ac494d8..c0f269c 100644 --- a/backend/internal/httpapi/reset.go +++ b/backend/internal/httpapi/reset.go @@ -246,6 +246,6 @@ func (s *Server) recordResetAudit(c *gin.Context, status, message string) { } var resetTemplate = template.Must(template.New("reset").Parse(` -Scert 超级管理员密码重置

超级管理员密码重置

本入口由 Scert-admin 临时开启,仅允许使用一次性校验码重置密码。

{{if .Message}}
{{.Message}}
{{end}}
`)) +Scert 超级管理员密码重置

超级管理员密码重置

本入口由 Scert-admin 临时开启,仅允许使用一次性校验码重置密码。

{{if .Message}}
{{.Message}}
{{end}}
`)) var resetSuccessTemplate = template.Must(template.New("reset-success").Parse(`Scert 密码重置完成

密码重置完成

{{.Message}}

`)) diff --git a/backend/internal/httpapi/server.go b/backend/internal/httpapi/server.go index 3f28c8b..f9eda70 100644 --- a/backend/internal/httpapi/server.go +++ b/backend/internal/httpapi/server.go @@ -29,33 +29,39 @@ import ( type setupSecretWriter interface { Put(context.Context, string, map[string]string) error + Delete(context.Context, string) error } type Dependencies struct { - Config config.Config - ConfigPath string - Logger *logging.Logger - Repository repository.DomainRepository - 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) - RollbackSetupCertificate func(context.Context, certificate.SavedResource) error - ImportCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error) - DeployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error) - CurrentCertificate certificateReader - ResetStatePath string - Audit repository.AuditRepository - Tasks repository.TaskRepository + Config config.Config + ConfigPath string + FrontendDir string + Logger *logging.Logger + Repository repository.DomainRepository + 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) + RollbackSetupCertificate func(context.Context, certificate.SavedResource) error + ImportCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error) + DeployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error) + RestoreCertificateVersion func(context.Context, string, string) (certificate.IssueResult, error) + + RunRenewal func(context.Context) (certificate.RenewalReport, error) + CurrentCertificate certificateReader + ResetStatePath string + Audit repository.AuditRepository + Tasks repository.TaskRepository } type Server struct { configMu sync.RWMutex config config.Config configPath string + frontendDir string logger *logging.Logger repository repository.DomainRepository servers repository.ServerRepository @@ -68,28 +74,35 @@ type Server struct { rollbackSetupCertificate func(context.Context, certificate.SavedResource) error importCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error) deployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error) - currentCertificate certificateReader - resetStatePath string - audit repository.AuditRepository - tasks repository.TaskRepository - resetMu sync.Mutex - resetClosedHash string - resetLimiter *resetRateLimiter - authSessions map[string]authSession - authMu sync.RWMutex - loginAttempts map[string]loginAttempt - loginMu sync.Mutex - now func() time.Time - httpServer *http.Server - router *gin.Engine + restoreVersion func(context.Context, string, string) (certificate.IssueResult, error) + + runRenewal func(context.Context) (certificate.RenewalReport, error) + currentCertificate certificateReader + resetStatePath string + audit repository.AuditRepository + tasks repository.TaskRepository + resetMu sync.Mutex + resetClosedHash string + resetLimiter *resetRateLimiter + authSessions map[string]authSession + authMu sync.RWMutex + loginAttempts map[string]loginAttempt + loginMu sync.Mutex + now func() time.Time + httpServer *http.Server + router *gin.Engine } func New(deps Dependencies) *Server { gin.SetMode(gin.ReleaseMode) router := gin.New() router.Use(gin.Recovery()) + frontendDir := strings.TrimSpace(deps.FrontendDir) + if frontendDir == "" { + frontendDir = filepath.Join(deps.Config.Paths.Install, "web") + } server := &Server{ - config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger, + config: deps.Config, configPath: deps.ConfigPath, frontendDir: filepath.Clean(frontendDir), logger: deps.Logger, repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router, servers: deps.Servers, sshKeys: deps.SSHKeys, @@ -98,6 +111,8 @@ func New(deps Dependencies) *Server { rollbackSetupCertificate: deps.RollbackSetupCertificate, importCertificate: deps.ImportCertificate, deployCertificate: deps.DeployCertificate, + restoreVersion: deps.RestoreCertificateVersion, + runRenewal: deps.RunRenewal, currentCertificate: deps.CurrentCertificate, resetStatePath: deps.ResetStatePath, audit: deps.Audit, @@ -133,12 +148,16 @@ func (s *Server) registerRoutes() { adminAPI.GET("/tasks/:id", s.getTask) adminAPI.GET("/tasks/:id/attempts", s.listTaskAttempts) adminAPI.GET("/audit-logs", s.listAuditLogs) + adminAPI.GET("/settings", s.getSettings) + adminAPI.PUT("/settings", s.updateSettings) + adminAPI.POST("/renewal/run", s.runRenewalNow) adminAPI.GET("/certificates", s.listCertificates) adminAPI.GET("/certificates/:id", s.getCertificate) adminAPI.POST("/domains/:id/certificate/import", s.importCertificateFiles) adminAPI.POST("/domains/:id/certificate/validate", s.validateCertificate) adminAPI.POST("/domains/:id/deploy", s.deployCertificateCurrent) adminAPI.GET("/domains/:id/certificate/versions", s.listCertificateVersions) + adminAPI.POST("/domains/:id/certificate/versions/:version/restore", s.restoreCertificateVersion) adminAPI.GET("/domains/:id/servers", s.listDomainServers) adminAPI.PUT("/domains/:id/servers", s.replaceDomainServers) adminAPI.GET("/servers", s.listServers) @@ -149,6 +168,7 @@ func (s *Server) registerRoutes() { adminAPI.GET("/ssh-keys", s.listSSHKeys) adminAPI.POST("/ssh-keys", s.createSSHKey) adminAPI.DELETE("/ssh-keys/:id", s.deleteSSHKey) + s.router.NoRoute(s.frontend) } func (s *Server) Handler() http.Handler { diff --git a/backend/internal/httpapi/server_test.go b/backend/internal/httpapi/server_test.go index 2a1532a..f74767d 100644 --- a/backend/internal/httpapi/server_test.go +++ b/backend/internal/httpapi/server_test.go @@ -134,8 +134,8 @@ func TestResetPasswordUpdatesConfigAndConsumesSession(t *testing.T) { form := url.Values{ "csrf_token": {cookie.Value}, "reset_code": {session.Code}, - "new_password": {"NewPassword123"}, - "confirm_password": {"NewPassword123"}, + "new_password": {"NewPass1234"}, + "confirm_password": {"NewPass1234"}, } request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(form.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") @@ -157,7 +157,7 @@ func TestResetPasswordUpdatesConfigAndConsumesSession(t *testing.T) { if err != nil { t.Fatalf("读取重置后的配置失败:%v", err) } - if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPassword123")) != nil { + if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPass1234")) != nil { t.Fatal("新密码摘要无法验证新密码") } if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("OldPassword123")) == nil { @@ -191,7 +191,7 @@ func TestResetRejectsCrossSiteAndLimitsFailures(t *testing.T) { get := httptest.NewRecorder() server.Handler().ServeHTTP(get, httptest.NewRequest(http.MethodGet, "http://scert.example.test/reset", nil)) cookie := get.Result().Cookies()[0] - base := url.Values{"csrf_token": {cookie.Value}, "reset_code": {session.Code}, "new_password": {"NewPassword123"}, "confirm_password": {"NewPassword123"}} + base := url.Values{"csrf_token": {cookie.Value}, "reset_code": {session.Code}, "new_password": {"NewPass1234"}, "confirm_password": {"NewPass1234"}} for i := 0; i < 5; i++ { request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(base.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") @@ -296,7 +296,7 @@ func TestResetConfigSaveFailureKeepsSessionAndPassword(t *testing.T) { } fixture.server.configPath = blockedPath - form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123") + form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234") request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.Header.Set("Origin", "https://scert.example.test") @@ -329,7 +329,7 @@ func TestResetConfigSaveFailureKeepsSessionAndPassword(t *testing.T) { func TestResetRejectsOversizedRequestBody(t *testing.T) { fixture := newResetTestFixture(t) - form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123") + form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234") form.Set("padding", strings.Repeat("x", resetMaxBodyBytes)) request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") @@ -365,7 +365,7 @@ func TestResetCSRFCookieHasRestrictedAttributes(t *testing.T) { func TestResetConcurrentSubmissionsAllowOnlyOneSuccess(t *testing.T) { fixture := newResetTestFixture(t) - form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123") + form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234") start := make(chan struct{}) responses := make(chan int, 2) var waitGroup sync.WaitGroup @@ -410,7 +410,7 @@ func TestResetConcurrentSubmissionsAllowOnlyOneSuccess(t *testing.T) { if err != nil { t.Fatalf("读取并发提交后的配置失败:%v", err) } - if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPassword123")) != nil { + if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPass1234")) != nil { t.Fatal("并发提交后的密码摘要无法验证新密码") } } diff --git a/backend/internal/httpapi/settings_api.go b/backend/internal/httpapi/settings_api.go new file mode 100644 index 0000000..e8c2b14 --- /dev/null +++ b/backend/internal/httpapi/settings_api.go @@ -0,0 +1,348 @@ +package httpapi + +import ( + "errors" + "net/http" + "reflect" + "strings" + + "github.com/gin-gonic/gin" + + "git.pcux.cn/xuans/Scert/backend/internal/config" +) + +type settingsView struct { + Server settingsServerView `json:"server"` + Web settingsWebView `json:"web"` + Paths settingsPathsView `json:"paths"` + ACME settingsACMEView `json:"acme"` + DNS settingsDNSView `json:"dns"` + Notification settingsNotificationView `json:"notification"` +} + +type settingsServerView struct { + Host string `json:"host"` + Port int `json:"port"` + HTTPSMode string `json:"https_mode"` +} + +type settingsWebView struct { + Enabled bool `json:"enabled"` + Hostname string `json:"hostname"` + PublicIP string `json:"public_ip"` +} + +type settingsPathsView struct { + Certificate string `json:"certificate"` +} + +type settingsACMEView struct { + 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 settingsDNSView struct { + Provider string `json:"provider"` + VerificationState string `json:"verification_state"` +} + +type settingsNotificationView struct { + HTTPEnabled bool `json:"http_enabled"` + SMTPEnabled bool `json:"smtp_enabled"` + SMTPHost string `json:"smtp_host"` + SMTPPort int `json:"smtp_port"` + SMTPUsername string `json:"smtp_username"` + SMTPMode string `json:"smtp_mode"` + SMTPAllowPlaintextAuth bool `json:"smtp_allow_plaintext_auth"` + SMTPCredentialConfigured bool `json:"smtp_credential_configured"` + Provider string `json:"provider"` + Endpoint string `json:"endpoint"` + HTTPPath string `json:"http_path"` + HTTPLoginPath string `json:"http_login_path"` + HTTPAuthMode string `json:"http_auth_mode"` + HTTPCredentialConfigured bool `json:"http_credential_configured"` + EventMode string `json:"event_mode"` + IncludeDeploymentDetails bool `json:"include_deployment_details"` + IncludeCertificateSerial bool `json:"include_certificate_serial"` + IncludeManagementURL bool `json:"include_management_url"` + SenderName string `json:"sender_name"` + SenderEmail string `json:"sender_email"` + Recipients []string `json:"recipients"` + TimeoutSecs int `json:"timeout_secs"` + RetryCount int `json:"retry_count"` + RetryIntervalsSecs []int `json:"retry_intervals_secs"` +} + +type settingsRequest struct { + Server *settingsServerRequest `json:"server"` + Web *settingsWebRequest `json:"web"` + Paths *settingsPathsRequest `json:"paths"` + ACME *settingsACMERequest `json:"acme"` + DNS *settingsDNSRequest `json:"dns"` + Notification *settingsNotificationRequest `json:"notification"` +} + +type settingsServerRequest struct { + Host *string `json:"host"` + Port *int `json:"port"` + HTTPSMode *string `json:"https_mode"` +} + +type settingsWebRequest struct { + Enabled *bool `json:"enabled"` + Hostname *string `json:"hostname"` + PublicIP *string `json:"public_ip"` +} + +type settingsPathsRequest struct { + Certificate *string `json:"certificate"` +} + +type settingsACMERequest struct { + 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 settingsDNSRequest struct { + Provider *string `json:"provider"` +} + +type settingsNotificationRequest struct { + HTTPEnabled *bool `json:"http_enabled"` + SMTPEnabled *bool `json:"smtp_enabled"` + SMTPHost *string `json:"smtp_host"` + SMTPPort *int `json:"smtp_port"` + SMTPUsername *string `json:"smtp_username"` + SMTPPassword *string `json:"smtp_password"` + SMTPMode *string `json:"smtp_mode"` + SMTPAllowPlaintextAuth *bool `json:"smtp_allow_plaintext_auth"` + HTTPCredentials map[string]string `json:"http_credentials"` + Provider *string `json:"provider"` + Endpoint *string `json:"endpoint"` + HTTPPath *string `json:"http_path"` + HTTPLoginPath *string `json:"http_login_path"` + HTTPAuthMode *string `json:"http_auth_mode"` + EventMode *string `json:"event_mode"` + IncludeDeploymentDetails *bool `json:"include_deployment_details"` + IncludeCertificateSerial *bool `json:"include_certificate_serial"` + IncludeManagementURL *bool `json:"include_management_url"` + SenderName *string `json:"sender_name"` + SenderEmail *string `json:"sender_email"` + Recipients *[]string `json:"recipients"` + TimeoutSecs *int `json:"timeout_secs"` + RetryCount *int `json:"retry_count"` + RetryIntervalsSecs *[]int `json:"retry_intervals_secs"` +} + +func (s *Server) getSettings(c *gin.Context) { + s.configMu.RLock() + cfg := s.config + s.configMu.RUnlock() + c.JSON(http.StatusOK, settingsViewFromConfig(cfg)) +} + +func (s *Server) updateSettings(c *gin.Context) { + if strings.TrimSpace(s.configPath) == "" { + s.writeError(c, http.StatusInternalServerError, "配置文件路径未配置", errors.New("配置文件路径为空")) + return + } + var request settingsRequest + if err := c.ShouldBindJSON(&request); err != nil { + s.writeError(c, http.StatusBadRequest, "设置请求格式不正确", err) + return + } + + s.configMu.Lock() + previous := s.config + updated := s.config + applySettingsRequest(&updated, request) + updated.Normalize() + if err := s.saveSettingsNotificationCredentials(c.Request.Context(), &updated, request); err != nil { + s.configMu.Unlock() + s.writeError(c, http.StatusBadRequest, "保存通知凭据失败", err) + return + } + if err := updated.Validate(); err != nil { + s.configMu.Unlock() + s.writeError(c, http.StatusBadRequest, "设置内容校验失败", err) + return + } + if err := updated.Save(s.configPath); err != nil { + s.configMu.Unlock() + s.writeError(c, http.StatusInternalServerError, "保存设置失败", err) + return + } + restartRequired := previous.Server.Host != updated.Server.Host || + previous.Server.Port != updated.Server.Port || + previous.Server.HTTPSMode != updated.Server.HTTPSMode || + previous.Paths.Certificate != updated.Paths.Certificate || + !reflect.DeepEqual(previous.ACME, updated.ACME) || + !reflect.DeepEqual(previous.DNS, updated.DNS) || + !reflect.DeepEqual(previous.Notification, updated.Notification) + message := "设置已保存" + if restartRequired { + message = "设置已保存;服务监听地址、端口或 HTTPS 模式已变更,请重启 Scert 服务" + } + s.config = updated + s.configMu.Unlock() + + c.JSON(http.StatusOK, gin.H{ + "settings": settingsViewFromConfig(updated), + "restart_required": restartRequired, + "message": message, + }) +} + +func settingsViewFromConfig(cfg config.Config) settingsView { + return settingsView{ + Server: settingsServerView{Host: cfg.Server.Host, Port: cfg.Server.Port, HTTPSMode: cfg.Server.HTTPSMode}, + Web: settingsWebView{Enabled: cfg.Web.Enabled, Hostname: cfg.Web.Hostname, PublicIP: cfg.Web.PublicIP}, + Paths: settingsPathsView{Certificate: cfg.Paths.Certificate}, + ACME: settingsACMEView{CA: cfg.ACME.CA, Environment: cfg.ACME.Environment, AccountEmail: cfg.ACME.AccountEmail, RenewalThresholdDays: cfg.ACME.RenewalThresholdDays, PropagationTimeoutSecs: cfg.ACME.PropagationTimeoutSecs, PropagationPollingIntervalSecs: cfg.ACME.PropagationPollingIntervalSecs}, + DNS: settingsDNSView{Provider: cfg.DNS.Provider, VerificationState: cfg.DNS.VerificationState}, + Notification: settingsNotificationView{ + HTTPEnabled: cfg.Notification.HTTPEnabled, SMTPEnabled: cfg.Notification.SMTPEnabled, Provider: cfg.Notification.Provider, + SMTPHost: cfg.Notification.SMTPHost, SMTPPort: cfg.Notification.SMTPPort, SMTPUsername: cfg.Notification.SMTPUsername, + SMTPMode: cfg.Notification.SMTPMode, SMTPAllowPlaintextAuth: cfg.Notification.SMTPAllowPlaintextAuth, + SMTPCredentialConfigured: strings.TrimSpace(cfg.Notification.SMTPCredentialRef) != "", + Endpoint: cfg.Notification.Endpoint, HTTPPath: cfg.Notification.HTTPPath, HTTPLoginPath: cfg.Notification.HTTPLoginPath, + HTTPAuthMode: cfg.Notification.HTTPAuthMode, HTTPCredentialConfigured: strings.TrimSpace(cfg.Notification.HTTPCredentialRef) != "", + EventMode: cfg.Notification.EventMode, IncludeDeploymentDetails: cfg.Notification.IncludeDeploymentDetails, + IncludeCertificateSerial: cfg.Notification.IncludeCertificateSerial, IncludeManagementURL: cfg.Notification.IncludeManagementURL, + SenderName: cfg.Notification.SenderName, SenderEmail: cfg.Notification.SenderEmail, + Recipients: append([]string(nil), cfg.Notification.Recipients...), TimeoutSecs: cfg.Notification.TimeoutSecs, + RetryCount: cfg.Notification.RetryCount, RetryIntervalsSecs: append([]int(nil), cfg.Notification.RetryIntervalsSecs...), + }, + } +} + +func applySettingsRequest(cfg *config.Config, request settingsRequest) { + if cfg == nil { + return + } + if request.Server != nil { + if request.Server.Host != nil { + cfg.Server.Host = strings.TrimSpace(*request.Server.Host) + } + if request.Server.Port != nil { + cfg.Server.Port = *request.Server.Port + } + if request.Server.HTTPSMode != nil { + cfg.Server.HTTPSMode = strings.TrimSpace(*request.Server.HTTPSMode) + } + } + if request.Web != nil { + if request.Web.Enabled != nil { + cfg.Web.Enabled = *request.Web.Enabled + } + if request.Web.Hostname != nil { + cfg.Web.Hostname = strings.TrimSpace(*request.Web.Hostname) + } + if request.Web.PublicIP != nil { + cfg.Web.PublicIP = strings.TrimSpace(*request.Web.PublicIP) + } + } + if request.Paths != nil && request.Paths.Certificate != nil { + cfg.Paths.Certificate = strings.TrimSpace(*request.Paths.Certificate) + } + if request.ACME != nil { + if request.ACME.CA != nil { + cfg.ACME.CA = strings.TrimSpace(*request.ACME.CA) + } + if request.ACME.Environment != nil { + cfg.ACME.Environment = strings.TrimSpace(*request.ACME.Environment) + } + if request.ACME.AccountEmail != nil { + cfg.ACME.AccountEmail = strings.TrimSpace(*request.ACME.AccountEmail) + } + if request.ACME.RenewalThresholdDays != nil { + cfg.ACME.RenewalThresholdDays = *request.ACME.RenewalThresholdDays + } + if request.ACME.PropagationTimeoutSecs != nil { + cfg.ACME.PropagationTimeoutSecs = *request.ACME.PropagationTimeoutSecs + } + if request.ACME.PropagationPollingIntervalSecs != nil { + cfg.ACME.PropagationPollingIntervalSecs = *request.ACME.PropagationPollingIntervalSecs + } + } + if request.DNS != nil && request.DNS.Provider != nil { + cfg.DNS.Provider = strings.TrimSpace(*request.DNS.Provider) + } + if request.Notification != nil { + item := request.Notification + if item.HTTPEnabled != nil { + cfg.Notification.HTTPEnabled = *item.HTTPEnabled + } + if item.SMTPEnabled != nil { + cfg.Notification.SMTPEnabled = *item.SMTPEnabled + } + if item.SMTPHost != nil { + cfg.Notification.SMTPHost = strings.TrimSpace(*item.SMTPHost) + } + if item.SMTPPort != nil { + cfg.Notification.SMTPPort = *item.SMTPPort + } + if item.SMTPUsername != nil { + cfg.Notification.SMTPUsername = strings.TrimSpace(*item.SMTPUsername) + } + if item.SMTPMode != nil { + cfg.Notification.SMTPMode = strings.TrimSpace(*item.SMTPMode) + } + if item.SMTPAllowPlaintextAuth != nil { + cfg.Notification.SMTPAllowPlaintextAuth = *item.SMTPAllowPlaintextAuth + } + if item.Provider != nil { + cfg.Notification.Provider = strings.TrimSpace(*item.Provider) + } + if item.Endpoint != nil { + cfg.Notification.Endpoint = strings.TrimSpace(*item.Endpoint) + } + if item.HTTPPath != nil { + cfg.Notification.HTTPPath = strings.TrimSpace(*item.HTTPPath) + } + if item.HTTPLoginPath != nil { + cfg.Notification.HTTPLoginPath = strings.TrimSpace(*item.HTTPLoginPath) + } + if item.HTTPAuthMode != nil { + cfg.Notification.HTTPAuthMode = strings.TrimSpace(*item.HTTPAuthMode) + } + if item.EventMode != nil { + cfg.Notification.EventMode = strings.TrimSpace(*item.EventMode) + } + if item.IncludeDeploymentDetails != nil { + cfg.Notification.IncludeDeploymentDetails = *item.IncludeDeploymentDetails + } + if item.IncludeCertificateSerial != nil { + cfg.Notification.IncludeCertificateSerial = *item.IncludeCertificateSerial + } + if item.IncludeManagementURL != nil { + cfg.Notification.IncludeManagementURL = *item.IncludeManagementURL + } + if item.SenderName != nil { + cfg.Notification.SenderName = strings.TrimSpace(*item.SenderName) + } + if item.SenderEmail != nil { + cfg.Notification.SenderEmail = strings.TrimSpace(*item.SenderEmail) + } + if item.Recipients != nil { + cfg.Notification.Recipients = append([]string(nil), (*item.Recipients)...) + } + if item.TimeoutSecs != nil { + cfg.Notification.TimeoutSecs = *item.TimeoutSecs + } + if item.RetryCount != nil { + cfg.Notification.RetryCount = *item.RetryCount + } + if item.RetryIntervalsSecs != nil { + cfg.Notification.RetryIntervalsSecs = append([]int(nil), (*item.RetryIntervalsSecs)...) + } + } +} diff --git a/backend/internal/httpapi/settings_api_test.go b/backend/internal/httpapi/settings_api_test.go new file mode 100644 index 0000000..d9f4d4d --- /dev/null +++ b/backend/internal/httpapi/settings_api_test.go @@ -0,0 +1,211 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "golang.org/x/crypto/bcrypt" + + "git.pcux.cn/xuans/Scert/backend/internal/certificate" + "git.pcux.cn/xuans/Scert/backend/internal/config" +) + +func TestSettingsAPIRequiresAuthentication(t *testing.T) { + cfg := config.Default(t.TempDir()) + cfg.SetupReady = true + server := New(Dependencies{Config: cfg}) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/settings", nil)) + if response.Code != http.StatusUnauthorized { + t.Fatalf("未登录访问设置接口应返回 401,实际为 %d:%s", response.Code, response.Body.String()) + } +} + +func TestSettingsAPIUpdatesSafeFieldsWithoutReturningSecrets(t *testing.T) { + dir := t.TempDir() + cfg := config.Default(dir) + cfg.SetupReady = true + cfg.DNS.VerificationState = "verified" + cfg.Web.Hostname = "scert.example.test" + cfg.Admin.Username = "admin" + cfg.Admin.Email = "admin@example.test" + cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123") + cfg.Database.DSN = "mysql://secret-user:secret-password@localhost/scert" + configPath := dir + "\\config\\scert.json" + if err := cfg.Save(configPath); err != nil { + t.Fatalf("保存测试配置失败:%v", err) + } + server := New(Dependencies{Config: cfg, ConfigPath: configPath}) + cookie := loginForSettingsTest(t, server) + + request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{ + "server": {"port": 5443}, + "web": {"hostname": "admin.example.test"}, + "acme": {"renewal_threshold_days": 10} + }`)) + request.Header.Set("Content-Type", "application/json") + request.AddCookie(cookie) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK { + t.Fatalf("更新设置应成功,实际为 %d:%s", response.Code, response.Body.String()) + } + body := response.Body.String() + for _, secret := range []string{"password_hash", "secret-password", "credential_ref", "tls_key", "mysql://"} { + if strings.Contains(body, secret) { + t.Fatalf("响应不应包含敏感字段 %q:%s", secret, body) + } + } + var payload struct { + Settings settingsView `json:"settings"` + RestartRequired bool `json:"restart_required"` + Message string `json:"message"` + } + if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil { + t.Fatalf("解析设置响应失败:%v", err) + } + if !payload.RestartRequired || payload.Settings.Server.Port != 5443 || payload.Settings.Web.Hostname != "admin.example.test" || payload.Settings.ACME.RenewalThresholdDays != 10 { + t.Fatalf("设置响应内容不正确:%+v", payload.Settings) + } + if !strings.Contains(payload.Message, "请重启 Scert 服务") { + t.Fatalf("监听参数变更后应明确提示重启服务:%s", payload.Message) + } + saved, err := config.Load(configPath) + if err != nil { + t.Fatalf("读取保存后的配置失败:%v", err) + } + if saved.Admin.PasswordHash != cfg.Admin.PasswordHash || saved.Database.DSN != cfg.Database.DSN { + t.Fatal("更新设置不应覆盖管理员密码或数据库 DSN") + } +} + +func TestSettingsAPIWebAddressChangeDoesNotRequireRestart(t *testing.T) { + dir := t.TempDir() + cfg := config.Default(dir) + cfg.SetupReady = true + cfg.DNS.VerificationState = "verified" + cfg.Web.Hostname = "scert.example.test" + cfg.Admin.Username = "admin" + cfg.Admin.Email = "admin@example.test" + cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123") + configPath := dir + "\\config\\scert.json" + if err := cfg.Save(configPath); err != nil { + t.Fatalf("保存测试配置失败:%v", err) + } + server := New(Dependencies{Config: cfg, ConfigPath: configPath}) + cookie := loginForSettingsTest(t, server) + + request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{ + "web": {"hostname": "admin.example.test", "public_ip": "203.0.113.10"} + }`)) + request.Header.Set("Content-Type", "application/json") + request.AddCookie(cookie) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK { + t.Fatalf("更新 Web 访问地址应成功,实际为 %d:%s", response.Code, response.Body.String()) + } + var payload struct { + RestartRequired bool `json:"restart_required"` + Message string `json:"message"` + } + if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil { + t.Fatalf("解析设置响应失败:%v", err) + } + if payload.RestartRequired { + t.Fatal("仅修改 Web 域名或公网 IP 不应要求重启服务") + } + if payload.Message != "设置已保存" { + t.Fatalf("无需重启时应返回简洁保存提示:%s", payload.Message) + } +} + +func TestSettingsAPIReturnsChineseNotificationCredentialError(t *testing.T) { + dir := t.TempDir() + cfg := config.Default(dir) + cfg.SetupReady = true + cfg.DNS.VerificationState = "verified" + cfg.Web.Hostname = "scert.example.test" + cfg.Admin.Username = "admin" + cfg.Admin.Email = "admin@example.test" + cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123") + configPath := dir + "\\config\\scert.json" + if err := cfg.Save(configPath); err != nil { + t.Fatalf("保存测试配置失败:%v", err) + } + server := New(Dependencies{Config: cfg, ConfigPath: configPath}) + cookie := loginForSettingsTest(t, server) + + request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{ + "notification": {"smtp_password": "secret-password"} + }`)) + request.Header.Set("Content-Type", "application/json") + request.AddCookie(cookie) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + + if response.Code != http.StatusBadRequest { + t.Fatalf("敏感凭据存储未配置时应返回 400,实际为 %d:%s", response.Code, response.Body.String()) + } + if !strings.Contains(response.Body.String(), "保存通知凭据失败") { + t.Fatalf("响应应包含中文通知凭据错误说明:%s", response.Body.String()) + } + if strings.Contains(response.Body.String(), "???") { + t.Fatalf("响应不应包含问号乱码:%s", response.Body.String()) + } +} + +func TestRenewalAPIUsesConfiguredRunner(t *testing.T) { + cfg := config.Default(t.TempDir()) + cfg.SetupReady = true + cfg.DNS.VerificationState = "verified" + cfg.Web.Hostname = "scert.example.test" + cfg.Admin.Username = "admin" + cfg.Admin.Email = "admin@example.test" + cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123") + called := false + server := New(Dependencies{ + Config: cfg, + RunRenewal: func(context.Context) (certificate.RenewalReport, error) { + called = true + return certificate.RenewalReport{Checked: 2, Selected: 1, Succeeded: 1}, nil + }, + }) + cookie := loginForSettingsTest(t, server) + request := httptest.NewRequest(http.MethodPost, "/api/v1/renewal/run", nil) + request.AddCookie(cookie) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK || !called || !strings.Contains(response.Body.String(), `"selected":1`) { + t.Fatalf("续期接口调用结果不正确:%d %s;called=%v", response.Code, response.Body.String(), called) + } +} + +func loginForSettingsTest(t *testing.T, server *Server) *http.Cookie { + t.Helper() + request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"identifier":"admin","password":"Password123"}`)) + request.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK { + t.Fatalf("管理员登录失败:%d %s", response.Code, response.Body.String()) + } + cookies := response.Result().Cookies() + if len(cookies) == 0 { + t.Fatal("登录响应未返回会话 Cookie") + } + return cookies[0] +} + +func mustTestPasswordHash(t *testing.T, password string) string { + t.Helper() + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost) + if err != nil { + t.Fatalf("生成测试密码摘要失败:%v", err) + } + return string(hash) +} diff --git a/backend/internal/httpapi/settings_secrets.go b/backend/internal/httpapi/settings_secrets.go new file mode 100644 index 0000000..140160d --- /dev/null +++ b/backend/internal/httpapi/settings_secrets.go @@ -0,0 +1,54 @@ +package httpapi + +import ( + "context" + "errors" + "strings" + + "git.pcux.cn/xuans/Scert/backend/internal/config" +) + +// saveSettingsNotificationCredentials 将页面提交的通知密码写入加密存储,配置文件只保存引用。 +func (s *Server) saveSettingsNotificationCredentials(ctx context.Context, cfg *config.Config, request settingsRequest) error { + if cfg == nil || request.Notification == nil { + return nil + } + item := request.Notification + if len(item.HTTPCredentials) > 0 { + if s.secrets == nil { + return errors.New("HTTP 通知敏感凭据存储尚未初始化") + } + values, err := normalizeNotificationCredentials(cfg.Notification.HTTPAuthMode, item.HTTPCredentials) + if err != nil { + return err + } + ref, err := newNotificationCredentialReference() + if err != nil { + return err + } + if err := s.secrets.Put(ctx, ref, values); err != nil { + return err + } + cfg.Notification.HTTPCredentialRef = ref + } + if item.SMTPPassword == nil || *item.SMTPPassword == "" { + return nil + } + if s.secrets == nil { + return errors.New("SMTP 通知敏感凭据存储尚未初始化") + } + username := strings.TrimSpace(cfg.Notification.SMTPUsername) + if username == "" { + return errors.New("填写 SMTP 密码前必须配置 SMTP 用户名") + } + ref, err := newNotificationCredentialReference() + if err != nil { + return err + } + values := map[string]string{"username": username, "password": *item.SMTPPassword} + if err := s.secrets.Put(ctx, ref, values); err != nil { + return err + } + cfg.Notification.SMTPCredentialRef = ref + return nil +} diff --git a/backend/internal/httpapi/setup.go b/backend/internal/httpapi/setup.go index 47daf7f..6693910 100644 --- a/backend/internal/httpapi/setup.go +++ b/backend/internal/httpapi/setup.go @@ -34,6 +34,13 @@ type setupRequest struct { AdminPassword string `json:"admin_password"` ServerPort int `json:"server_port"` EmailHTTPEnabled *bool `json:"email_http_enabled"` + EmailSMTPEnabled *bool `json:"email_smtp_enabled"` + EmailSMTPHost string `json:"email_smtp_host"` + EmailSMTPPort int `json:"email_smtp_port"` + EmailSMTPUsername string `json:"email_smtp_username"` + EmailSMTPPassword string `json:"email_smtp_password"` + EmailSMTPMode string `json:"email_smtp_mode"` + EmailSMTPAllowPlaintextAuth bool `json:"email_smtp_allow_plaintext_auth"` EmailProvider string `json:"email_provider"` EmailEndpoint string `json:"email_endpoint"` EmailHTTPPath string `json:"email_http_path"` @@ -145,10 +152,15 @@ func (s *Server) testSetupDNS(c *gin.Context) { s.writeError(c, http.StatusNotImplemented, "该 DNS 服务商在线验证适配器尚未开放", nil) return } + report := result.TestReport + var verificationErr *setup.DNSVerificationError + if errors.As(err, &verificationErr) { + report = verificationErr.Report + } if s.logger != nil { s.logger.Error("DNS API 在线验证失败", "provider", request.ProviderID, "test_domain", request.TestDomain) } - c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "DNS API 在线验证失败,请检查凭据、测试域名和 DNS 权限"}) + c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "DNS API 在线验证失败,请检查凭据、测试域名和 DNS 权限", "test_report": report}) return } c.JSON(http.StatusOK, gin.H{ @@ -156,6 +168,7 @@ func (s *Server) testSetupDNS(c *gin.Context) { "credential_ref": result.CredentialRef, "verification_token": result.VerificationToken, "expires_at": result.ExpiresAt, + "test_report": result.TestReport, "message": "DNS API 在线验证通过,凭据已加密保存。", }) } @@ -197,7 +210,37 @@ func (s *Server) applySetup(c *gin.Context) { if request.EmailHTTPEnabled != nil { emailHTTPEnabled = *request.EmailHTTPEnabled } + emailSMTPEnabled := false + if request.EmailSMTPEnabled != nil { + emailSMTPEnabled = *request.EmailSMTPEnabled + } + createdCredentialRefs := make([]string, 0, 2) emailCredentialRef := strings.TrimSpace(request.EmailHTTPCredentialRef) + smtpCredentialRef := "" + if emailSMTPEnabled { + smtpCredentialRef = strings.TrimSpace(s.config.Notification.SMTPCredentialRef) + if strings.TrimSpace(request.EmailSMTPPassword) != "" { + if strings.TrimSpace(request.EmailSMTPUsername) == "" { + s.writeError(c, http.StatusBadRequest, "填写 SMTP 密码前必须配置 SMTP 用户名", nil) + return + } + if s.secrets == nil { + s.writeError(c, http.StatusServiceUnavailable, "SMTP 通知敏感凭据存储尚未初始化", nil) + return + } + var smtpErr error + smtpCredentialRef, smtpErr = newNotificationCredentialReference() + if smtpErr != nil { + s.writeError(c, http.StatusInternalServerError, "生成 SMTP 通知凭据引用失败", smtpErr) + return + } + createdCredentialRefs = append(createdCredentialRefs, smtpCredentialRef) + } + if smtpCredentialRef == "" { + s.writeError(c, http.StatusBadRequest, "启用 SMTP 通知后必须填写 SMTP 密码或使用已有凭据", nil) + return + } + } var notificationCredentials map[string]string var credentialErr error if emailHTTPEnabled && strings.ToLower(strings.TrimSpace(request.EmailHTTPAuthMode)) != "none" { @@ -216,6 +259,7 @@ func (s *Server) applySetup(c *gin.Context) { s.writeError(c, http.StatusInternalServerError, "生成 HTTP 通知凭据引用失败", credentialErr) return } + createdCredentialRefs = append(createdCredentialRefs, emailCredentialRef) } else if emailCredentialRef == "" { s.writeError(c, http.StatusBadRequest, "启用 HTTP 通知认证后必须填写明文凭据或已有凭据引用", nil) return @@ -228,6 +272,13 @@ func (s *Server) applySetup(c *gin.Context) { AdminPassword: request.AdminPassword, ServerPort: request.ServerPort, EmailHTTPEnabled: emailHTTPEnabled, + EmailSMTPEnabled: emailSMTPEnabled, + EmailSMTPHost: request.EmailSMTPHost, + EmailSMTPPort: request.EmailSMTPPort, + EmailSMTPUsername: request.EmailSMTPUsername, + EmailSMTPCredentialRef: smtpCredentialRef, + EmailSMTPMode: request.EmailSMTPMode, + EmailSMTPAllowPlaintextAuth: request.EmailSMTPAllowPlaintextAuth, EmailProvider: request.EmailProvider, EmailEndpoint: request.EmailEndpoint, EmailHTTPPath: request.EmailHTTPPath, @@ -257,18 +308,22 @@ func (s *Server) applySetup(c *gin.Context) { HTTPSMode: request.HTTPSMode, }) if err != nil { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) s.writeError(c, http.StatusBadRequest, err.Error(), err) return } if strings.TrimSpace(s.configPath) == "" { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) s.writeError(c, http.StatusInternalServerError, "服务未配置配置文件路径,无法保存初始化结果", nil) return } if strings.TrimSpace(updated.Web.PublicIP) != "" { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) s.writeError(c, http.StatusBadRequest, "公网 IP 暂不支持通过 DNS-01 自动申请管理后台证书,请先配置域名或上传自有证书", nil) return } if s.issueSetupCertificate == nil { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) s.writeError(c, http.StatusServiceUnavailable, "初始化证书申请服务尚未配置", nil) return } @@ -286,10 +341,12 @@ func (s *Server) applySetup(c *gin.Context) { }) certificateCancel() if certificateErr != nil { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) s.writeError(c, http.StatusBadGateway, "申请管理后台证书失败,初始化尚未完成", certificateErr) return } if err := validateSetupCertificateFiles(savedCertificate); err != nil { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil { s.logger.Error("管理后台证书文件校验失败,且证书回滚失败", "error", rollbackErr) } @@ -300,6 +357,7 @@ func (s *Server) applySetup(c *gin.Context) { updated.Server.TLSKey = savedCertificate.PrivateKeyPath if len(notificationCredentials) > 0 { if err := s.secrets.Put(c.Request.Context(), emailCredentialRef, notificationCredentials); err != nil { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil { s.logger.Error("保存 HTTP 通知凭据失败,且证书回滚失败", "error", rollbackErr) } @@ -307,8 +365,22 @@ func (s *Server) applySetup(c *gin.Context) { return } } + if emailSMTPEnabled && strings.TrimSpace(request.EmailSMTPPassword) != "" { + if err := s.secrets.Put(c.Request.Context(), smtpCredentialRef, map[string]string{ + "username": strings.TrimSpace(request.EmailSMTPUsername), + "password": request.EmailSMTPPassword, + }); err != nil { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) + if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil { + s.logger.Error("保存 SMTP 通知凭据失败,且证书回滚失败", "error", rollbackErr) + } + s.writeError(c, http.StatusInternalServerError, "保存 SMTP 通知凭据失败,初始化尚未完成", err) + return + } + } updated.SetupReady = true if err := updated.Validate(); err != nil { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil { s.logger.Error("初始化证书配置无效,且证书回滚失败", "error", rollbackErr) } @@ -324,6 +396,7 @@ func (s *Server) applySetup(c *gin.Context) { firewallResult, err = s.firewall.OpenTCP(firewallContext, updated.Server.Port) cancel() if err != nil { + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil { s.logger.Error("自动配置本机防火墙失败,且证书回滚失败", "error", rollbackErr) } @@ -345,6 +418,7 @@ func (s *Server) applySetup(c *gin.Context) { if certificateRollbackErr != nil && s.logger != nil { s.logger.Error("保存初始化配置失败,且初始化证书回滚失败", "error", certificateRollbackErr) } + s.rollbackSetupCredentialsWithLog(createdCredentialRefs) if firewallRollbackErr != nil { s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败,且自动创建的防火墙规则回滚失败,请手动检查本机防火墙", err) return @@ -376,6 +450,36 @@ func (s *Server) applySetup(c *gin.Context) { }) } +func (s *Server) rollbackSetupCredentialsWithLog(references []string) { + if err := s.rollbackSetupCredentials(references); err != nil && s.logger != nil { + s.logger.Error("\u521d\u59cb\u5316\u654f\u611f\u51ed\u636e\u56de\u6eda\u5931\u8d25", "error", err) + } +} + +func (s *Server) rollbackSetupCredentials(references []string) error { + if s == nil || s.secrets == nil || len(references) == 0 { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + seen := make(map[string]struct{}, len(references)) + var rollbackErrors []error + for _, reference := range references { + reference = strings.TrimSpace(reference) + if reference == "" { + continue + } + if _, ok := seen[reference]; ok { + continue + } + seen[reference] = struct{}{} + if err := s.secrets.Delete(ctx, reference); err != nil { + rollbackErrors = append(rollbackErrors, fmt.Errorf("\u56de\u6eda\u654f\u611f\u51ed\u636e %s \u5931\u8d25\uFF1A%w", reference, err)) + } + } + return errors.Join(rollbackErrors...) +} + func (s *Server) rollbackIssuedSetupCertificate(saved certificate.SavedResource) error { if s.rollbackSetupCertificate == nil { return nil diff --git a/backend/internal/httpapi/setup_test.go b/backend/internal/httpapi/setup_test.go index 97540aa..35aeab1 100644 --- a/backend/internal/httpapi/setup_test.go +++ b/backend/internal/httpapi/setup_test.go @@ -29,7 +29,8 @@ type fakeSetupDNSVerifier struct { } type fakeSetupSecretWriter struct { - values map[string]map[string]string + values map[string]map[string]string + deleted []string } func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value map[string]string) error { @@ -44,6 +45,18 @@ func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value m return nil } +func (f *fakeSetupSecretWriter) Delete(_ context.Context, reference string) error { + if f.values == nil { + return errors.New("secret not found") + } + if _, ok := f.values[reference]; !ok { + return errors.New("secret not found") + } + delete(f.values, reference) + f.deleted = append(f.deleted, reference) + return nil +} + type fakeFirewallManager struct { result firewall.Result openErr error @@ -99,6 +112,14 @@ func (f *fakeSetupDNSVerifier) Verify(context.Context, setup.DNSVerificationInpu CredentialRef: "secret://dns/cloudflare/test", VerificationToken: "verified-token", ExpiresAt: time.Now().UTC().Add(15 * time.Minute), + TestReport: setup.DNSVerificationReport{ + RecordName: "_acme-challenge.example.com.", + Stages: []setup.DNSVerificationStage{ + {Name: "创建记录", Status: "completed", Message: "已创建测试记录"}, + {Name: "查询记录", Status: "completed", Message: "已确认测试记录"}, + {Name: "清理记录", Status: "completed", Message: "已清理测试记录"}, + }, + }, } } return f.verifyResult, f.verifyErr @@ -175,6 +196,11 @@ func TestSetupDNSProviderCatalogAndOnlineTest(t *testing.T) { if strings.Contains(testResponse.Body.String(), "secret-token") { t.Fatal("DNS 在线测试响应不应返回明文凭据") } + if !strings.Contains(testResponse.Body.String(), "test_report") || + !strings.Contains(testResponse.Body.String(), "创建记录") || + !strings.Contains(testResponse.Body.String(), "清理记录") { + t.Fatalf("DNS 在线测试响应应包含阶段报告:%s", testResponse.Body.String()) + } } func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) { @@ -193,7 +219,7 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) { payload := `{ "admin_username":"root-admin", "admin_email":"admin@example.test", - "admin_password":"secure-pass-123", + "admin_password":"secure1234", "server_port":8443, "email_provider":"mail-api", "email_endpoint":"https://mail.example.test/send", @@ -234,7 +260,7 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) { if err != nil { t.Fatalf("读取保存后的配置失败:%v", err) } - if strings.Contains(string(data), "secure-pass-123") { + if strings.Contains(string(data), "secure1234") { t.Fatal("配置文件不应保存管理员明文密码") } var saved config.Config @@ -275,7 +301,7 @@ func TestSetupApplyEncryptsNotificationCredentialsAndPersistsReference(t *testin payload := `{ "admin_username":"root-admin", "admin_email":"admin@example.test", - "admin_password":"secure-pass-123", + "admin_password":"secure1234", "server_port":8443, "email_http_enabled":true, "email_provider":"mail-api", @@ -368,7 +394,7 @@ func TestSetupApplyRejectsMissingNotificationCredentials(t *testing.T) { payload := `{ "admin_username":"root-admin", "admin_email":"admin@example.test", - "admin_password":"secure-pass-123", + "admin_password":"secure1234", "server_port":8443, "email_http_enabled":true, "email_endpoint":"https://mail.example.test", @@ -483,7 +509,7 @@ func TestSetupSaveFailureDoesNotConsumeDNSToken(t *testing.T) { Repository: &stubDomainRepository{}, SetupDNS: verifier, Firewall: firewallManager, IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil), }) - request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123"))) + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234"))) request.RemoteAddr = "127.0.0.1:53000" request.Header.Set("Content-Type", "application/json") response := httptest.NewRecorder() @@ -513,7 +539,7 @@ func TestSetupSaveFailureKeepsExistingFirewallRule(t *testing.T) { Repository: &stubDomainRepository{}, SetupDNS: &fakeSetupDNSVerifier{}, Firewall: firewallManager, IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil), }) - request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123"))) + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234"))) request.RemoteAddr = "127.0.0.1:53000" request.Header.Set("Content-Type", "application/json") response := httptest.NewRecorder() @@ -536,7 +562,7 @@ func TestSetupFirewallFailureDoesNotSaveOrConsumeToken(t *testing.T) { Repository: &stubDomainRepository{}, SetupDNS: verifier, Firewall: firewallManager, IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil), }) - request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123"))) + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234"))) request.RemoteAddr = "127.0.0.1:53000" request.Header.Set("Content-Type", "application/json") response := httptest.NewRecorder() @@ -552,6 +578,48 @@ func TestSetupFirewallFailureDoesNotSaveOrConsumeToken(t *testing.T) { } } +func TestSetupLateFailureDeletesNewNotificationCredentials(t *testing.T) { + baseDir := t.TempDir() + blockedParent := filepath.Join(baseDir, "blocked") + if err := os.WriteFile(blockedParent, []byte("blocked"), 0o600); err != nil { + t.Fatalf("create blocked path: %v", err) + } + secrets := &fakeSetupSecretWriter{} + firewallManager := &fakeFirewallManager{result: firewall.Result{ + Backend: "ufw", RuleName: "Scert Web TCP 8443", Port: 8443, Created: true, + }} + server := New(Dependencies{ + Config: config.Default(baseDir), ConfigPath: filepath.Join(blockedParent, "scert.json"), + Repository: &stubDomainRepository{}, SetupDNS: &fakeSetupDNSVerifier{}, Secrets: secrets, + Firewall: firewallManager, IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil), + }) + payload := strings.Replace(setupPayload(baseDir, "secure1234"), + `"server_port":8443,`, + `"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":"http-secret"}, + "email_smtp_enabled":true, + "email_smtp_host":"smtp.example.test", + "email_smtp_port":587, + "email_smtp_username":"smtp-user", + "email_smtp_password":"smtp-secret", + "email_smtp_mode":"starttls",`, 1) + 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.StatusInternalServerError { + t.Fatalf("late setup failure should return 500: %d %s", response.Code, response.Body.String()) + } + if len(secrets.deleted) != 2 || len(secrets.values) != 0 { + t.Fatalf("new notification credentials should be deleted: deleted=%v values=%v", secrets.deleted, secrets.values) + } +} + func setupPayload(baseDir, password string) string { return `{ "admin_username":"root-admin", @@ -578,7 +646,7 @@ func TestSetupCertificateFailureDoesNotSaveOrConsumeDNSToken(t *testing.T) { Repository: &stubDomainRepository{}, SetupDNS: verifier, IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, errors.New("模拟证书申请失败")), }) - request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123"))) + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234"))) request.RemoteAddr = "127.0.0.1:53000" request.Header.Set("Content-Type", "application/json") response := httptest.NewRecorder() @@ -609,7 +677,7 @@ func TestSetupCertificateFileValidationDoesNotSaveOrConsumeDNSToken(t *testing.T Repository: &stubDomainRepository{}, SetupDNS: verifier, IssueSetupCertificate: issuer, }) - request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123"))) + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234"))) request.RemoteAddr = "127.0.0.1:53000" request.Header.Set("Content-Type", "application/json") response := httptest.NewRecorder() @@ -634,7 +702,7 @@ func TestSetupWithPublicIPRejectsDNSAutomaticCertificate(t *testing.T) { Repository: &stubDomainRepository{}, SetupDNS: verifier, IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil), }) - payload := strings.Replace(setupPayload(baseDir, "secure-pass-123"), + payload := strings.Replace(setupPayload(baseDir, "secure1234"), `"web_hostname":"scert.example.test",`, `"web_hostname":"","web_public_ip":"192.0.2.10",`, 1) request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload)) @@ -667,7 +735,7 @@ func TestSetupFirewallFailureRollsBackIssuedCertificate(t *testing.T) { return certificate.RollbackSavedResource(context.Background(), saved) }, }) - request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123"))) + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234"))) request.RemoteAddr = "127.0.0.1:53000" request.Header.Set("Content-Type", "application/json") response := httptest.NewRecorder() diff --git a/backend/internal/notification/service.go b/backend/internal/notification/service.go index 67c5af6..51af458 100644 --- a/backend/internal/notification/service.go +++ b/backend/internal/notification/service.go @@ -6,6 +6,7 @@ import ( "crypto/hmac" "crypto/rand" "crypto/sha256" + "crypto/tls" "encoding/hex" "encoding/json" "errors" @@ -88,17 +89,18 @@ func (e *sessionExpiredError) Error() string { // Service 通过 HTTP 邮件 API 发送通知。 type Service struct { - config config.NotificationConfig - credentials CredentialReader - client HTTPDoer - now func() time.Time - requestID func() string - sleep func(context.Context, time.Duration) error + config config.NotificationConfig + credentials CredentialReader + client HTTPDoer + now func() time.Time + requestID func() string + sleep func(context.Context, time.Duration) error + smtpTLSConfig func(string) *tls.Config } // New 创建 HTTP 通知服务。SMTP 配置暂保留为兼容字段,当前发送器只执行 HTTP 通知。 func New(cfg config.NotificationConfig, credentials CredentialReader) *Service { - return &Service{ + service := &Service{ config: cfg, credentials: credentials, client: &http.Client{}, @@ -106,18 +108,19 @@ func New(cfg config.NotificationConfig, credentials CredentialReader) *Service { requestID: newRequestID, sleep: sleepContext, } + service.smtpTLSConfig = func(host string) *tls.Config { + return &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12} + } + return service } // Send 按配置发送通知;未启用任何通知通道时直接返回成功。 -func (s *Service) Send(ctx context.Context, event Event) error { +func (s *Service) sendHTTP(ctx context.Context, event Event) error { if s == nil { return errors.New("通知服务未初始化") } - if !s.config.HTTPEnabled && !s.config.SMTPEnabled { - return nil - } if !s.config.HTTPEnabled { - return errors.New("当前仅支持 HTTP 邮件通知,SMTP 通知发送器尚未接入") + return nil } if err := ctx.Err(); err != nil { return err @@ -272,7 +275,7 @@ func (s *Service) sendOnce(ctx context.Context, endpoint string, body []byte, cr func (s *Service) loginSession(ctx context.Context, credentials map[string]string) (sessionAuth, error) { account := credentialValue(credentials, "account", "username", "identifier") password := credentials["password"] - if account == "" || strings.TrimSpace(password) == "" { + if account == "" || password == "" { return sessionAuth{}, errors.New("HTTP 通知会话凭据必须包含账号和密码") } loginURL, err := notificationURL(s.config.Endpoint, s.config.HTTPLoginPath) @@ -321,7 +324,7 @@ func (s *Service) loginSession(ctx context.Context, credentials map[string]strin if strings.TrimSpace(envelope.ErrorMsg) == "" { return sessionAuth{}, fmt.Errorf("HTTP 通知登录失败,错误码 %d", *envelope.ErrorNo) } - return sessionAuth{}, fmt.Errorf("HTTP 通知登录失败,错误码 %d", *envelope.ErrorNo) + return sessionAuth{}, fmt.Errorf("HTTP 通知登录失败,错误码 %d:%s", *envelope.ErrorNo, strings.TrimSpace(envelope.ErrorMsg)) } cookies := make([]string, 0, len(response.Cookies())) csrf := "" diff --git a/backend/internal/notification/service_test.go b/backend/internal/notification/service_test.go index 0144188..89add14 100644 --- a/backend/internal/notification/service_test.go +++ b/backend/internal/notification/service_test.go @@ -271,3 +271,80 @@ func TestSendRefreshesExpiredSession(t *testing.T) { t.Fatalf("未使用刷新后的会话:%v", cookies) } } + +func TestSendRejectsEmptySessionPasswordWithoutTrimmingValidPassword(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + writer.WriteHeader(http.StatusInternalServerError) + })) + defer server.Close() + + cfg := newTestConfig(server.URL) + cfg.HTTPAuthMode = "session" + cfg.HTTPCredentialRef = "secret://mail-session" + service := New(cfg, credentialReaderStub{values: map[string]string{ + "account": "xuans", + "password": "", + }}) + err := service.Send(context.Background(), Event{Status: "success", Domain: "example.com"}) + if err == nil || !strings.Contains(err.Error(), "必须包含账号和密码") { + t.Fatalf("空密码应在发起登录请求前被拒绝:%v", err) + } +} + +func TestSessionLoginPreservesWhitespacePassword(t *testing.T) { + var loginPayload map[string]string + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path != "/api/login" { + writer.WriteHeader(http.StatusNoContent) + return + } + body, err := io.ReadAll(request.Body) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(body, &loginPayload); err != nil { + t.Fatal(err) + } + writer.Header().Add("Set-Cookie", "session=whitespace-session; Path=/; HttpOnly") + writer.Header().Set("Content-Type", "application/json; charset=utf-8") + _, _ = writer.Write([]byte(`{"errorNo":0,"errorMsg":""}`)) + })) + defer server.Close() + + cfg := newTestConfig(server.URL) + cfg.HTTPAuthMode = "session" + cfg.HTTPCredentialRef = "secret://mail-session" + service := New(cfg, credentialReaderStub{values: map[string]string{ + "account": "xuans", + "password": " test-password ", + }}) + if err := service.Send(context.Background(), Event{Status: "success", Domain: "example.com"}); err != nil { + t.Fatalf("保留空白密码的会话登录失败:%v", err) + } + if loginPayload["password"] != " test-password " { + t.Fatalf("密码不应被 TrimSpace:%q", loginPayload["password"]) + } +} + +func TestSessionLoginReturnsBusinessMessageWithoutCredentials(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Type", "application/json; charset=utf-8") + _, _ = writer.Write([]byte(`{"errorNo":403,"errorMsg":"账号或密码错误"}`)) + })) + defer server.Close() + + cfg := newTestConfig(server.URL) + cfg.HTTPAuthMode = "session" + cfg.HTTPCredentialRef = "secret://mail-session" + service := New(cfg, credentialReaderStub{values: map[string]string{ + "account": "xuans", + "password": "test-password", + }}) + err := service.Send(context.Background(), Event{Status: "success", Domain: "example.com"}) + if err == nil || !strings.Contains(err.Error(), "错误码 403") || !strings.Contains(err.Error(), "账号或密码错误") { + t.Fatalf("登录业务错误应包含安全诊断:%v", err) + } + if strings.Contains(err.Error(), "test-password") { + t.Fatalf("登录错误不得包含密码:%v", err) + } +} diff --git a/backend/internal/notification/smtp.go b/backend/internal/notification/smtp.go new file mode 100644 index 0000000..d93408a --- /dev/null +++ b/backend/internal/notification/smtp.go @@ -0,0 +1,228 @@ +package notification + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "mime" + "net" + "net/mail" + "net/smtp" + "strconv" + "strings" + "time" +) + +// Send 通过所有已启用的出站通道发送通知。 +func (s *Service) Send(ctx context.Context, event Event) error { + if s == nil { + return errors.New("通知服务未初始化") + } + if !s.config.HTTPEnabled && !s.config.SMTPEnabled { + return nil + } + if err := ctx.Err(); err != nil { + return err + } + var errs []error + if s.config.HTTPEnabled { + if err := s.sendHTTP(ctx, event); err != nil { + errs = append(errs, err) + } + } + if s.config.SMTPEnabled { + payload, err := s.buildPayload(event) + if err != nil { + errs = append(errs, err) + } else if err := s.sendSMTPWithRetry(ctx, payload); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +func (s *Service) sendSMTPWithRetry(ctx context.Context, payload mailPayload) error { + if strings.TrimSpace(s.config.SMTPHost) == "" { + return errors.New("SMTP 主机不能为空") + } + credentials, err := s.loadSMTPCredentials(ctx) + if err != nil { + return err + } + var lastErr error + for attempt := 0; attempt <= s.config.RetryCount; attempt++ { + if attempt > 0 { + interval := time.Duration(0) + if attempt-1 < len(s.config.RetryIntervalsSecs) { + interval = time.Duration(s.config.RetryIntervalsSecs[attempt-1]) * time.Second + } + if err := s.sleep(ctx, interval); err != nil { + return err + } + } + if err := s.sendSMTPOnce(ctx, payload, credentials); err == nil { + return nil + } else { + lastErr = err + } + } + return fmt.Errorf("发送 SMTP 通知失败,已重试 %d 次:%w", s.config.RetryCount, lastErr) +} + +func (s *Service) loadSMTPCredentials(ctx context.Context) (map[string]string, error) { + ref := strings.TrimSpace(s.config.SMTPCredentialRef) + if ref == "" { + return nil, nil + } + if s.credentials == nil { + return nil, errors.New("SMTP 通知凭据存储未配置") + } + values, err := s.credentials.Get(ctx, ref) + if err != nil { + return nil, fmt.Errorf("读取 SMTP 通知凭据失败:%w", err) + } + return values, nil +} + +func (s *Service) sendSMTPOnce(ctx context.Context, payload mailPayload, credentials map[string]string) error { + host := strings.TrimSpace(s.config.SMTPHost) + if host == "" { + return errors.New("SMTP 主机不能为空") + } + timeout := time.Duration(s.config.TimeoutSecs) * time.Second + if timeout < time.Second { + timeout = time.Second + } + address := net.JoinHostPort(strings.Trim(host, "[]"), strconv.Itoa(s.config.SMTPPort)) + conn, err := s.dialSMTP(ctx, address, host, s.config.SMTPMode, timeout) + if err != nil { + return fmt.Errorf("连接 SMTP 服务器失败:%w", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(timeout)) + client, err := smtp.NewClient(conn, host) + if err != nil { + return fmt.Errorf("初始化 SMTP 客户端失败:%w", err) + } + defer client.Close() + if s.config.SMTPMode == "starttls" { + tlsConfig := s.smtpTLSConfig(host) + if ok, _ := client.Extension("STARTTLS"); !ok { + return errors.New("SMTP 服务器不支持 STARTTLS") + } + if err := client.StartTLS(tlsConfig); err != nil { + return fmt.Errorf("建立 SMTP STARTTLS 连接失败:%w", err) + } + } + username := strings.TrimSpace(s.config.SMTPUsername) + if username == "" { + username = credentialValue(credentials, "username", "account", "email") + } + password := credentialValue(credentials, "password", "pass") + if username != "" { + if password == "" { + return errors.New("SMTP 凭据中缺少密码") + } + if s.config.SMTPMode == "plain" && !s.config.SMTPAllowPlaintextAuth { + return errors.New("SMTP 明文连接禁止认证,请启用 TLS 或明确允许明文认证") + } + if err := client.Auth(smtp.PlainAuth("", username, password, host)); err != nil { + return fmt.Errorf("SMTP 认证失败:%w", err) + } + } + recipients := make([]string, 0, len(payload.To)) + for _, item := range payload.To { + recipients = append(recipients, item.Email) + } + if err := client.Mail(payload.From.Email); err != nil { + return fmt.Errorf("设置 SMTP 发件人失败:%w", err) + } + for _, recipient := range recipients { + if err := client.Rcpt(recipient); err != nil { + return fmt.Errorf("设置 SMTP 收件人失败:%w", err) + } + } + writer, err := client.Data() + if err != nil { + return fmt.Errorf("打开 SMTP 邮件数据通道失败:%w", err) + } + if _, err := writer.Write(buildSMTPMessage(payload)); err != nil { + _ = writer.Close() + return fmt.Errorf("写入 SMTP 邮件内容失败:%w", err) + } + if err := writer.Close(); err != nil { + return fmt.Errorf("提交 SMTP 邮件失败:%w", err) + } + if err := client.Quit(); err != nil { + return fmt.Errorf("关闭 SMTP 会话失败:%w", err) + } + return nil +} + +func (s *Service) dialSMTP(ctx context.Context, address, host, mode string, timeout time.Duration) (net.Conn, error) { + dialer := &net.Dialer{Timeout: timeout} + conn, err := dialer.DialContext(ctx, "tcp", address) + if err != nil { + return nil, err + } + if mode != "implicit_tls" { + return conn, nil + } + tlsConfig := s.smtpTLSConfig + if tlsConfig == nil { + tlsConfig = func(serverName string) *tls.Config { + return &tls.Config{ServerName: serverName, MinVersion: tls.VersionTLS12} + } + } + tlsConn := tls.Client(conn, tlsConfig(host)) + if err := tlsConn.SetDeadline(time.Now().Add(timeout)); err != nil { + _ = conn.Close() + return nil, err + } + if err := tlsConn.HandshakeContext(ctx); err != nil { + _ = conn.Close() + return nil, err + } + _ = tlsConn.SetDeadline(time.Time{}) + return tlsConn, nil +} + +func buildSMTPMessage(payload mailPayload) []byte { + from := formatSMTPAddress(payload.From) + to := make([]string, 0, len(payload.To)) + for _, item := range payload.To { + to = append(to, formatSMTPAddress(item)) + } + subject := mime.QEncoding.Encode("UTF-8", payload.Subject) + content := payload.Text + content = strings.ReplaceAll(content, "\r\n", "\n") + content = strings.ReplaceAll(content, "\r", "\n") + content = strings.ReplaceAll(content, "\n", "\r\n") + if !strings.HasSuffix(content, "\r\n") { + content += "\r\n" + } + message := "From: " + from + "\r\n" + + "To: " + strings.Join(to, ", ") + "\r\n" + + "Subject: " + subject + "\r\n" + + "Date: " + time.Now().Format(time.RFC1123Z) + "\r\n" + + "MIME-Version: 1.0\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Content-Transfer-Encoding: 8bit\r\n\r\n" + content + return []byte(message) +} + +func formatSMTPAddress(value address) string { + parsed, err := mail.ParseAddress(value.Email) + if err != nil || parsed.Address == "" { + return value.Email + } + name := strings.TrimSpace(value.Name) + if name == "" { + name = parsed.Name + } + if name == "" { + return parsed.Address + } + return mime.QEncoding.Encode("UTF-8", name) + " <" + parsed.Address + ">" +} diff --git a/backend/internal/notification/smtp_test.go b/backend/internal/notification/smtp_test.go new file mode 100644 index 0000000..6269a2f --- /dev/null +++ b/backend/internal/notification/smtp_test.go @@ -0,0 +1,365 @@ +package notification + +import ( + "bufio" + "context" + "crypto/rand" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "io" + "math/big" + "net" + "strings" + "sync" + "testing" + "time" + + "git.pcux.cn/xuans/Scert/backend/internal/config" +) + +type smtpTestServer struct { + listener net.Listener + tlsConfig *tls.Config + implicitTLS bool + failMailOnce bool + rejectAuth bool + mu sync.Mutex + messages [][]byte + connections int +} + +func newSMTPTestServer(t *testing.T, implicitTLS, startTLS bool) *smtpTestServer { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("create SMTP test listener: %v", err) + } + server := &smtpTestServer{listener: listener, implicitTLS: implicitTLS} + if implicitTLS || startTLS { + server.tlsConfig = newSMTPTestTLSConfig(t) + } + go server.serve(startTLS) + t.Cleanup(func() { _ = listener.Close() }) + return server +} + +func (s *smtpTestServer) address() (string, int) { + address := s.listener.Addr().(*net.TCPAddr) + return address.IP.String(), address.Port +} + +func (s *smtpTestServer) serve(startTLS bool) { + for { + connection, err := s.listener.Accept() + if err != nil { + return + } + s.mu.Lock() + s.connections++ + s.mu.Unlock() + go s.handle(connection, startTLS) + } +} + +func (s *smtpTestServer) handle(connection net.Conn, startTLS bool) { + defer connection.Close() + if s.implicitTLS { + tlsConnection := tls.Server(connection, s.tlsConfig) + if err := tlsConnection.Handshake(); err != nil { + return + } + connection = tlsConnection + } + reader := bufio.NewReader(connection) + writeLine := func(value string) error { + _, err := io.WriteString(connection, value+"\r\n") + return err + } + if writeLine("220 smtp.test.local ESMTP") != nil { + return + } + for { + line, err := reader.ReadString('\n') + if err != nil { + return + } + command := strings.TrimSpace(line) + upper := strings.ToUpper(command) + switch { + case strings.HasPrefix(upper, "EHLO"), strings.HasPrefix(upper, "HELO"): + if writeLine("250-smtp.test.local") != nil { + return + } + if startTLS && writeLine("250-STARTTLS") != nil { + return + } + if writeLine("250 AUTH PLAIN") != nil { + return + } + case strings.HasPrefix(upper, "STARTTLS"): + if !startTLS || writeLine("220 ready for TLS") != nil { + return + } + tlsConnection := tls.Server(connection, s.tlsConfig) + if err := tlsConnection.Handshake(); err != nil { + return + } + connection = tlsConnection + reader = bufio.NewReader(connection) + case strings.HasPrefix(upper, "AUTH PLAIN"): + if s.rejectAuth { + if writeLine("535 authentication failed") != nil { + return + } + continue + } + if writeLine("235 authentication successful") != nil { + return + } + case strings.HasPrefix(upper, "MAIL FROM:"): + s.mu.Lock() + fail := s.failMailOnce + s.failMailOnce = false + s.mu.Unlock() + if fail { + if writeLine("451 temporary failure") != nil { + return + } + return + } + if writeLine("250 sender accepted") != nil { + return + } + case strings.HasPrefix(upper, "RCPT TO:"): + if writeLine("250 recipient accepted") != nil { + return + } + case upper == "DATA": + if writeLine("354 end with .") != nil { + return + } + var message strings.Builder + for { + dataLine, readErr := reader.ReadString('\n') + if readErr != nil { + return + } + if dataLine == ".\r\n" { + break + } + message.WriteString(dataLine) + } + s.mu.Lock() + s.messages = append(s.messages, []byte(message.String())) + s.mu.Unlock() + if writeLine("250 queued") != nil { + return + } + case upper == "QUIT": + _ = writeLine("221 closing connection") + return + default: + if writeLine("250 ok") != nil { + return + } + } + } +} + +func (s *smtpTestServer) clientTLSConfig(host string) *tls.Config { + s.mu.Lock() + defer s.mu.Unlock() + pool := x509.NewCertPool() + if len(s.tlsConfig.Certificates) == 0 || len(s.tlsConfig.Certificates[0].Certificate) == 0 { + return &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12} + } + pool.AppendCertsFromPEM(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: s.tlsConfig.Certificates[0].Certificate[0]})) + return &tls.Config{ServerName: host, RootCAs: pool, MinVersion: tls.VersionTLS12} +} + +func (s *smtpTestServer) message() []byte { + s.mu.Lock() + defer s.mu.Unlock() + if len(s.messages) == 0 { + return nil + } + return append([]byte(nil), s.messages[len(s.messages)-1]...) +} + +func newSMTPTestTLSConfig(t *testing.T) *tls.Config { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generate SMTP test key: %v", err) + } + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120)) + if err != nil { + t.Fatalf("generate SMTP test serial: %v", err) + } + template := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: "127.0.0.1"}, + DNSNames: []string{"smtp.test.local"}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + NotBefore: time.Now().Add(-time.Minute), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatalf("generate SMTP test certificate: %v", err) + } + certificate, err := tls.X509KeyPair( + pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), + pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}), + ) + if err != nil { + t.Fatalf("load SMTP test certificate: %v", err) + } + return &tls.Config{Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS12} +} + +func smtpTestConfig(host string, port int, mode string) config.NotificationConfig { + return config.NotificationConfig{ + SMTPEnabled: true, + SMTPHost: host, + SMTPPort: port, + SMTPUsername: "user", + SMTPCredentialRef: "secret://notification/smtp/test", + SMTPMode: mode, + TimeoutSecs: 2, + RetryCount: 0, + SenderName: "Scert", + SenderEmail: "sender@example.com", + Recipients: []string{"receiver@example.com"}, + } +} + +func TestSMTPRejectsPlainAuthenticationByDefault(t *testing.T) { + server := newSMTPTestServer(t, false, false) + host, port := server.address() + service := New(smtpTestConfig(host, port, "plain"), credentialReaderStub{values: map[string]string{ + "username": "user", + "password": "test-password", + }}) + + err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}) + if err == nil || !strings.Contains(err.Error(), "\u660e\u6587\u8fde\u63a5\u7981\u6b62\u8ba4\u8bc1") { + t.Fatalf("plain SMTP authentication should be rejected: %v", err) + } + if strings.Contains(err.Error(), "test-password") { + t.Fatalf("SMTP errors must not expose password: %v", err) + } +} + +func TestSMTPSendsUTF8WithAllowedPlainAuthentication(t *testing.T) { + server := newSMTPTestServer(t, false, false) + host, port := server.address() + cfg := smtpTestConfig(host, port, "plain") + cfg.SMTPAllowPlaintextAuth = true + service := New(cfg, credentialReaderStub{values: map[string]string{ + "username": "user", + "password": "test-password", + }}) + + if err := service.Send(context.Background(), Event{Type: "certificate_renewal", Status: "success", Domain: "example.test"}); err != nil { + t.Fatalf("send UTF-8 SMTP notification: %v", err) + } + message := string(server.message()) + if !strings.Contains(message, "Subject: =?UTF-8?") || !strings.Contains(message, "example.test") { + t.Fatalf("SMTP message was not generated correctly: %q", message) + } +} + +func TestSMTPStartTLS(t *testing.T) { + server := newSMTPTestServer(t, false, true) + host, port := server.address() + service := New(smtpTestConfig(host, port, "starttls"), credentialReaderStub{values: map[string]string{ + "username": "user", + "password": "test-password", + }}) + service.smtpTLSConfig = server.clientTLSConfig + + if err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}); err != nil { + t.Fatalf("send SMTP STARTTLS notification: %v", err) + } +} + +func TestSMTPImplicitTLS(t *testing.T) { + server := newSMTPTestServer(t, true, false) + host, port := server.address() + service := New(smtpTestConfig(host, port, "implicit_tls"), credentialReaderStub{values: map[string]string{ + "username": "user", + "password": "test-password", + }}) + service.smtpTLSConfig = server.clientTLSConfig + + if err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}); err != nil { + t.Fatalf("send SMTP implicit TLS notification: %v", err) + } +} + +func TestSMTPRetriesTemporaryFailure(t *testing.T) { + server := newSMTPTestServer(t, false, false) + server.failMailOnce = true + host, port := server.address() + cfg := smtpTestConfig(host, port, "plain") + cfg.SMTPAllowPlaintextAuth = true + cfg.RetryCount = 1 + cfg.RetryIntervalsSecs = []int{0} + service := New(cfg, credentialReaderStub{values: map[string]string{ + "username": "user", + "password": "test-password", + }}) + service.sleep = func(context.Context, time.Duration) error { return nil } + + if err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}); err != nil { + t.Fatalf("SMTP retry should recover from temporary failure: %v", err) + } + server.mu.Lock() + connections := server.connections + messages := len(server.messages) + server.mu.Unlock() + if connections < 2 || messages != 1 { + t.Fatalf("SMTP retry result is incorrect: connections=%d messages=%d", connections, messages) + } +} + +func TestSMTPAuthFailureDoesNotLeakPassword(t *testing.T) { + server := newSMTPTestServer(t, false, true) + server.rejectAuth = true + host, port := server.address() + service := New(smtpTestConfig(host, port, "starttls"), credentialReaderStub{values: map[string]string{ + "username": "user", + "password": "wrong-password", + }}) + service.smtpTLSConfig = server.clientTLSConfig + + err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}) + if err == nil || !strings.Contains(err.Error(), "\u8ba4\u8bc1\u5931\u8d25") { + t.Fatalf("SMTP authentication failure should be reported: %v", err) + } + if strings.Contains(err.Error(), "wrong-password") { + t.Fatalf("SMTP authentication errors must not expose password: %v", err) + } +} + +func TestSMTPRejectsMissingHost(t *testing.T) { + cfg := smtpTestConfig("", 587, "starttls") + service := New(cfg, nil) + err := service.Send(context.Background(), Event{Type: "certificate_issue", Status: "success", Domain: "example.com"}) + if err == nil || !strings.Contains(err.Error(), "SMTP \u4e3b\u673a\u4e0d\u80fd\u4e3a\u7a7a") { + t.Fatalf("missing SMTP host should return a clear error: %v", err) + } +} + +func TestSMTPAddressFormatting(t *testing.T) { + value := formatSMTPAddress(address{Name: "\u7ba1\u7406\u670d\u52a1", Email: "admin@example.com"}) + if !strings.Contains(value, "admin@example.com") || !strings.Contains(value, "=?UTF-8?") { + t.Fatalf("SMTP address encoding is incorrect: %s", value) + } +} diff --git a/backend/internal/passwordpolicy/password.go b/backend/internal/passwordpolicy/password.go index 1d9d882..b491006 100644 --- a/backend/internal/passwordpolicy/password.go +++ b/backend/internal/passwordpolicy/password.go @@ -9,7 +9,7 @@ import ( const ( MinLength = 8 - MaxLength = 128 + MaxLength = 12 ) func Validate(password, username string) error { diff --git a/backend/internal/passwordpolicy/password_test.go b/backend/internal/passwordpolicy/password_test.go index b0214df..b19cd03 100644 --- a/backend/internal/passwordpolicy/password_test.go +++ b/backend/internal/passwordpolicy/password_test.go @@ -13,6 +13,8 @@ func TestValidate(t *testing.T) { wantErr bool }{ {name: "合法密码", password: "Password123", username: "admin"}, + {name: "length at max", password: "Pass12345678", username: "admin"}, + {name: "length above max", password: "Pass123456789", username: "admin", wantErr: true}, {name: "支持中文字符", password: "安全密码2026", username: "admin"}, {name: "长度不足", password: "Pass123", username: "admin", wantErr: true}, {name: "缺少数字", password: "PasswordOnly", username: "admin", wantErr: true}, diff --git a/backend/internal/servicehost/linux.go b/backend/internal/servicehost/linux.go new file mode 100644 index 0000000..434900b --- /dev/null +++ b/backend/internal/servicehost/linux.go @@ -0,0 +1,81 @@ +//go:build linux + +package servicehost + +import ( + "context" + "os/exec" +) + +func Install(ctx context.Context, options Options) error { + o, err := options.normalized() + if err != nil { + return err + } + if err := runSystemctl(ctx, "enable", o.Name); err != nil { + return commandError("注册", err) + } + return nil +} + +func Uninstall(ctx context.Context, name string) error { + if err := validateName(name); err != nil { + return err + } + if err := runSystemctl(ctx, "disable", name); err != nil { + return commandError("取消注册", err) + } + return nil +} + +func Start(ctx context.Context, name string) error { + if err := validateName(name); err != nil { + return err + } + if err := runSystemctl(ctx, "start", name); err != nil { + return commandError("启动", err) + } + return nil +} + +func Stop(ctx context.Context, name string) error { + if err := validateName(name); err != nil { + return err + } + if err := runSystemctl(ctx, "stop", name); err != nil { + return commandError("停止", err) + } + return nil +} + +func runSystemctl(ctx context.Context, args ...string) error { + command := exec.CommandContext(ctx, "systemctl", args...) + output, err := command.CombinedOutput() + if err != nil { + return &commandFailure{output: string(output), err: err} + } + return nil +} + +type commandFailure struct { + output string + err error +} + +func (e *commandFailure) Error() string { + if e.err != nil { + return e.output + ": " + e.err.Error() + } + return e.output +} + +func (e *commandFailure) Unwrap() error { return e.err } + +func validateName(name string) error { + if name == "" || name == "." || name == ".." { + return ErrInvalidName + } + return nil +} + +var ErrInvalidName = &commandFailure{output: "服务名称无效"} diff --git a/backend/internal/servicehost/service.go b/backend/internal/servicehost/service.go new file mode 100644 index 0000000..b3d7480 --- /dev/null +++ b/backend/internal/servicehost/service.go @@ -0,0 +1,65 @@ +package servicehost + +import ( + "errors" + "fmt" + "path/filepath" + "strings" +) + +type Options struct { + Name string + DisplayName string + Description string + Executable string + ConfigPath string + WorkDir string +} + +func (o Options) Validate() error { + if strings.TrimSpace(o.Name) == "" { + return errors.New("服务名称不能为空") + } + if strings.ContainsAny(o.Name, `/\\`) { + return errors.New("服务名称不能包含路径分隔符") + } + if strings.TrimSpace(o.Executable) == "" { + return errors.New("服务程序路径不能为空") + } + if filepath.Clean(o.Executable) == "." { + return errors.New("服务程序路径无效") + } + if strings.TrimSpace(o.ConfigPath) == "" { + return errors.New("配置文件路径不能为空") + } + if filepath.Clean(o.ConfigPath) == "." { + return errors.New("配置文件路径无效") + } + if strings.TrimSpace(o.WorkDir) == "" { + return errors.New("服务工作目录不能为空") + } + return nil +} + +func (o Options) normalized() (Options, error) { + if err := o.Validate(); err != nil { + return Options{}, err + } + o.Name = strings.TrimSpace(o.Name) + o.DisplayName = strings.TrimSpace(o.DisplayName) + if o.DisplayName == "" { + o.DisplayName = o.Name + } + o.Description = strings.TrimSpace(o.Description) + if o.Description == "" { + o.Description = o.DisplayName + } + o.Executable = filepath.Clean(strings.TrimSpace(o.Executable)) + o.ConfigPath = filepath.Clean(strings.TrimSpace(o.ConfigPath)) + o.WorkDir = filepath.Clean(strings.TrimSpace(o.WorkDir)) + return o, nil +} + +func commandError(action string, err error) error { + return fmt.Errorf("%s服务失败:%w", action, err) +} diff --git a/backend/internal/servicehost/service_test.go b/backend/internal/servicehost/service_test.go new file mode 100644 index 0000000..3285ceb --- /dev/null +++ b/backend/internal/servicehost/service_test.go @@ -0,0 +1,47 @@ +package servicehost + +import ( + "path/filepath" + "strings" + "testing" +) + +func TestOptionsValidate(t *testing.T) { + base := Options{ + Name: "Scert", + Executable: filepath.Join("C:", "scert.exe"), + ConfigPath: filepath.Join("C:", "scert", "scert.json"), + WorkDir: filepath.Join("C:", "scert"), + } + if err := base.Validate(); err != nil { + t.Fatalf("有效服务配置不应失败:%v", err) + } + for name, mutate := range map[string]func(*Options){ + "名称为空": func(o *Options) { o.Name = "" }, + "名称含路径": func(o *Options) { o.Name = "a/b" }, + "程序路径为空": func(o *Options) { o.Executable = "" }, + "配置路径为空": func(o *Options) { o.ConfigPath = "" }, + "工作目录为空": func(o *Options) { o.WorkDir = "" }, + } { + item := base + mutate(&item) + if err := item.Validate(); err == nil { + t.Errorf("%s时应校验失败", name) + } + } +} + +func TestOptionsNormalizedDefaultsDisplayText(t *testing.T) { + item, err := (Options{ + Name: " Scert ", Executable: "scert.exe", ConfigPath: "scert.json", WorkDir: filepath.Join("C:", "scert"), + }).normalized() + if err != nil { + t.Fatalf("规范化服务配置失败:%v", err) + } + if item.DisplayName != "Scert" || item.Description != "Scert" { + t.Fatalf("服务显示信息默认值错误:%+v", item) + } + if strings.TrimSpace(item.Executable) == "" { + t.Fatal("规范化后程序路径不能为空") + } +} diff --git a/backend/internal/servicehost/unsupported.go b/backend/internal/servicehost/unsupported.go new file mode 100644 index 0000000..3e35e41 --- /dev/null +++ b/backend/internal/servicehost/unsupported.go @@ -0,0 +1,15 @@ +//go:build !windows && !linux + +package servicehost + +import ( + "context" + "errors" +) + +var ErrUnsupported = errors.New("当前操作系统不支持系统服务管理") + +func Install(_ context.Context, _ Options) error { return ErrUnsupported } +func Uninstall(_ context.Context, _ string) error { return ErrUnsupported } +func Start(_ context.Context, _ string) error { return ErrUnsupported } +func Stop(_ context.Context, _ string) error { return ErrUnsupported } diff --git a/backend/internal/servicehost/windows.go b/backend/internal/servicehost/windows.go new file mode 100644 index 0000000..f18a80b --- /dev/null +++ b/backend/internal/servicehost/windows.go @@ -0,0 +1,90 @@ +//go:build windows + +package servicehost + +import ( + "context" + "os/exec" + "strconv" +) + +func Install(ctx context.Context, options Options) error { + o, err := options.normalized() + if err != nil { + return err + } + binPath := strconv.Quote(o.Executable) + " --config " + strconv.Quote(o.ConfigPath) + " serve" + if err := runSC(ctx, "create", o.Name, "binPath=", binPath, "start=", "auto", "DisplayName=", o.DisplayName); err != nil { + return commandError("安装", err) + } + if err := runSC(ctx, "description", o.Name, o.Description); err != nil { + return commandError("写入描述", err) + } + return nil +} + +func Uninstall(ctx context.Context, name string) error { + if name == "" { + return commandError("卸载", ErrInvalidName) + } + if err := runSC(ctx, "stop", name); err != nil { + // 服务未运行时允许继续删除。 + _ = err + } + if err := runSC(ctx, "delete", name); err != nil { + return commandError("卸载", err) + } + return nil +} + +func Start(ctx context.Context, name string) error { + if err := validateName(name); err != nil { + return err + } + if err := runSC(ctx, "start", name); err != nil { + return commandError("启动", err) + } + return nil +} + +func Stop(ctx context.Context, name string) error { + if err := validateName(name); err != nil { + return err + } + if err := runSC(ctx, "stop", name); err != nil { + return commandError("停止", err) + } + return nil +} + +func runSC(ctx context.Context, args ...string) error { + command := exec.CommandContext(ctx, "sc.exe", args...) + output, err := command.CombinedOutput() + if err != nil { + return &commandFailure{output: string(output), err: err} + } + return nil +} + +var ErrInvalidName = &commandFailure{output: "服务名称无效"} + +type commandFailure struct { + output string + err error +} + +func (e *commandFailure) Error() string { + if e.err != nil { + return e.output + ": " + e.err.Error() + } + return e.output +} + +func (e *commandFailure) Unwrap() error { return e.err } + +func validateName(name string) error { + if name == "" || name == "." || name == ".." { + return ErrInvalidName + } + return nil +} diff --git a/backend/internal/setup/dns_verification.go b/backend/internal/setup/dns_verification.go index 61ca70c..7464c0f 100644 --- a/backend/internal/setup/dns_verification.go +++ b/backend/internal/setup/dns_verification.go @@ -16,7 +16,37 @@ import ( const dnsVerificationLifetime = 15 * time.Minute type DNSCredentialTester interface { - Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) error + Verify(ctx context.Context, providerID, testDomain string, credentials map[string]string) (DNSVerificationReport, error) +} + +type DNSVerificationStage struct { + Name string `json:"name"` + Status string `json:"status"` + Message string `json:"message"` +} + +type DNSVerificationReport struct { + RecordName string `json:"record_name"` + Stages []DNSVerificationStage `json:"stages"` +} + +type DNSVerificationError struct { + Report DNSVerificationReport + Err error +} + +func (e *DNSVerificationError) Error() string { + if e == nil || e.Err == nil { + return "DNS API 在线验证失败" + } + return e.Err.Error() +} + +func (e *DNSVerificationError) Unwrap() error { + if e == nil { + return nil + } + return e.Err } type SecretWriter interface { @@ -33,6 +63,7 @@ type DNSVerificationResult struct { CredentialRef string VerificationToken string ExpiresAt time.Time + TestReport DNSVerificationReport } type dnsVerificationSession struct { @@ -69,15 +100,20 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati if !domain.IsValidName(testDomain) { return DNSVerificationResult{}, fmt.Errorf("DNS 测试域名格式无效:%s", testDomain) } - if err := m.tester.Verify(ctx, providerID, testDomain, input.Credentials); err != nil { - return DNSVerificationResult{}, err + normalizedCredentials := normalizeCredentials(input.Credentials) + testReport, err := m.tester.Verify(ctx, providerID, testDomain, normalizedCredentials) + if err != nil { + return DNSVerificationResult{TestReport: testReport}, &DNSVerificationError{ + Report: testReport, + Err: err, + } } credentialID, err := secureToken(18) if err != nil { return DNSVerificationResult{}, fmt.Errorf("生成 DNS 凭据引用失败:%w", err) } credentialRef := fmt.Sprintf("secret://dns/%s/%s", providerID, credentialID) - if err := m.store.Put(ctx, credentialRef, input.Credentials); err != nil { + if err := m.store.Put(ctx, credentialRef, normalizedCredentials); err != nil { return DNSVerificationResult{}, fmt.Errorf("加密保存 DNS 凭据失败:%w", err) } verificationToken, err := secureToken(32) @@ -94,6 +130,7 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati m.mu.Unlock() return DNSVerificationResult{ CredentialRef: credentialRef, VerificationToken: verificationToken, ExpiresAt: expiresAt, + TestReport: testReport, }, nil } @@ -140,6 +177,17 @@ func (m *DNSVerificationManager) clearExpiredLocked(now time.Time) { } } +func normalizeCredentials(credentials map[string]string) map[string]string { + if credentials == nil { + return nil + } + normalized := make(map[string]string, len(credentials)) + for key, value := range credentials { + normalized[strings.TrimSpace(key)] = strings.TrimSpace(value) + } + return normalized +} + func normalizeTestDomain(value string) string { return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), ".")) } diff --git a/backend/internal/setup/dns_verification_test.go b/backend/internal/setup/dns_verification_test.go index ad05353..cda995f 100644 --- a/backend/internal/setup/dns_verification_test.go +++ b/backend/internal/setup/dns_verification_test.go @@ -11,8 +11,8 @@ type fakeDNSTester struct { err error } -func (f fakeDNSTester) Verify(context.Context, string, string, map[string]string) error { - return f.err +func (f fakeDNSTester) Verify(context.Context, string, string, map[string]string) (DNSVerificationReport, error) { + return DNSVerificationReport{}, f.err } type memorySecretWriter struct { @@ -105,3 +105,38 @@ func TestDNSVerificationManagerDoesNotStoreFailedCredential(t *testing.T) { t.Fatal("DNS 测试失败时不应保存凭据") } } + +type recordingDNSTester struct { + credentials map[string]string +} + +func (f *recordingDNSTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) (DNSVerificationReport, error) { + f.credentials = credentials + return DNSVerificationReport{}, nil +} + +func TestDNSVerificationManagerNormalizesCredentialCopyBeforeTestingAndStoring(t *testing.T) { + store := &memorySecretWriter{} + tester := &recordingDNSTester{} + manager := NewDNSVerificationManager(tester, store) + inputCredentials := map[string]string{" api_token ": " secret-token "} + result, err := manager.Verify(t.Context(), DNSVerificationInput{ + ProviderID: "cloudflare", TestDomain: "example.com", Credentials: inputCredentials, + }) + if err != nil { + t.Fatalf("DNS 在线验证失败:%v", err) + } + if tester.credentials["api_token"] != "secret-token" { + t.Fatalf("传给测试器的凭据未规范化:%v", tester.credentials) + } + if _, ok := tester.credentials[" api_token "]; ok { + t.Fatal("测试器不应收到带首尾空格的凭据键") + } + stored := store.values[result.CredentialRef] + if stored["api_token"] != "secret-token" { + t.Fatalf("保存的凭据未规范化:%v", stored) + } + if inputCredentials[" api_token "] != " secret-token " { + t.Fatal("规范化过程不应修改调用方的原始凭据 Map") + } +} diff --git a/backend/internal/setup/setup.go b/backend/internal/setup/setup.go index b13c57b..8f2dc94 100644 --- a/backend/internal/setup/setup.go +++ b/backend/internal/setup/setup.go @@ -18,6 +18,14 @@ type Input struct { AdminPassword string ServerPort int EmailHTTPEnabled bool + EmailSMTPEnabled bool + EmailSMTPHost string + EmailSMTPPort int + EmailSMTPUsername string + EmailSMTPPassword string + EmailSMTPCredentialRef string + EmailSMTPMode string + EmailSMTPAllowPlaintextAuth bool EmailProvider string EmailEndpoint string EmailHTTPPath string @@ -118,7 +126,17 @@ func Apply(cfg *config.Config, input Input) error { cfg.DNS.CredentialRef = strings.TrimSpace(input.DNSCredentialRef) cfg.DNS.VerificationState = "verified" cfg.Notification.HTTPEnabled = input.EmailHTTPEnabled - cfg.Notification.SMTPEnabled = false + cfg.Notification.SMTPEnabled = input.EmailSMTPEnabled + cfg.Notification.SMTPHost = strings.TrimSpace(input.EmailSMTPHost) + if input.EmailSMTPPort != 0 { + cfg.Notification.SMTPPort = input.EmailSMTPPort + } + cfg.Notification.SMTPUsername = strings.TrimSpace(input.EmailSMTPUsername) + cfg.Notification.SMTPCredentialRef = strings.TrimSpace(input.EmailSMTPCredentialRef) + if strings.TrimSpace(input.EmailSMTPMode) != "" { + cfg.Notification.SMTPMode = strings.TrimSpace(input.EmailSMTPMode) + } + cfg.Notification.SMTPAllowPlaintextAuth = input.EmailSMTPAllowPlaintextAuth cfg.Notification.Provider = strings.TrimSpace(input.EmailProvider) cfg.Notification.Endpoint = strings.TrimSpace(input.EmailEndpoint) if strings.TrimSpace(input.EmailHTTPPath) != "" { @@ -162,6 +180,9 @@ func Apply(cfg *config.Config, input Input) error { cfg.Notification.Recipients = []string{adminEmail} } cfg.SetupReady = true + if cfg.Notification.SMTPEnabled && strings.TrimSpace(cfg.Notification.SMTPCredentialRef) == "" { + return fmt.Errorf("启用 SMTP 通知后必须配置加密凭据引用") + } return cfg.Validate() } diff --git a/backend/service/handler_test.go b/backend/service/handler_test.go new file mode 100644 index 0000000..718476e --- /dev/null +++ b/backend/service/handler_test.go @@ -0,0 +1,17 @@ +package service + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestHandlerReturnsServiceUnavailableWhenRuntimeIsNil(t *testing.T) { + var runtime *Runtime + request := httptest.NewRequest(http.MethodGet, "/healthz", nil) + response := httptest.NewRecorder() + runtime.Handler().ServeHTTP(response, request) + if response.Code != http.StatusServiceUnavailable { + t.Fatalf("空运行时状态码错误:%d", response.Code) + } +} diff --git a/backend/service/runtime.go b/backend/service/runtime.go new file mode 100644 index 0000000..0cf10d4 --- /dev/null +++ b/backend/service/runtime.go @@ -0,0 +1,90 @@ +package service + +import ( + "context" + "errors" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + + "git.pcux.cn/xuans/Scert/backend/internal/app" + "git.pcux.cn/xuans/Scert/backend/internal/config" +) + +type Runtime struct { + core *app.App + cancel context.CancelFunc +} + +func Open(configPath, baseDir string) (*Runtime, error) { + configPath = strings.TrimSpace(configPath) + baseDir = strings.TrimSpace(baseDir) + if configPath == "" { + configPath = filepath.Join(defaultPaths(baseDir).Config, "scert.json") + } + if baseDir == "" { + baseDir = filepath.Dir(filepath.Dir(configPath)) + } + + cfg, err := config.Load(configPath) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + cfg = defaultConfig(baseDir) + } + + ctx, cancel := context.WithCancel(context.Background()) + core, err := app.NewWithConfigPath(ctx, cfg, configPath) + if err != nil { + cancel() + return nil, err + } + if core.Renewal != nil && cfg.SetupReady { + core.Renewal.Start(ctx) + } + return &Runtime{core: core, cancel: cancel}, nil +} + +func (r *Runtime) Handler() http.Handler { + if r == nil || r.core == nil || r.core.HTTP == nil { + return http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { + http.Error(writer, "Scert 核心服务未初始化", http.StatusServiceUnavailable) + }) + } + return r.core.HTTP.Handler() +} + +func (r *Runtime) Close() error { + if r == nil { + return nil + } + if r.cancel != nil { + r.cancel() + } + if r.core != nil { + return r.core.Close() + } + return nil +} + +func defaultConfig(baseDir string) config.Config { + cfg := config.Default(baseDir) + if runtime.GOOS == "linux" && strings.TrimSpace(baseDir) != "" { + install := filepath.Join(baseDir, "Scert") + cfg.Paths.Install = install + cfg.Paths.Certificate = filepath.Join(install, "ssl") + cfg.Paths.Config = filepath.Join(install, "config") + cfg.Paths.Data = filepath.Join(install, "data") + cfg.Paths.Log = filepath.Join(install, "logs") + cfg.Paths.Backup = filepath.Join(install, "backups") + cfg.Database.DSN = filepath.Join(cfg.Paths.Data, "scert.db") + } + return cfg +} + +func defaultPaths(baseDir string) config.PathsConfig { + return defaultConfig(baseDir).Paths +} diff --git a/backend/service/runtime_test.go b/backend/service/runtime_test.go new file mode 100644 index 0000000..6123034 --- /dev/null +++ b/backend/service/runtime_test.go @@ -0,0 +1,68 @@ +package service + +import ( + "net/http" + "os" + "path/filepath" + "testing" +) + +func TestOpenCreatesUninitializedRuntime(t *testing.T) { + baseDir := t.TempDir() + runtime, err := Open(filepath.Join(baseDir, "config", "scert.json"), baseDir) + if err != nil { + t.Fatalf("打开桌面核心服务失败:%v", err) + } + defer runtime.Close() + + request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1/api/v1/setup/status", nil) + if err != nil { + t.Fatal(err) + } + request.RemoteAddr = "127.0.0.1:1234" + response := newRecordingResponse() + runtime.Handler().ServeHTTP(response, request) + if response.status != http.StatusOK { + t.Fatalf("初始化状态接口状态码错误:%d,响应:%s", response.status, response.body) + } +} + +func TestOpenRejectsInvalidConfiguration(t *testing.T) { + baseDir := t.TempDir() + configPath := filepath.Join(baseDir, "config", "scert.json") + if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(configPath, []byte("{invalid"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := Open(configPath, baseDir); err == nil { + t.Fatal("无效配置不应打开成功") + } +} + +type recordingResponse struct { + header http.Header + status int + body string +} + +func newRecordingResponse() *recordingResponse { + return &recordingResponse{header: make(http.Header)} +} + +func (r *recordingResponse) Header() http.Header { + return r.header +} + +func (r *recordingResponse) WriteHeader(status int) { + r.status = status +} + +func (r *recordingResponse) Write(body []byte) (int, error) { + if r.status == 0 { + r.status = http.StatusOK + } + r.body += string(body) + return len(body), nil +} diff --git a/deploy/README.md b/deploy/README.md index 4ba73a4..1725a93 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,6 +9,9 @@ deploy/ ├── install-linux.sh ├── scert ├── scert-admin +├── web/ +│ ├── index.html +│ └── assets/ └── systemd/ ├── Scert.service ├── Scert-admin.service @@ -37,8 +40,8 @@ sudo ./install-linux.sh --source-dir /tmp/scert-linux-amd64 1. 检查 Linux、root 权限、`systemctl` 和安装产物。 2. 创建 `Scert` 系统用户和同名系统用户组,禁止交互式登录。 -3. 创建 `/scert`、`/scert/conf`、`/scert/data`、`/scert/log`、`/scert/backups`、`/scert/docs` 和证书目录。 -4. 安装 `scert`、`scert-admin` 以及两个 systemd unit。 +3. 创建 `/scert`、`/scert/conf`、`/scert/data`、`/scert/log`、`/scert/backups`、`/scert/docs`、`/scert/web` 和证书目录。 +4. 安装 `scert`、`scert-admin`、Web 静态资源以及两个 systemd unit。 5. 设置安装目录、服务目录和配置目录权限,防止 `Scert` 运行用户替换 root 所有的程序文件。 6. 为证书根目录生成 systemd drop-in,并执行一次 `systemctl daemon-reload`。 @@ -64,9 +67,99 @@ systemctl stop Scert-admin ## 参数说明 -- `--source-dir`:包含两个 Linux 可执行文件的目录,默认是安装器所在目录。 +- `--source-dir`:包含两个 Linux 可执行文件和 `web/index.html` 的目录,默认是安装器所在目录。 - `--certificate-dir`:证书根目录参数,默认 `/ssl`。安装器会创建该目录,写入 `/scert/conf/installation.json`,并生成对应的 `Scert.service.d/10-certificate-path.conf`。首次初始化会读取该记录作为证书目录默认值。 Linux 安装目录当前固定为 `/scert`。自定义证书根目录必须是规范化的安全绝对路径,只允许字母、数字、点、下划线、连字符和斜杠,不允许空格、`..` 路径片段、符号链接、受保护系统目录或 `/scert` 下的路径;`/var` 下仅允许 `/var/lib/scert` 专用目录。 安装器是文件部署阶段,不负责替代首次初始化向导,也不代替真实 ACME 申请和远程部署验收。 + +## 开发阶段反向代理部署 + +开发阶段可以使用测试域名 `web.xuans.com` 验证 Web 页面和反向代理链路。推荐让 Scert 只监听本机端口 `9003`,由 Nginx 对外提供 HTTPS: + +```text +公网 HTTPS 443 + ↓ +Nginx + ↓ https://127.0.0.1:9003 +Scert +``` + +对应配置为: + +```json +{ + "server": { + "host": "127.0.0.1", + "port": 9003, + "https_mode": "proxy" + } +} +``` + +Nginx 示例: + +```nginx +server { + listen 443 ssl http2; + server_name web.xuans.com; + + ssl_certificate /etc/letsencrypt/live/web.xuans.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/web.xuans.com/privkey.pem; + + location / { + proxy_pass https://127.0.0.1:9003; + proxy_ssl_server_name on; + proxy_ssl_name web.xuans.com; + proxy_ssl_verify off; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + } +} +``` + +如果需要 HTTP 自动跳转,再配置并开放 `80`;正常访问只需开放公网 `443`。`9003` 仅供本机 Nginx 使用,不应加入公网防火墙规则。端口可以在配置文件的 `server.port` 修改,修改后需要重启 Scert;如果改为直接对外监听,则还需要同步调整防火墙和安全组规则。 + +`web.xuans.com` 仅用于开发阶段测试,不能作为生产环境证书、DNS、ACME 或最终 HTTPS 验收依据。 + +## Windows 部署 + +Windows 发布目录应包含: + +```text +scert.exe +scert-admin.exe +install-windows.ps1 +``` + +使用管理员 PowerShell 执行: + +```powershell +powershell -ExecutionPolicy Bypass -File .\install-windows.ps1 -SourceDirectory . +``` + +默认目录: + +- 程序目录:`C:\Program Files\Scert` +- 配置和运行数据目录:`C:\ProgramData\Scert` +- 证书目录:`C:\ProgramData\Scert\ssl` + +安装器会检查 Windows、管理员权限、`sc.exe`、`icacls.exe` 和两个程序产物;创建配置、数据、日志、备份、文档、运行时和证书目录;设置 Windows ACL;使用 `LocalService` 身份注册 `Scert` 与 `Scert-admin` 服务;并写入不含凭据的安装记录。 + +安装器不会删除或覆盖已有配置、数据库、证书和备份,不会启动或重启服务,也不会创建公网防火墙规则。`Scert` 注册为自动启动,`Scert-admin` 注册为手动启动;只有确需密码重置时才应由管理员启动 `Scert-admin`,完成后立即停止。 + +自定义目录示例: + +```powershell +powershell -ExecutionPolicy Bypass -File .\install-windows.ps1 ` + -SourceDirectory D:\release\Scert\windows-amd64 ` + -InstallDirectory D:\Apps\Scert ` + -DataDirectory D:\ScertData ` + -CertificateDirectory D:\ScertCertificates +``` + +Windows Service 实机安装、开机启动、停止、升级和 ACL 仍需在授权 Windows 主机上验收。 diff --git a/deploy/install-linux.sh b/deploy/install-linux.sh index d676ffd..848eb5a 100644 --- a/deploy/install-linux.sh +++ b/deploy/install-linux.sh @@ -113,6 +113,7 @@ validate_managed_paths() { "$INSTALL_DIR/log" \ "$INSTALL_DIR/backups" \ "$INSTALL_DIR/docs" \ + "$INSTALL_DIR/web" \ "$INSTALL_DIR/scert" \ "$INSTALL_DIR/scert-admin" \ "$INSTALL_METADATA_FILE" \ @@ -130,7 +131,7 @@ validate_environment() { [[ "$(uname -s)" == "Linux" ]] || fail "此安装器只支持 Linux" [[ "$(id -u)" -eq 0 ]] || fail "请使用 root 或 sudo 运行安装器" local command_name - for command_name in install systemctl getent groupadd useradd id chmod chown cut grep readlink; do + for command_name in install systemctl getent groupadd useradd id chmod chown cut grep readlink find; do command -v "$command_name" >/dev/null 2>&1 || fail "找不到系统命令:$command_name" done nologin_shell="$(command -v nologin || true)" @@ -147,6 +148,7 @@ validate_artifacts() { [[ -f "$source_dir/$artifact" ]] || fail "安装产物不存在:$source_dir/$artifact" [[ -x "$source_dir/$artifact" ]] || fail "安装产物不可执行:$source_dir/$artifact" done + [[ -f "$source_dir/web/index.html" ]] || fail "缺少前端入口文件:$source_dir/web/index.html" [[ -f "$SCRIPT_DIR/systemd/Scert.service" ]] || fail "缺少 Scert systemd unit" [[ -f "$SCRIPT_DIR/systemd/Scert-admin.service" ]] || fail "缺少 Scert-admin systemd unit" [[ -f "$SCRIPT_DIR/systemd/Scert-admin服务管理说明.md" ]] || fail "缺少 Scert-admin 服务管理说明" @@ -184,6 +186,7 @@ ensure_service_account() { create_directories() { install -d -o root -g "$SERVICE_GROUP" -m 0750 "$INSTALL_DIR" install -d -o root -g root -m 0755 "$INSTALL_DIR/docs" + install -d -o root -g root -m 0755 "$INSTALL_DIR/web" install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 \ "$INSTALL_DIR/conf" \ "$INSTALL_DIR/data" \ @@ -217,6 +220,12 @@ install_binaries() { install -o root -g root -m 0755 "$source_dir/scert-admin" "$INSTALL_DIR/scert-admin" } +install_web() { + cp -a "$source_dir/web/." "$INSTALL_DIR/web/" + find "$INSTALL_DIR/web" -type d -exec chmod 0755 {} + + find "$INSTALL_DIR/web" -type f -exec chown root:root {} + -exec chmod 0644 {} + +} + install_service_files() { install -o root -g root -m 0644 "$SCRIPT_DIR/systemd/Scert.service" "$SERVICE_DIR/Scert.service" install -o root -g root -m 0644 "$SCRIPT_DIR/systemd/Scert-admin.service" "$SERVICE_DIR/Scert-admin.service" @@ -269,6 +278,7 @@ main() { create_directories write_install_metadata install_binaries + install_web install_service_files reload_systemd print_completion diff --git a/deploy/install-windows.ps1 b/deploy/install-windows.ps1 new file mode 100644 index 0000000..fb7a03e --- /dev/null +++ b/deploy/install-windows.ps1 @@ -0,0 +1,192 @@ +[CmdletBinding()] +param( + [string]$SourceDirectory = "", + [string]$InstallDirectory = (Join-Path $env:ProgramFiles "Scert"), + [string]$DataDirectory = (Join-Path $env:ProgramData "Scert"), + [string]$CertificateDirectory = (Join-Path $env:ProgramData "Scert\ssl"), + [ValidatePattern("^[A-Za-z0-9_.-]+$")] + [string]$ServiceName = "Scert", + [ValidatePattern("^[A-Za-z0-9_.-]+$")] + [string]$AdminServiceName = "Scert-admin" +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Definition +if ([string]::IsNullOrWhiteSpace($SourceDirectory)) { + $SourceDirectory = $scriptDirectory +} + +function Test-Administrator { + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = [Security.Principal.WindowsPrincipal]::new($identity) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +function Resolve-RequiredDirectory { + param( + [Parameter(Mandatory = $true)] + [string]$Path, + [Parameter(Mandatory = $true)] + [string]$Label + ) + + if ([string]::IsNullOrWhiteSpace($Path)) { + throw "$Label 不能为空。" + } + $resolved = [System.IO.Path]::GetFullPath($Path) + $root = [System.IO.Path]::GetPathRoot($resolved) + if ($resolved -eq $root) { + throw "$Label 不能使用磁盘根目录:$resolved" + } + return $resolved.TrimEnd([System.IO.Path]::DirectorySeparatorChar) +} + +function Invoke-Sc { + param( + [Parameter(Mandatory = $true)] + [string[]]$Arguments, + [switch]$AllowFailure + ) + + $output = & sc.exe @Arguments 2>&1 + if ($LASTEXITCODE -ne 0 -and -not $AllowFailure) { + throw "Windows 服务命令执行失败:sc.exe $($Arguments -join ' ')`n$($output -join "`n")" + } + return $output +} + +function Test-ServiceExists { + param([Parameter(Mandatory = $true)][string]$Name) + & sc.exe query $Name *> $null + return $LASTEXITCODE -eq 0 +} + +function Install-OrUpdateService { + param( + [Parameter(Mandatory = $true)][string]$Name, + [Parameter(Mandatory = $true)][string]$DisplayName, + [Parameter(Mandatory = $true)][string]$Description, + [Parameter(Mandatory = $true)][string]$BinaryPath, + [Parameter(Mandatory = $true)][ValidateSet("auto", "demand")][string]$StartMode + ) + + if (Test-ServiceExists -Name $Name) { + Invoke-Sc -Arguments @("config", $Name, "binPath=", $BinaryPath, "start=", $StartMode, "obj=", "NT AUTHORITY\LocalService", "DisplayName=", $DisplayName) | Out-Null + } + else { + Invoke-Sc -Arguments @("create", $Name, "binPath=", $BinaryPath, "start=", $StartMode, "obj=", "NT AUTHORITY\LocalService", "DisplayName=", $DisplayName) | Out-Null + } + Invoke-Sc -Arguments @("description", $Name, $Description) | Out-Null +} + +function Set-DirectoryAcl { + param( + [Parameter(Mandatory = $true)][string]$Path, + [Parameter(Mandatory = $true)][ValidateSet("read", "modify")][string]$Mode + ) + + $localServicePermission = if ($Mode -eq "modify") { "(OI)(CI)(M)" } else { "(OI)(CI)(RX)" } + & icacls.exe $Path /inheritance:r /grant:r ` + "BUILTIN\Administrators:(OI)(CI)(F)" ` + "NT AUTHORITY\SYSTEM:(OI)(CI)(F)" ` + "NT AUTHORITY\LOCAL SERVICE:$localServicePermission" *> $null + if ($LASTEXITCODE -ne 0) { + throw "设置目录访问控制失败:$Path" + } +} + +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw "该安装器只能在 Windows 上运行。" +} +if (-not (Test-Administrator)) { + throw "请使用管理员权限运行 Scert Windows 安装器。" +} +if (-not (Get-Command sc.exe -ErrorAction SilentlyContinue)) { + throw "系统中没有找到 sc.exe,无法注册 Windows 服务。" +} +if (-not (Get-Command icacls.exe -ErrorAction SilentlyContinue)) { + throw "系统中没有找到 icacls.exe,无法设置安全权限。" +} + +$source = Resolve-RequiredDirectory -Path $SourceDirectory -Label "安装产物目录" +$install = Resolve-RequiredDirectory -Path $InstallDirectory -Label "程序安装目录" +$data = Resolve-RequiredDirectory -Path $DataDirectory -Label "数据目录" +$certificate = Resolve-RequiredDirectory -Path $CertificateDirectory -Label "证书目录" + +$sourceScert = Join-Path $source "scert.exe" +$sourceAdmin = Join-Path $source "scert-admin.exe" +if (-not (Test-Path -LiteralPath $sourceScert -PathType Leaf)) { + throw "安装产物目录缺少 scert.exe:$sourceScert" +} +if (-not (Test-Path -LiteralPath $sourceAdmin -PathType Leaf)) { + throw "安装产物目录缺少 scert-admin.exe:$sourceAdmin" +} + +$configDirectory = Join-Path $data "config" +$databaseDirectory = Join-Path $data "data" +$logDirectory = Join-Path $data "logs" +$backupDirectory = Join-Path $data "backups" +$docsDirectory = Join-Path $data "docs" +$runtimeDirectory = Join-Path $data "runtime" + +foreach ($directory in @($install, $data, $configDirectory, $databaseDirectory, $logDirectory, $backupDirectory, $docsDirectory, $runtimeDirectory, $certificate)) { + New-Item -ItemType Directory -Path $directory -Force | Out-Null +} + +$installedScert = Join-Path $install "scert.exe" +$installedAdmin = Join-Path $install "scert-admin.exe" +Copy-Item -LiteralPath $sourceScert -Destination $installedScert -Force +Copy-Item -LiteralPath $sourceAdmin -Destination $installedAdmin -Force + +Set-DirectoryAcl -Path $install -Mode read +foreach ($directory in @($data, $configDirectory, $databaseDirectory, $logDirectory, $backupDirectory, $runtimeDirectory, $certificate)) { + Set-DirectoryAcl -Path $directory -Mode modify +} +Set-DirectoryAcl -Path $docsDirectory -Mode read + +$configurationPath = Join-Path $configDirectory "scert.json" +$resetCodePath = Join-Path $runtimeDirectory "reset-code" +$mainBinaryPath = '"{0}" --config "{1}" serve' -f $installedScert, $configurationPath +$adminBinaryPath = '"{0}" --config "{1}" --code-output "{2}"' -f $installedAdmin, $configurationPath, $resetCodePath + +Install-OrUpdateService ` + -Name $ServiceName ` + -DisplayName "Scert SSL 证书管理服务" ` + -Description "Scert SSL 证书申请、续期和部署服务" ` + -BinaryPath $mainBinaryPath ` + -StartMode auto + +Install-OrUpdateService ` + -Name $AdminServiceName ` + -DisplayName "Scert-admin 临时密码重置服务" ` + -Description "仅在管理员手动启动时临时激活 Scert 密码重置入口" ` + -BinaryPath $adminBinaryPath ` + -StartMode demand + +$metadata = [ordered]@{ + installed_at = [DateTimeOffset]::Now.ToString("o") + install_directory = $install + data_directory = $data + config_directory = $configDirectory + certificate_root = $certificate + service_name = $ServiceName + admin_service_name = $AdminServiceName + service_account = "NT AUTHORITY\LocalService" +} +$metadataPath = Join-Path $configDirectory "installation.json" +$metadata | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $metadataPath -Encoding UTF8 + +Write-Host "Scert Windows 文件安装和服务注册完成。" +Write-Host "核心程序:$installedScert" +Write-Host "密码重置程序:$installedAdmin" +Write-Host "配置目录:$configDirectory" +Write-Host "数据目录:$databaseDirectory" +Write-Host "日志目录:$logDirectory" +Write-Host "备份目录:$backupDirectory" +Write-Host "证书目录:$certificate" +Write-Host "安装记录:$metadataPath" +Write-Host "Scert 主服务已注册为自动启动,但本安装器没有启动或重启服务。" +Write-Host "Scert-admin 已注册为手动启动,本安装器不会启动它,也不会创建公网防火墙规则。" +Write-Host "首次初始化时请使用配置文件路径:$configurationPath" \ No newline at end of file diff --git a/deploy/systemd/Scert服务管理说明.md b/deploy/systemd/Scert服务管理说明.md index e0f773e..bf40999 100644 --- a/deploy/systemd/Scert服务管理说明.md +++ b/deploy/systemd/Scert服务管理说明.md @@ -26,6 +26,7 @@ systemctl daemon-reload ```text /scert 安装目录 +/scert/web Web 管理页面静态资源 /scert/conf 配置目录 /scert/data 数据目录 /scert/log 日志目录 diff --git a/desktop/.gitignore b/desktop/.gitignore new file mode 100644 index 0000000..a768298 --- /dev/null +++ b/desktop/.gitignore @@ -0,0 +1,8 @@ +# Wails 桌面版生成资源 +frontend/dist/* +!frontend/dist/index.html +bin/ + +build/ +frontend/wailsjs/ +frontend/package.json.md5 diff --git a/desktop/README.md b/desktop/README.md new file mode 100644 index 0000000..b0e70a5 --- /dev/null +++ b/desktop/README.md @@ -0,0 +1,23 @@ +# Scert 桌面版 + +桌面版使用 Wails 2,将 Vue 管理页面嵌入桌面窗口,并在同一进程内复用 Scert Go 核心服务和 HTTP API。桌面版不会额外监听服务端口,也不会复制一套桌面专用业务页面。 + +## 开发运行 + +在项目根目录先构建前端,再进入桌面目录执行: + +```powershell +npm.cmd --prefix .\frontend run build +wails dev +``` + +首次构建或发布构建会通过 `desktop/scripts/build-frontend.mjs` 构建根目录前端,并同步到桌面嵌入目录。 + +## 配置目录 + +默认使用当前用户配置目录下的 `Scert` 目录。可以通过以下环境变量覆盖: + +- `SCERT_DESKTOP_BASE_DIR`:桌面版运行数据基础目录。 +- `SCERT_CONFIG_PATH`:明确指定 `scert.json` 配置文件路径。 + +桌面版和 Web 版使用相同的配置格式、数据库、证书目录、DNS API 和部署逻辑。 diff --git a/desktop/frontend/dist/index.html b/desktop/frontend/dist/index.html new file mode 100644 index 0000000..2981411 --- /dev/null +++ b/desktop/frontend/dist/index.html @@ -0,0 +1,14 @@ + + + + + + + Scert SSL 证书管理 + + + + +
+ + diff --git a/desktop/frontend/package-lock.json b/desktop/frontend/package-lock.json new file mode 100644 index 0000000..66fc94f --- /dev/null +++ b/desktop/frontend/package-lock.json @@ -0,0 +1,11 @@ +{ + "name": "scert-desktop-frontend", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "scert-desktop-frontend" + } + } +} diff --git a/desktop/frontend/package.json b/desktop/frontend/package.json new file mode 100644 index 0000000..57f7ab5 --- /dev/null +++ b/desktop/frontend/package.json @@ -0,0 +1,8 @@ +{ + "name": "scert-desktop-frontend", + "private": true, + "scripts": { + "build": "node ../scripts/build-frontend.mjs", + "dev": "npm --prefix ../../frontend run dev" + } +} diff --git a/desktop/go.mod b/desktop/go.mod new file mode 100644 index 0000000..4335e24 --- /dev/null +++ b/desktop/go.mod @@ -0,0 +1,131 @@ +module git.pcux.cn/xuans/Scert/desktop + +go 1.26.0 + +require ( + git.pcux.cn/xuans/Scert/backend v0.0.0 + github.com/wailsapp/wails/v2 v2.11.0 +) + +require ( + cloud.google.com/go/auth v0.20.0 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect + cloud.google.com/go/compute/metadata v0.9.0 // indirect + filippo.io/edwards25519 v1.1.0 // indirect + github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.5 // indirect + github.com/alibabacloud-go/darabonba-openapi/v2 v2.2.3 // indirect + github.com/alibabacloud-go/debug v1.0.1 // indirect + github.com/alibabacloud-go/tea v1.5.2 // indirect + github.com/alibabacloud-go/tea-utils/v2 v2.0.9 // indirect + github.com/aliyun/credentials-go v1.4.7 // indirect + github.com/aws/aws-sdk-go-v2 v1.42.1 // indirect + github.com/aws/aws-sdk-go-v2/config v1.32.30 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.19.29 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30 // indirect + github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.4.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.32.1 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.44.1 // indirect + github.com/aws/smithy-go v1.27.3 // indirect + github.com/bep/debounce v1.2.1 // indirect + github.com/bytedance/sonic v1.11.6 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/clbanning/mxj/v2 v2.7.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/gabriel-vasile/mimetype v1.4.13 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.10.1 // indirect + github.com/go-acme/alidns-20150109/v5 v5.5.0 // indirect + github.com/go-acme/lego/v5 v5.4.0 // indirect + github.com/go-acme/tencentclouddnspod v1.3.24 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.3 // indirect + github.com/go-sql-driver/mysql v1.9.3 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/google/s2a-go v0.1.9 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.17 // indirect + github.com/googleapis/gax-go/v2 v2.22.0 // indirect + github.com/gorilla/websocket v1.5.3 // indirect + github.com/huaweicloud/huaweicloud-sdk-go-v3 v0.1.205 // indirect + github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect + github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/kr/fs v0.1.0 // indirect + github.com/labstack/echo/v4 v4.13.3 // indirect + github.com/labstack/gommon v0.4.2 // indirect + github.com/leaanthony/go-ansi-parser v1.6.1 // indirect + github.com/leaanthony/gosod v1.0.4 // indirect + github.com/leaanthony/slicer v1.6.0 // indirect + github.com/leaanthony/u v1.1.1 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.22 // indirect + github.com/miekg/dns v1.1.72 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pkg/sftp v1.13.11 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/samber/lo v1.49.1 // indirect + github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.133 // indirect + github.com/tjfoc/gmsm v1.4.1 // indirect + github.com/tkrajina/go-reflector v0.5.8 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect + github.com/wailsapp/go-webview2 v1.0.22 // indirect + github.com/wailsapp/mimetype v1.4.1 // indirect + go.mongodb.org/mongo-driver v1.17.9 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect + go.opentelemetry.io/otel v1.43.0 // indirect + go.opentelemetry.io/otel/metric v1.43.0 // indirect + go.opentelemetry.io/otel/trace v1.43.0 // indirect + golang.org/x/arch v0.8.0 // indirect + golang.org/x/crypto v0.54.0 // indirect + golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect + golang.org/x/mod v0.37.0 // indirect + golang.org/x/net v0.57.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.40.0 // indirect + golang.org/x/tools v0.47.0 // indirect + google.golang.org/api v0.288.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 // indirect + google.golang.org/grpc v1.82.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect + gopkg.in/ini.v1 v1.67.3 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + modernc.org/libc v1.62.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.9.1 // indirect + modernc.org/sqlite v1.37.0 // indirect + software.sslmate.com/src/go-pkcs12 v0.7.3 // indirect +) + +replace git.pcux.cn/xuans/Scert/backend => ../backend diff --git a/desktop/go.sum b/desktop/go.sum new file mode 100644 index 0000000..f6ac8f2 --- /dev/null +++ b/desktop/go.sum @@ -0,0 +1,571 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go/auth v0.20.0 h1:kXTssoVb4azsVDoUiF8KvxAqrsQcQtB53DcSgta74CA= +cloud.google.com/go/auth v0.20.0/go.mod h1:942/yi/itH1SsmpyrbnTMDgGfdy2BUqIKyd0cyYLc5Q= +cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= +cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/alibabacloud-go/alibabacloud-gateway-pop v0.0.6 h1:eIf+iGJxdU4U9ypaUfbtOWCsZSbTb8AUHvyPrxu6mAA= +github.com/alibabacloud-go/alibabacloud-gateway-pop v0.0.6/go.mod h1:4EUIoxs/do24zMOGGqYVWgw0s9NtiylnJglOeEB5UJo= +github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.4/go.mod h1:sCavSAvdzOjul4cEqeVtvlSaSScfNsTQ+46HwlTL1hc= +github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.5 h1:zE8vH9C7JiZLNJJQ5OwjU9mSi4T9ef9u3BURT6LCLC8= +github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.5/go.mod h1:tWnyE9AjF8J8qqLk645oUmVUnFybApTQWklQmi5tY6g= +github.com/alibabacloud-go/darabonba-array v0.1.0 h1:vR8s7b1fWAQIjEjWnuF0JiKsCvclSRTfDzZHTYqfufY= +github.com/alibabacloud-go/darabonba-array v0.1.0/go.mod h1:BLKxr0brnggqOJPqT09DFJ8g3fsDshapUD3C3aOEFaI= +github.com/alibabacloud-go/darabonba-encode-util v0.0.2 h1:1uJGrbsGEVqWcWxrS9MyC2NG0Ax+GpOM5gtupki31XE= +github.com/alibabacloud-go/darabonba-encode-util v0.0.2/go.mod h1:JiW9higWHYXm7F4PKuMgEUETNZasrDM6vqVr/Can7H8= +github.com/alibabacloud-go/darabonba-map v0.0.2 h1:qvPnGB4+dJbJIxOOfawxzF3hzMnIpjmafa0qOTp6udc= +github.com/alibabacloud-go/darabonba-map v0.0.2/go.mod h1:28AJaX8FOE/ym8OUFWga+MtEzBunJwQGceGQlvaPGPc= +github.com/alibabacloud-go/darabonba-openapi/v2 v2.2.2/go.mod h1:CsqHkHPpAKL64jl/fChR249EL0abYEIDWmlwFYgo7/E= +github.com/alibabacloud-go/darabonba-openapi/v2 v2.2.3 h1:rec08F9BzxIiJ03h2u6BT2QqLVa8ktnpvJ27j5PsjLM= +github.com/alibabacloud-go/darabonba-openapi/v2 v2.2.3/go.mod h1:eHjVxrT9g8uVYN/nyAwOFQEfkVA154ChiqRc2XnNKYU= +github.com/alibabacloud-go/darabonba-signature-util v0.0.7 h1:UzCnKvsjPFzApvODDNEYqBHMFt1w98wC7FOo0InLyxg= +github.com/alibabacloud-go/darabonba-signature-util v0.0.7/go.mod h1:oUzCYV2fcCH797xKdL6BDH8ADIHlzrtKVjeRtunBNTQ= +github.com/alibabacloud-go/darabonba-string v1.0.2 h1:E714wms5ibdzCqGeYJ9JCFywE5nDyvIXIIQbZVFkkqo= +github.com/alibabacloud-go/darabonba-string v1.0.2/go.mod h1:93cTfV3vuPhhEwGGpKKqhVW4jLe7tDpo3LUM0i0g6mA= +github.com/alibabacloud-go/debug v0.0.0-20190504072949-9472017b5c68/go.mod h1:6pb/Qy8c+lqua8cFpEy7g39NRRqOWc3rOwAy8m5Y2BY= +github.com/alibabacloud-go/debug v1.0.0/go.mod h1:8gfgZCCAC3+SCzjWtY053FrOcd4/qlH6IHTI4QyICOc= +github.com/alibabacloud-go/debug v1.0.1 h1:MsW9SmUtbb1Fnt3ieC6NNZi6aEwrXfDksD4QA6GSbPg= +github.com/alibabacloud-go/debug v1.0.1/go.mod h1:8gfgZCCAC3+SCzjWtY053FrOcd4/qlH6IHTI4QyICOc= +github.com/alibabacloud-go/endpoint-util v1.1.0 h1:r/4D3VSw888XGaeNpP994zDUaxdgTSHBbVfZlzf6b5Q= +github.com/alibabacloud-go/endpoint-util v1.1.0/go.mod h1:O5FuCALmCKs2Ff7JFJMudHs0I5EBgecXXxZRyswlEjE= +github.com/alibabacloud-go/openapi-util v0.1.0/go.mod h1:sQuElr4ywwFRlCCberQwKRFhRzIyG4QTP/P4y1CJ6Ws= +github.com/alibabacloud-go/openapi-util v0.1.2 h1:aljdyAPotH4xHymo5wzARjcHb3Org0zKnLP4RxS0JGY= +github.com/alibabacloud-go/openapi-util v0.1.2/go.mod h1:/UehBSE2cf1gYT43GV4E+RxTdLRzURImCYY0aRmlXpw= +github.com/alibabacloud-go/tea v1.1.0/go.mod h1:IkGyUSX4Ba1V+k4pCtJUc6jDpZLFph9QMy2VUPTwukg= +github.com/alibabacloud-go/tea v1.1.7/go.mod h1:/tmnEaQMyb4Ky1/5D+SE1BAsa5zj/KeGOFfwYm3N/p4= +github.com/alibabacloud-go/tea v1.1.8/go.mod h1:/tmnEaQMyb4Ky1/5D+SE1BAsa5zj/KeGOFfwYm3N/p4= +github.com/alibabacloud-go/tea v1.1.11/go.mod h1:/tmnEaQMyb4Ky1/5D+SE1BAsa5zj/KeGOFfwYm3N/p4= +github.com/alibabacloud-go/tea v1.1.17/go.mod h1:nXxjm6CIFkBhwW4FQkNrolwbfon8Svy6cujmKFUq98A= +github.com/alibabacloud-go/tea v1.1.20/go.mod h1:nXxjm6CIFkBhwW4FQkNrolwbfon8Svy6cujmKFUq98A= +github.com/alibabacloud-go/tea v1.2.2/go.mod h1:CF3vOzEMAG+bR4WOql8gc2G9H3EkH3ZLAQdpmpXMgwk= +github.com/alibabacloud-go/tea v1.5.1/go.mod h1:hgSs82CkOiehSQMoiFN79dL6zsGX7pVGvnn9SIEs8/0= +github.com/alibabacloud-go/tea v1.5.2 h1:DUzV/cRTbJC++rmADfqVu//GuWbaD64ZJ3yW3v2ukNU= +github.com/alibabacloud-go/tea v1.5.2/go.mod h1:hgSs82CkOiehSQMoiFN79dL6zsGX7pVGvnn9SIEs8/0= +github.com/alibabacloud-go/tea-utils v1.3.1/go.mod h1:EI/o33aBfj3hETm4RLiAxF/ThQdSngxrpF8rKUDJjPE= +github.com/alibabacloud-go/tea-utils/v2 v2.0.5/go.mod h1:dL6vbUT35E4F4bFTHL845eUloqaerYBYPsdWR2/jhe4= +github.com/alibabacloud-go/tea-utils/v2 v2.0.9 h1:y6pUIlhjxbZl9ObDAcmA1H3c21eaAxADHTDQmBnAIgA= +github.com/alibabacloud-go/tea-utils/v2 v2.0.9/go.mod h1:qxn986l+q33J5VkialKMqT/TTs3E+U9MJpd001iWQ9I= +github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw= +github.com/aliyun/credentials-go v1.3.1/go.mod h1:8jKYhQuDawt8x2+fusqa1Y6mPxemTsBEN04dgcAcYz0= +github.com/aliyun/credentials-go v1.3.6/go.mod h1:1LxUuX7L5YrZUWzBrRyk0SwSdH4OmPrib8NVePL3fxM= +github.com/aliyun/credentials-go v1.4.5/go.mod h1:Jm6d+xIgwJVLVWT561vy67ZRP4lPTQxMbEYRuT2Ti1U= +github.com/aliyun/credentials-go v1.4.7 h1:T17dLqEtPUFvjDRRb5giVvLh6dFT8IcNFJJb7MeyCxw= +github.com/aliyun/credentials-go v1.4.7/go.mod h1:Jm6d+xIgwJVLVWT561vy67ZRP4lPTQxMbEYRuT2Ti1U= +github.com/aws/aws-sdk-go-v2 v1.42.1 h1:9eOTgu1z/dVtYpNZ3/8/XbbaX0x/BqE3HUzAzs6K0ek= +github.com/aws/aws-sdk-go-v2 v1.42.1/go.mod h1:5pKeft2eJj+gElQ38Jqg4ibCqh+/AK33/0X3hip7IjM= +github.com/aws/aws-sdk-go-v2/config v1.32.30 h1:XwsEzpTJfQYJbFicz/QMLwAZdyeNVVoOEkbF7R3gPJk= +github.com/aws/aws-sdk-go-v2/config v1.32.30/go.mod h1:Ud32SuMc+/9BGxfpSVld7HrE2o05JwKmXY4M3jOQNZU= +github.com/aws/aws-sdk-go-v2/credentials v1.19.29 h1:WHZGssHH887cO0ox07SIQZsFx3MKD4ps6w0xUEmnKYQ= +github.com/aws/aws-sdk-go-v2/credentials v1.19.29/go.mod h1:Mhl0xR6zjguiuj00XRx2wMx22sAltk7oya39sT7fdg8= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30 h1:/hi1JADLEW9YYryEz1w4GQu0EtP23pP553Cf9KgsDV4= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30/go.mod h1:/3AOgy4K17Dm4ucMZVC/MJkzy5kmfKUcINRHZyo0koQ= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30 h1:xM/Is9cKMHa8Jj8zkvWhvrFkZsXJV9E+BB4g0HW0duQ= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30/go.mod h1:WueJeNDZvK1fMYEWJIkcivBfEzUkTpBhzlrUKKY8EuA= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30 h1:jn46zC9LdsVR/ZpMIJqMqb8hHv31BlLx3ulVqNspUOk= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30/go.mod h1:1hTMsAgbdS/AtUi4bw8+gUuh1pceo+eXRLfpSuSQj3M= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31 h1:3GUprIsfmGcC5SACIyB0e7E0BM1O1b3Erl5CePYIAeQ= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31/go.mod h1:7PuV1yl5e2xnUbm+RqvVg5i2iBM8EyijZNoI9wsOoOc= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13 h1:mbRIur/BiHK6SKPjoBIXSE/hJ6g6JGRLuxQy1jGjlN4= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13/go.mod h1:ITg9em2KbJx1s0y4aqRX5OYWG6HBZ5TVR//OdpEZ2CQ= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30 h1:/Z5jmNrKsSD7EmDjzAPsm/3L9IuOkzaynklJZ1qX7S4= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30/go.mod h1:lEzEZnOosE7zi8Z6royW1cFJTD9fpab4Ul1SBrllewk= +github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1 h1:qL5ELChQ1o1ZbzHvsl8gzQfAZdbQtrDbUyzJkjkMKcg= +github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1/go.mod h1:0hIRXFez1bZsDFMGkLZvNJbByTSVZ4sFZWpxZ39NPuM= +github.com/aws/aws-sdk-go-v2/service/signin v1.4.1 h1:V7ZZ300WPXGjvkyore5DGe0ljVPOxCXie/thWdtSBXE= +github.com/aws/aws-sdk-go-v2/service/signin v1.4.1/go.mod h1:mxC0nT/C8wMMS97DemZPzvUZxvIt+2Iq+eS3JdFZGgg= +github.com/aws/aws-sdk-go-v2/service/sso v1.32.1 h1:gYFYh4iLLcAOJRLNPY2aD2g9DIhKn4eof8UkIrr1rTk= +github.com/aws/aws-sdk-go-v2/service/sso v1.32.1/go.mod h1:u8af9Nqkmqnr96f7v9nHqzZT9XBwbXEkTiqT4ROuJSE= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.1 h1:arjT9Cm3/WYbGmD5TUZHk4UQn4Lle1fUNZs5FC6CtF0= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.1/go.mod h1:DMPWJBjYs6+3+f/qhBFEFPPlQ6NlhWjai3dJNvipJ84= +github.com/aws/aws-sdk-go-v2/service/sts v1.44.1 h1:RvfHDg+xvAeZ+5741vUEjpOVtYSIm93W2zhx10Xtydw= +github.com/aws/aws-sdk-go-v2/service/sts v1.44.1/go.mod h1:9gdl4RrflIdpDb2TlXshWgR1F9TeCkvqDx77Vpr4Z/Q= +github.com/aws/smithy-go v1.27.3 h1:F3Zb497UhhskkfpJmfkXswyo+t0sh9OTBnIHjogWbVY= +github.com/aws/smithy-go v1.27.3/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY= +github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0= +github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= +github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME= +github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM= +github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ= +github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-acme/alidns-20150109/v5 v5.5.0 h1:/LUHZSQoaDqagi8wCq8f9Rx4AoVr/Jd4rKEV2IQYvxs= +github.com/go-acme/alidns-20150109/v5 v5.5.0/go.mod h1:J2B9WBwSFfZalzlCqSkeyBkqBcWPEZMDkxwhOjjF0MA= +github.com/go-acme/lego/v5 v5.4.0 h1:y107z5o/Ru5qzv5ZnD7MZ1QyCbsZbfxREOxdMdx3FuY= +github.com/go-acme/lego/v5 v5.4.0/go.mod h1:YGuvVqYJZvmy6t0COKHC/+z9zhF4IrJQ1iA8NLX5c9Y= +github.com/go-acme/tencentclouddnspod v1.3.24 h1:uCSiOW1EJttcnOON+MVVyVDJguFL/Q4NIGkq1CrT9p8= +github.com/go-acme/tencentclouddnspod v1.3.24/go.mod h1:RKcB2wSoZncjBA0OEFj59s1ko1XDy+ZsAtk+9uMxUF0= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8= +github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc= +github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= +github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/goccy/go-yaml v1.9.8/go.mod h1:JubOolP3gh0HpiBc4BLRD4YmjEjHAmIIB2aaXKkTfoE= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.17 h1:73NfMHdiqo9JFU9+7a5ExpVa10/R29pXfZIaW559nrg= +github.com/googleapis/enterprise-certificate-proxy v0.3.17/go.mod h1:rSEsBUemEBZEexP2y6jPp16LUmUbjmSbcPMQizR0o4k= +github.com/googleapis/gax-go/v2 v2.22.0 h1:PjIWBpgGIVKGoCXuiCoP64altEJCj3/Ei+kSU5vlZD4= +github.com/googleapis/gax-go/v2 v2.22.0/go.mod h1:irWBbALSr0Sk3qlqb9SyJ1h68WjgeFuiOzI4Rqw5+aY= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/huaweicloud/huaweicloud-sdk-go-v3 v0.1.205 h1:YnI2+56S5oxByz8BYChRrsmqTUmCp1Ww2KIzZtF4XOU= +github.com/huaweicloud/huaweicloud-sdk-go-v3 v0.1.205/go.mod h1:M+yna96Fx9o5GbIUnF3OvVvQGjgfVSyeJbV9Yb1z/wI= +github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck= +github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12 h1:9Nu54bhS/H/Kgo2/7xNSUuC5G28VR8ljfrLKU2G4IjU= +github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12/go.mod h1:TBzl5BIHNXfS9+C35ZyJaklL7mLDbgUkcgXzSLa8Tk0= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY= +github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g= +github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0= +github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU= +github.com/leaanthony/debme v1.2.1 h1:9Tgwf+kjcrbMQ4WnPcEIUcQuIZYqdWftzZkBr+i/oOc= +github.com/leaanthony/debme v1.2.1/go.mod h1:3V+sCm5tYAgQymvSOfYQ5Xx2JCr+OXiD9Jkw3otUjiA= +github.com/leaanthony/go-ansi-parser v1.6.1 h1:xd8bzARK3dErqkPFtoF9F3/HgN8UQk0ed1YDKpEz01A= +github.com/leaanthony/go-ansi-parser v1.6.1/go.mod h1:+vva/2y4alzVmmIEpk9QDhA7vLC5zKDTRwfZGOp3IWU= +github.com/leaanthony/gosod v1.0.4 h1:YLAbVyd591MRffDgxUOU1NwLhT9T1/YiwjKZpkNFeaI= +github.com/leaanthony/gosod v1.0.4/go.mod h1:GKuIL0zzPj3O1SdWQOdgURSuhkF+Urizzxh26t9f1cw= +github.com/leaanthony/slicer v1.6.0 h1:1RFP5uiPJvT93TAHi+ipd3NACobkW53yUiBqZheE/Js= +github.com/leaanthony/slicer v1.6.0/go.mod h1:o/Iz29g7LN0GqH3aMjWAe90381nyZlDNquK+mtH2Fj8= +github.com/leaanthony/u v1.1.1 h1:TUFjwDGlNX+WuwVEzDqQwC2lOv0P4uhTQw7CMFdiK7M= +github.com/leaanthony/u v1.1.1/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQcaRfI= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= +github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= +github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= +github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4= +github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= +github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.13.11 h1:0N92SLTB8JqASJB14ZLHHzFnBV8mG9zw4K7jghEFWuE= +github.com/pkg/sftp v1.13.11/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew= +github.com/samber/lo v1.49.1/go.mod h1:dO6KHFzUKXgP8LDhU0oI8d2hekjXnGOu0DB8Jecxd6o= +github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/assertions v1.1.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.24/go.mod h1:r5r4xbfxSaeR04b166HGsBa/R4U3SueirEUpXGuw+Q0= +github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.133 h1:EKJsaGHbifEKqWCdJ4tJNLxbJ5h/Pm3CaLKzcCS/pkw= +github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.133/go.mod h1:r5r4xbfxSaeR04b166HGsBa/R4U3SueirEUpXGuw+Q0= +github.com/tjfoc/gmsm v1.3.2/go.mod h1:HaUcFuY0auTiaHB9MHFGCPx5IaLhTUd2atbCFBQXn9w= +github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho= +github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE= +github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ= +github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +github.com/wailsapp/go-webview2 v1.0.22 h1:YT61F5lj+GGaat5OB96Aa3b4QA+mybD0Ggq6NZijQ58= +github.com/wailsapp/go-webview2 v1.0.22/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc= +github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs= +github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o= +github.com/wailsapp/wails/v2 v2.11.0 h1:seLacV8pqupq32IjS4Y7V8ucab0WZwtK6VvUVxSBtqQ= +github.com/wailsapp/wails/v2 v2.11.0/go.mod h1:jrf0ZaM6+GBc1wRmXsM8cIvzlg0karYin3erahI4+0k= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.13.1/go.mod h1:wcDf1JBCXy2mOW0bWHwO/IOYqdca1MPCwDtFu/Z9+eo= +go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU= +go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg= +go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= +go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg= +go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= +go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= +go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= +golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191219195013-becbf705a915/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= +golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= +golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220406163625-3f8b81556e12/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= +golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200509030707-2212a7e161a5/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/api v0.288.0 h1:glhO/J88obKP5I269W3hB73dvBKrjU56ZfmNlNXpgTU= +google.golang.org/api v0.288.0/go.mod h1:lM2kYRzYUCBY91P9h6VF1PYmvhxii3O5hji37qRvIcY= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= +google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I= +google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec= +google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 h1:eM/YSd5bBFagF51o1E745Ta7RwzpW0h+z+QDNZOgmQ8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU= +google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/ini.v1 v1.56.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw= +gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +modernc.org/cc/v4 v4.25.2 h1:T2oH7sZdGvTaie0BRNFbIYsabzCxUQg8nLqCdQ2i0ic= +modernc.org/cc/v4 v4.25.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= +modernc.org/ccgo/v4 v4.25.1 h1:TFSzPrAGmDsdnhT9X2UrcPMI3N/mJ9/X9ykKXwLhDsU= +modernc.org/ccgo/v4 v4.25.1/go.mod h1:njjuAYiPflywOOrm3B7kCB444ONP5pAVr8PIEoE0uDw= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/libc v1.62.1 h1:s0+fv5E3FymN8eJVmnk0llBe6rOxCu/DEU+XygRbS8s= +modernc.org/libc v1.62.1/go.mod h1:iXhATfJQLjG3NWy56a6WVU73lWOcdYVxsvwCgoPljuo= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.9.1 h1:V/Z1solwAVmMW1yttq3nDdZPJqV1rM05Ccq6KMSZ34g= +modernc.org/memory v1.9.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= +modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.37.0 h1:s1TMe7T3Q3ovQiK2Ouz4Jwh7dw4ZDqbebSDTlSJdfjI= +modernc.org/sqlite v1.37.0/go.mod h1:5YiWv+YviqGMuGw4V+PNplcyaJ5v+vQd7TQOgkACoJM= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= +software.sslmate.com/src/go-pkcs12 v0.7.3 h1:JBQD3FDqYjTeyDAeZQklj2ar88ykBLtALloPJHyAauU= +software.sslmate.com/src/go-pkcs12 v0.7.3/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI= diff --git a/desktop/main.go b/desktop/main.go new file mode 100644 index 0000000..f85158e --- /dev/null +++ b/desktop/main.go @@ -0,0 +1,81 @@ +package main + +import ( + "context" + "embed" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + + "git.pcux.cn/xuans/Scert/backend/service" + "github.com/wailsapp/wails/v2" + "github.com/wailsapp/wails/v2/pkg/options" + "github.com/wailsapp/wails/v2/pkg/options/assetserver" +) + +//go:embed all:frontend/dist +var assets embed.FS + +func main() { + baseDir := resolveBaseDir() + configPath := strings.TrimSpace(os.Getenv("SCERT_CONFIG_PATH")) + if configPath == "" { + configPath = filepath.Join(baseDir, "Scert", "config", "scert.json") + } + core, err := service.Open(configPath, baseDir) + if err != nil { + fmt.Fprintln(os.Stderr, "启动 Scert 桌面核心服务失败:", err) + os.Exit(1) + } + + if err := wails.Run(&options.App{ + Title: "Scert SSL 证书管理", + Width: 1440, + Height: 900, + MinWidth: 1100, + MinHeight: 720, + AssetServer: &assetserver.Options{Assets: assets, Handler: desktopHandler(core.Handler())}, + BackgroundColour: &options.RGBA{R: 246, G: 248, B: 252, A: 1}, + OnShutdown: func(_ context.Context) { + _ = core.Close() + }, + }); err != nil { + _ = core.Close() + fmt.Fprintln(os.Stderr, "Scert 桌面程序退出失败:", err) + os.Exit(1) + } +} + +func resolveBaseDir() string { + if value := strings.TrimSpace(os.Getenv("SCERT_DESKTOP_BASE_DIR")); value != "" { + return filepath.Clean(value) + } + if value, err := os.UserConfigDir(); err == nil && strings.TrimSpace(value) != "" { + return filepath.Clean(value) + } + if value, err := os.Executable(); err == nil { + return filepath.Dir(value) + } + return "." +} + +func desktopHandler(core http.Handler) http.Handler { + return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + path := request.URL.Path + if request.Method != http.MethodGet || isCorePath(path) { + core.ServeHTTP(writer, request) + return + } + http.NotFound(writer, request) + }) +} + +func isCorePath(path string) bool { + return path == "/api" || + strings.HasPrefix(path, "/api/") || + path == "/healthz" || + path == "/reset" || + strings.HasPrefix(path, "/reset/") +} diff --git a/desktop/main_test.go b/desktop/main_test.go new file mode 100644 index 0000000..9323ff4 --- /dev/null +++ b/desktop/main_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestIsCorePath(t *testing.T) { + tests := []struct { + path string + want bool + }{ + {path: "/api", want: true}, + {path: "/api/v1/status", want: true}, + {path: "/healthz", want: true}, + {path: "/reset", want: true}, + {path: "/reset/confirm", want: true}, + {path: "/apix", want: false}, + {path: "/healthz-extra", want: false}, + {path: "/reset-password", want: false}, + {path: "/", want: false}, + } + + for _, test := range tests { + t.Run(test.path, func(t *testing.T) { + if got := isCorePath(test.path); got != test.want { + t.Fatalf("isCorePath(%q) = %v, want %v", test.path, got, test.want) + } + }) + } +} + +func TestDesktopHandlerRoutesCoreRequests(t *testing.T) { + core := http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { + writer.WriteHeader(http.StatusNoContent) + }) + handler := desktopHandler(core) + + tests := []struct { + name string + method string + path string + want int + }{ + {name: "API GET", method: http.MethodGet, path: "/api/v1/status", want: http.StatusNoContent}, + {name: "reset GET", method: http.MethodGet, path: "/reset", want: http.StatusNoContent}, + {name: "API POST", method: http.MethodPost, path: "/api/v1/setup", want: http.StatusNoContent}, + {name: "non-API POST", method: http.MethodPost, path: "/unknown", want: http.StatusNoContent}, + {name: "asset fallback", method: http.MethodGet, path: "/apix", want: http.StatusNotFound}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + request := httptest.NewRequest(test.method, test.path, nil) + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != test.want { + t.Fatalf("status = %d, want %d", response.Code, test.want) + } + }) + } +} diff --git a/desktop/scripts/build-frontend.mjs b/desktop/scripts/build-frontend.mjs new file mode 100644 index 0000000..2809b5b --- /dev/null +++ b/desktop/scripts/build-frontend.mjs @@ -0,0 +1,24 @@ +import { execSync } from "node:child_process"; +import { cpSync, existsSync, mkdirSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const scriptDirectory = dirname(fileURLToPath(import.meta.url)); +const projectRoot = resolve(scriptDirectory, "../.."); +const frontendDirectory = resolve(projectRoot, "frontend"); +const desktopDistribution = resolve(scriptDirectory, "../frontend/dist"); +const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; + +execSync(`${npmCommand} run build`, { + cwd: frontendDirectory, + stdio: "inherit", + shell: true, +}); + +const frontendDistribution = resolve(frontendDirectory, "dist"); +if (!existsSync(frontendDistribution)) { + throw new Error("前端构建没有生成 dist 目录"); +} + +mkdirSync(desktopDistribution, { recursive: true }); +cpSync(frontendDistribution, desktopDistribution, { recursive: true, force: true }); diff --git a/desktop/wails.json b/desktop/wails.json new file mode 100644 index 0000000..fb4eaaa --- /dev/null +++ b/desktop/wails.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://wails.io/schemas/config.v2.json", + "name": "ScertDesktop", + "outputfilename": "ScertDesktop", + "frontend:dir": "frontend", + "frontend:install": "npm install", + "frontend:build": "npm run build", + "frontend:dev:watcher": "npm --prefix ../../frontend run dev", + "frontend:dev:serverUrl": "auto", + "author": { + "name": "xuans", + "email": "likb_blue@163.com" + } +} diff --git a/doc/SSL服务程序技术架构设计文档.md b/doc/SSL服务程序技术架构设计文档.md index 25e1ae2..7fd6447 100644 --- a/doc/SSL服务程序技术架构设计文档.md +++ b/doc/SSL服务程序技术架构设计文档.md @@ -687,7 +687,7 @@ POST /api/v1/domains/{id}/test-servers | fingerprint | 证书指纹 | | issued_at | 签发时间 | | expires_at | 到期时间 | -| status | `current`、`history`、`failed`、`rolled_back` | +| status | `current`、`failed`、`rolled_back` | | created_at | 创建时间 | ### 5.4 servers @@ -795,29 +795,20 @@ SAN 进入默认 UI、自动续期、证书版本保存、部署关联和验收 ```text {storage_root}/{domain}/ -├── production/ -│ ├── wildcard/ -│ │ ├── current/ -│ │ └── versions/{version}/ -│ └── single/ -│ ├── current/ -│ └── versions/{version}/ -└── development/ - ├── wildcard/ - │ ├── current/ - │ └── versions/{version}/ - └── single/ - ├── current/ - └── versions/{version}/ +├── wildcard/ +│ └── YYYYMMDD-Vx.x/ +├── single/ +│ └── YYYYMMDD-Vx.x/ +└── san/{certificate_identifier}/ + └── YYYYMMDD-Vx.x/ ``` 每个版本目录至少包含: ```text cert.pem -chain.pem fullchain.pem -privkey.pem +key.pem metadata.json ``` @@ -825,9 +816,11 @@ metadata.json - Linux 私钥文件使用 600 或更严格权限。 - Windows 使用仅服务账户和授权管理员可读的 ACL。 -- `current` 可以使用目录切换或受控复制,不直接覆盖正在使用的版本。 +- 生产和开发申请环境由域名配置中的 ACME 环境字段区分,不再创建两套证书目录。 +- 每个证书类型正式目录只保留一个当前版本目录;版本目录名称使用 `YYYYMMDD-Vx.x`。 +- 新证书写入新版本目录并完成校验后移除旧当前版本;失败时从备份目录恢复。 - 删除域名时先停止相关任务,再删除数据库记录和证书文件。 -- 用户上传证书默认保留当前版本和一个最近历史版本。 +- 用户上传证书默认只保留当前版本,备份目录仅用于失败回滚,不作为历史版本目录展示。 ### 6.1 跨平台默认路径 diff --git a/doc/SSL服务程序需求确认文档.md b/doc/SSL服务程序需求确认文档.md index 4b7f080..9a83f8b 100644 --- a/doc/SSL服务程序需求确认文档.md +++ b/doc/SSL服务程序需求确认文档.md @@ -65,35 +65,27 @@ ```text /ssl/{域名}/ -├── production/ 生产证书 -│ ├── wildcard/ 泛域名证书,例如 *.example.com -│ │ ├── current/ 当前使用版本 -│ │ └── versions/{版本}/ 历史版本 -│ └── single/ 单域名证书,例如 example.com -│ ├── current/ -│ └── versions/{版本}/ -└── development/ 开发证书,目录结构与 production 相同 +├── wildcard/ 泛域名证书,例如 *.example.com +│ └── {日期}-Vx.x/ 当前使用版本 +├── single/ 单域名证书,例如 example.com +│ └── {日期}-Vx.x/ 当前使用版本 +└── san/{证书标识}/ 多域名 SAN 证书 + └── {日期}-Vx.x/ 当前使用版本 ``` +版本目录名称格式为 `YYYYMMDD-Vx.x`,例如 `20260830-V1.0`。同一天再次保存时递增版本号,例如 `20260830-V1.1`。生产和开发证书不再使用两套目录层级,统一由域名配置中的 ACME 环境字段区分申请环境。正式证书目录只保留当前使用版本;新证书保存成功后替换旧当前版本,旧文件仅在失败回滚所需时进入备份目录。 + 多域名 SAN 证书纳入第一阶段,证书以主域名作为管理归属,并保存完整的 SAN 域名集合。SAN 证书目录使用证书标识区分不同域名集合: ```text /ssl/{主域名}/ -├── production/ -│ ├── wildcard/ -│ ├── single/ -│ └── san/{证书标识}/ -│ ├── current/ -│ └── versions/{版本}/ -└── development/ - ├── wildcard/ - ├── single/ - └── san/{证书标识}/ - ├── current/ - └── versions/{版本}/ +└── san/{证书标识}/ + └── {日期}-Vx.x/ ``` -其中 `{证书标识}` 必须能够稳定对应主域名和 SAN 域名集合;域名集合发生变化时创建新的证书版本,不覆盖原有证书版本。 +其中 `{证书标识}` 必须能够稳定对应主域名和 SAN 域名集合;域名集合发生变化时更新当前证书版本目录,不在正式证书目录中保留历史版本。 + +【用户补充 U-074】(2026-08-30):将生产/开发目录和当前/历史版本目录合并简化;正式证书目录只保留当前使用版本,版本目录名称使用日期加 `Vx.x`。本补充作为当前实现约束,优先于本节之前关于双环境目录和正式目录保留历史版本的描述。 ### 1.3 DNS 验证 @@ -1020,4 +1012,4 @@ imported 外部导入 - **用户补充:**为不熟悉 SSH 密钥生成的用户提供从生成密钥到粘贴公钥的完整指导,并支持更省事的操作方式。 - **实现说明:**服务器配置页面增加 Windows、Linux/macOS 命令切换;支持复制密钥生成命令、复制公钥安装命令、选择本机私钥文件导入、私钥口令显示/隐藏,以及 Linux 和 Windows OpenSSH 授权位置说明。私钥只在页面内存中读取,保存时由后端加密存储。 -- **状态:**`[x]` 已完成前端引导和中文说明文档,待前端构建和真实浏览器页面复审。 \ No newline at end of file +- **状态:**`[x]` 已完成前端引导和中文说明文档,待前端构建和真实浏览器页面复审。 diff --git a/doc/Scert开发任务清单.md b/doc/Scert开发任务清单.md index ca5000f..22874f8 100644 --- a/doc/Scert开发任务清单.md +++ b/doc/Scert开发任务清单.md @@ -2710,3 +2710,234 @@ Linux Ubuntu 22.04 上的 `Scert-admin` 手动启停、无开机自启动、无 - [x] 源码中未发现 HTML 数字编码中文字符。 - [x] `git diff --check` 通过。 - [!] 浏览器 MCP 当前因共享 Chrome Profile 被其他浏览器进程占用,暂未完成本次实际输入交互截图复审。 + +## 六十三、初始化向导布局与 DNS API 在线测试完善(2026-08-29) + +### 63.1 本轮需求 + +- [✓] 将 Scert 主服务端口放入初始化向导第 1 步。 +- [✓] 将管理页面使用的域名或公网 IP 放入初始化向导第 1 步。 +- [✓] 补全 DNS API 在线测试的临时 TXT 记录创建、公网 DNS 查询确认和自动清理流程。 +- [✓] 在前端展示 DNS 在线测试的创建、查询和清理阶段状态及诊断信息。 + +### 63.2 细节修复 + +- [✓] 将“管理页面访问方式”从嵌套 `label` 调整为独立可访问性控件,避免按钮名称错误继承外层字段标题。 +- [✓] 为域名/IP切换按钮补充 `aria-pressed` 状态。 +- [✓] 将 DNS 验证兜底错误改为中文提示“DNS API 在线验证失败”。 + +### 63.3 验证状态 + +- [✓] 后端单元测试、竞态测试、静态检查和模块校验通过。 +- [✓] 前端生产构建通过。 +- [✓] 无效 DNS 凭据测试能够展示“创建记录:失败”阶段诊断,未暴露 TXT 验证值或凭据。 +- [✓] 桌面浏览器已完成 1440×900、1200×700 宽度/低高度复审,内容区可滚动且底部操作栏保持可见。 +- [!] 真实 DNS 服务商成功链路不能在无用户授权凭据和测试域名时重复执行;现有真实验证记录仍以此前授权测试结果为准。 + +## 六十四、临时文件清理与 DNS 在线测试取消场景保护(2026-08-29) + +### 64.1 文件清理 + +- [✓] 删除根目录已确认无用的 `.codex-*` 临时补丁和临时源码副本。 +- [✓] 删除 `.review-reset-docs.patch`、`backend/codex-restore.patch` 和 `backend/.codex-test-build/`。 +- [✓] 未删除源码、文档、配置、数据库、证书、运行数据、依赖目录或可能正在使用的构建产物。 +- [✓] 清理后确认工作区中未残留上述 Codex 临时文件。 + +### 64.2 DNS 在线测试保护 + +- [✓] 公网 DNS 查询失败或请求被取消后,仍使用独立清理上下文尝试删除临时 TXT 记录。 +- [✓] 清理上下文最多保留 30 秒,避免继承已取消的请求上下文,也避免清理操作无限等待。 +- [✓] 增加查询取消后自动清理的回归测试。 +- [✓] 增加查询失败且自动清理失败时的组合诊断和阶段报告回归测试。 +- [✓] 修复 DNS 测试辅助代码中的连续问号占位错误,恢复可读的中文诊断。 + +### 64.3 验证结果 + +- [✓] DNS Provider 定向测试通过。 +- [✓] `go test -race ./...` 通过。 +- [✓] `go vet ./...` 通过。 +- [✓] `go mod verify` 通过。 +- [✓] `npm.cmd run build` 通过。 +- [✓] `git diff --check` 通过;Git 的换行格式提示不属于差异错误。 +- [✓] 跟踪中的源码和文档未发现连续问号、替换字符或 HTML 数字编码中文。 +- [!] 本轮未重复使用真实 DNS 凭据写入公网记录;真实服务商成功链路继续沿用此前授权测试结果。 + +## 六十五、管理后台登录态门禁接入(2026-08-29) + +### 65.1 本轮需求清单 + +- [✓] 初始化完成后,前端先读取服务端登录会话,再决定显示管理后台或登录页面。 +- [✓] 未登录访问根路径时显示管理员登录界面,不再把管理接口 401 错误误报为核心服务连接失败。 +- [✓] 初始化向导完成后进入登录状态检查,避免初始化完成后直接渲染未授权管理后台。 +- [✓] 登录态检查请求显式携带 Cookie,并保留后端会话过期后的重新登录入口。 + +### 65.2 修改文件 + +- `frontend/src/App.js` + - 增加初始化完成后的 `/api/v1/auth/session` 会话检查。 + - 区分未登录、已登录和服务检查失败状态。 + - 初始化向导完成后将管理后台置为未登录状态。 +- `frontend/src/App.vue` + - 未登录时渲染管理员登录页面。 + - 只有确认已登录后才渲染管理后台。 +- `frontend/src/views/Dashboard/Dashboard.js` + - 管理接口统一携带登录 Cookie。 + - 会话过期时跳转到管理员登录页面,并显示重新登录提示。 + +### 65.3 验证状态 + +- [✓] 前端生产构建。 +- [✓] 后端回归测试、竞态测试、静态检查和模块完整性检查。 +- [x] 通过浏览器隔离模拟已初始化且未登录场景,根路径显示管理员登录页面,未直接渲染管理数据。 +- [x] 通过浏览器隔离模拟已初始化且已登录场景,根路径显示管理后台并完成空数据状态加载。 +- [x] 当前管理后台会话过期时跳转管理员登录页面,并提示重新登录。 +- [!] 当前运行配置仍未完成首次初始化,尚未在真实已初始化运行数据上重复执行登录流程;隔离模拟不替代生产验收。 +- [!] 真实浏览器截图复审仍需独立浏览器 MCP 窗口;不能用移动端预览替代桌面端复审。 + +## 六十六、CNAME 委派与凭据规范化完成记录(2026-08-29) + +### 66.1 开发任务状态 + +- [✓] CNAME Provider 标记为可用,并支持配置专用验证域。 +- [✓] CNAME 委派支持选择已接入的目标 DNS Provider。 +- [✓] CNAME 委派支持嵌套 JSON 凭据,并复用目标 Provider 的凭据校验和 lego 适配器。 +- [✓] DNS-01 临时 TXT 记录的创建和清理转发到专用验证域。 +- [✓] 委派目标禁止再次选择 CNAME 或其他未接入 Provider,避免递归和不明确的适配器行为。 +- [✓] 初始化保存 DNS 凭据前复制并规范化键和值,不修改调用方输入。 +- [✓] 增加委派转发、错误透传、递归保护、凭据 JSON 校验和凭据规范化测试。 + +### 66.2 验证状态 + +- [✓] `go test ./...` 通过。 +- [ ] `go test -race ./...`、`go vet ./...`、`go mod verify` 和前端生产构建等待本轮最终复核。 +- [!] 未使用真实 DNS 凭据执行公网 CNAME、TXT 传播和 Let’s Encrypt Production 验收;该项必须在用户授权的真实域名环境执行。 + +## 六十七、全量代码复审与最终验证记录(2026-08-29) + +### 67.1 本轮需求与开发状态 + +- [✓] 系统设置页面补充服务监听地址、服务端口、HTTPS 模式、管理页面域名和管理页面公网 IP。 +- [✓] 初始化向导保留首次运行所需的端口和 Web 访问方式配置,并与服务端配置字段保持一致。 +- [✓] DNS API 在线测试支持服务商目录、动态凭据字段、CNAME 委派专用验证域、目标 Provider 和嵌套凭据 JSON。 +- [✓] DNS 在线测试覆盖临时 TXT 记录创建、公网查询、自动清理和失败阶段报告。 +- [✓] CNAME 委派 Provider 已接入,目标 Provider 禁止再次选择 CNAME 或未接入 Provider。 +- [✓] DNS 凭据在验证前规范化并在验证成功后加密保存,普通配置和接口响应不返回明文凭据。 +- [✓] 设置接口仅在监听地址、服务端口或 HTTPS 模式变化时返回 `restart_required: true`。 +- [✓] 手动续期检查接口已接入管理后台。 + +### 67.2 实际浏览器和接口复核 + +- [✓] 当前源码后端已重新构建并启动于 `127.0.0.1:5200`。 +- [✓] 前端开发服务运行于 `127.0.0.1:5273`,独立 Chrome DevTools 页面可正常访问。 +- [✓] 初始化向导第 1 步实际显示 Scert 主服务端口、管理页面域名/IP 切换和密码重置地址预览。 +- [✓] DNS Provider 实际显示“CNAME 委派”,不再显示“适配器待开放”。 +- [✓] 选择 CNAME 委派后实际显示专用验证域、委派目标 DNS 服务商和委派凭据 JSON 字段。 +- [✓] 使用伪造 Cloudflare 凭据实际触发在线测试,页面显示“创建记录:失败”,未误报验证成功。 +- [✓] 设置和初始化接口实际返回服务端口、Web 域名/IP、传播参数和 DNS Provider 状态。 + +### 67.3 最终自动化验证 + +- [✓] `go test ./...` +- [✓] `go test -race ./...` +- [✓] `go vet ./...` +- [✓] `go mod verify` +- [✓] `npm.cmd run build` +- [✓] `git diff --check` + +### 67.4 文件清理与验收边界 + +- [✓] 根目录没有发现 `.codex` 目录或已知 Codex 临时源码副本。 +- [!] `.runtime` 中仍有 3 个已确认的 Codex 临时补丁文件;本轮逐个删除命令被当前执行环境安全策略拒绝,因此未绕过策略强制删除。 +- [✓] 未删除源码、文档、配置、数据库、证书、密钥、运行目录或构建产物。 +- [!] 未在本轮使用新的真实 DNS 凭据、Let’s Encrypt Production、SSH 私钥、远程服务器或生产 HTTPS 环境;这些仍需用户授权后的实机验收。 +- [✓] 代码层开发和本地验证完成,Git 提交与推送仍未执行。 +## 六十八、部署脚本、发布构建与通知安全复核(2026-08-30) + +### 68.1 本轮需求清单 + +- [✓] 增加 Windows 安装器,检查平台、管理员权限、安装产物、服务名称和系统工具。 +- [✓] Windows 安装器创建程序、配置、数据、日志、备份、文档、运行时和证书目录。 +- [✓] Windows 安装器使用 `LocalService` 注册 `Scert` 和手动启动的 `Scert-admin`,并设置 ACL。 +- [✓] Windows 安装器不启动服务、不创建公网防火墙规则、不删除已有配置、数据库、证书和备份。 +- [✓] 增加 Windows amd64 和 Linux amd64 的跨平台发布构建脚本。 +- [✓] 发布构建输出核心服务、密码重置程序和 SHA-256 校验清单。 +- [✓] 通知会话认证保留密码原始字节,不对密码使用 `TrimSpace`;登录业务错误解析 `errorNo`,并保留非敏感错误说明。 +- [✓] 通知发送接口仍按“进入邮件服务队列”处理,不将 HTTP 成功误称为最终收件成功。 + +### 68.2 新增和修改文件 + +- `deploy/install-windows.ps1` +- `deploy/README.md` +- `build/build-release.ps1` +- `build/README.md` +- `backend/internal/notification/service.go` +- `backend/internal/notification/service_test.go` + +### 68.3 验证边界 + +- [x] Windows 安装脚本已完成代码编写,等待 Windows 管理员权限、服务控制台和 ACL 实机复审。 +- [x] 发布构建脚本已完成代码编写,等待本轮执行 Windows/Linux 目标构建。 +- [x] 通知会话流程已完成本地测试覆盖,真实临时邮箱最终投递仍需查看邮件详情状态和收件证据。 +- [!] 未使用真实 DNS 凭据、Let’s Encrypt Production、SSH 私钥、远程服务器或生产 HTTPS 环境;这些项目仍需用户授权后的实机验收。 + +## 六十九、SSH 密钥随机路径与配置引导复核(2026-08-30) + +### 69.1 本轮需求与实现状态 + +- [✓] 本机 SSH 密钥统一使用 `/ssl/ssh/` 目录生成。 +- [✓] 密钥文件名使用 `用户名+scert-随机标识` 格式,公钥文件追加 `.pub`。 +- [✓] 每次打开 SSH 密钥配置弹窗都会重新生成随机标识,避免不同主机或不同配置复用固定文件名。 +- [✓] Windows、Linux/macOS 密钥生成命令和公钥安装命令统一使用当前随机路径。 +- [✓] 页面显示本次密钥文件名、本地私钥路径、本地公钥路径和远程登录目标。 +- [✓] Scert 后端仍仅保存加密敏感信息引用,不将本地明文私钥路径或私钥内容写入普通配置。 + +### 69.2 本轮验证结果 + +- [✓] `npm.cmd run build` 通过。 +- [✓] 浏览器复核首次打开和再次打开弹窗时随机文件名发生变化。 +- [✓] 浏览器复核服务器配置填写 `deploy` 和 `192.0.2.50` 后,路径和 SSH 目标同步更新。 +- [✓] 浏览器复核 Windows 与 Linux/macOS 命令均包含当前随机路径和公钥 `.pub` 路径。 +- [✓] 桌面端 1440×901 视口下弹窗宽度为 1080px,页面背景滚动已锁定,弹窗内部无垂直溢出。 +- [!] 真实 SSH 主机、公钥安装、私钥登录和证书部署仍需用户提供并授权实机环境后验收。 + +## 七十、证书目录结构合并与当前版本简化(2026-08-30) + +### 70.1 本轮需求清单 + +- [✓] 合并生产和开发证书目录层级,申请环境继续由域名配置中的 ACME 环境字段区分。 +- [✓] 合并当前和历史版本目录层级,正式证书目录只保留当前使用版本。 +- [✓] 版本目录名称改为 `YYYYMMDD-Vx.x`,例如 `20260830-V1.0`。 +- [✓] 同一天重复保存时递增版本号,避免目录覆盖。 +- [✓] 保留备份目录用于保存失败回滚所需的旧证书文件,不将备份目录作为历史版本列表。 +- [✓] 前端移除历史版本查看和恢复入口,只显示当前证书状态。 + +### 70.2 代码和文档调整 + +- `backend/internal/certificate/lifecycle.go` +- `backend/internal/certificate/lifecycle_version_test.go` +- `backend/internal/certificate/service_test.go` +- `frontend/src/views/Dashboard/Dashboard.vue` +- `frontend/src/views/Dashboard/Dashboard.js` +- `frontend/src/views/Dashboard/Dashboard.css` +- `doc/SSL服务程序需求确认文档.md` +- `doc/SSL服务程序技术架构设计文档.md` + +### 70.3 验证状态 + +- [x] 证书生命周期专项测试已通过,等待全量后端测试复审。 +- [x] 新目录格式、重复保存唯一性、旧当前目录清理和失败回滚已覆盖自动化测试。 +- [x] 前端历史版本面板和恢复操作已移除,等待前端构建复审。 +- [!] 旧安装目录中的历史文件未执行批量清理,避免未经授权删除用户证书、私钥或备份;后续迁移清理需单独授权。 + +## 七十一、登录界面用户化(2026-08-30) + +### 71.1 本轮需求清单 + +- [✓] 登录页面标题由“管理员登录”调整为“用户登录”。 +- [✓] 登录页面说明、密码占位符和无障碍标签统一使用“用户”文案。 +- [✓] 登录流程阶段标题同步调整为“用户登录”,不改变服务端认证、角色识别和会话逻辑。 + +### 71.2 验证状态 + +- [✓] 登录相关前端文件已完成修改,等待本轮构建复审。 +- [!] 后端仍根据服务端返回结果识别超级管理员、管理员和普通用户,未因页面文案调整而改变权限模型。 \ No newline at end of file diff --git a/doc/邮件通知配置说明.md b/doc/邮件通知配置说明.md index 04e493a..f9adfdc 100644 --- a/doc/邮件通知配置说明.md +++ b/doc/邮件通知配置说明.md @@ -2,7 +2,7 @@ ## 1. 配置目的 -Scert 的证书申请、续期、部署和校验任务完成后,可以通过第三方邮件服务 API 发送通知。SMTP、IMAP、POP3 协议仅作为外部邮件服务兼容性参考,Scert 不实现邮件服务器端;当前已接入 HTTP 邮件 API 通知。 +Scert 的证书申请、续期、部署和校验任务完成后,可以通过第三方邮件服务 API 或 SMTP 服务发送通知。Scert 只实现出站通知客户端,不实现 SMTP、IMAP、POP3 邮件服务器端;HTTP 邮件 API 和 SMTP 出站通知均已接入。 ## 2. HTTP 邮件服务配置 @@ -58,7 +58,7 @@ Smail 当前接口需要登录会话 Cookie、`smail_csrf` Cookie、`X-CSRF-Toke ## 6. 当前实现边界 -当前阶段已完成邮件通知配置的保存、校验、初始化接口、CLI/Web 表单接入和 HTTP 通知发送器。SMTP 发送器尚未接入;当前应优先使用 HTTP 邮件 API 方式配置邮件服务。Smail 登录会话可通过 `session` 认证模式自动建立和刷新。 +当前阶段已完成邮件通知配置的保存、校验、初始化接口、CLI/Web 表单接入、HTTP 通知发送器和 SMTP 出站通知发送器。SMTP 支持 `plain`、`starttls` 和 `implicit_tls` 三种连接模式;生产环境建议使用 STARTTLS 或隐式 TLS。Smail 登录会话可通过 `session` 认证模式自动建立和刷新。 ## 7. 当前开发状态补充 @@ -73,4 +73,4 @@ Smail 当前接口需要登录会话 Cookie、`smail_csrf` Cookie、`X-CSRF-Toke - 将所有 2xx 响应视为成功,其他响应按重试配置处理。 - 证书工作流会在任务成功、失败或部署错误后触发通知;通知发送失败会写入 Scert 日志,不覆盖原证书任务结果。 -SMTP 发送器仍未接入。初始化界面和 CLI 不再暴露 SMTP 开关,旧配置字段仅为兼容已有配置文件保留,并不会在初始化时启用。Smail 登录会话的自动适配已通过 `session` 模式接入,仍需在目标部署环境使用实际凭据进行上线前复核。 +SMTP 出站通知已经接入。初始化界面和 CLI 可以配置 SMTP 主机、端口、用户名、凭据引用、连接模式和明文认证开关;SMTP 密码只保存到加密敏感信息存储,配置文件仅保存 `secret://` 凭据引用。明文连接认证默认拒绝,只有明确启用 `SMTP 明文认证` 后才允许。CLI 可使用 `scert config set-secret --key notification.smtp_password` 保存敏感值。SMTP 是出站连接,Scert 不需要开放 SMTP 入站端口。Smail 登录会话的自动适配已通过 `session` 模式接入,仍需在目标部署环境使用实际凭据进行上线前复核。 diff --git a/frontend/src/App.js b/frontend/src/App.js index d83e608..a7ffbe6 100644 --- a/frontend/src/App.js +++ b/frontend/src/App.js @@ -2,6 +2,7 @@ import { onMounted, ref } from "vue"; export function useAppShell() { const setupState = ref(null); + const authenticated = ref(null); const bootstrapping = ref(true); const error = ref(""); const routePath = window.location.pathname.replace(/\/+$/, "") || "/"; @@ -15,15 +16,36 @@ export function useAppShell() { const result = await response.json().catch(() => ({})); if (!response.ok) throw new Error(result.error || "读取初始化状态失败"); setupState.value = result; + if (result.initialized) { + await checkAuth(); + } else { + authenticated.value = false; + } } catch (err) { + setupState.value = null; + authenticated.value = null; error.value = err.message || "无法连接核心服务,请先启动 scert serve"; } finally { bootstrapping.value = false; } } + async function checkAuth() { + const response = await fetch("/api/v1/auth/session", { + credentials: "include", + }); + if (response.status === 401) { + authenticated.value = false; + return; + } + const result = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(result.error || "读取登录状态失败"); + authenticated.value = result.authenticated === true; + } + function handleInitialized() { setupState.value = { ...setupState.value, initialized: true }; + authenticated.value = false; } onMounted(() => { @@ -36,6 +58,7 @@ export function useAppShell() { return { setupState, + authenticated, bootstrapping, error, routePath, diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 62db38e..07926c3 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -8,6 +8,7 @@ import SuperAdminReset from "./views/SuperAdminReset/SuperAdminReset.vue"; const { setupState, + authenticated, bootstrapping, error, routePath, @@ -41,5 +42,7 @@ const { @initialized="handleInitialized" /> - + + + diff --git a/frontend/src/views/Dashboard/Dashboard.css b/frontend/src/views/Dashboard/Dashboard.css index d6950e7..949367f 100644 --- a/frontend/src/views/Dashboard/Dashboard.css +++ b/frontend/src/views/Dashboard/Dashboard.css @@ -155,6 +155,59 @@ h2 { .server-panel { margin-top: 18px; } +.operations-panel { + margin-top: 18px; +} +.operation-columns { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 18px; +} +.operation-columns h3 { + margin: 0 0 10px; + color: #32405a; + font-size: 15px; +} +.record-list { + display: grid; + gap: 8px; +} +.record-row { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + min-height: 54px; + padding: 11px 12px; + border: 1px solid #edf0f5; + border-radius: 11px; + background: #fbfcfe; +} +.record-row > div { + display: grid; + gap: 5px; + min-width: 0; +} +.record-row strong, +.record-row .muted { + overflow-wrap: anywhere; +} +.compact-empty { + min-height: 80px; + padding: 18px 8px; + font-size: 12px; +} +.settings-modal { + width: min(100%, 760px); +} +.settings-modal h3 { + margin: 22px 0 10px; + color: #32405a; + font-size: 15px; +} +.settings-modal h3:first-of-type { + margin-top: 0; +} .panel-heading { margin-bottom: 22px; } @@ -258,18 +311,59 @@ code { z-index: 10; display: grid; place-items: center; - padding: 20px; - background: rgba(18, 31, 58, 0.45); + overflow-y: auto; + padding: clamp(16px, 3vw, 32px); + background: rgba(18, 31, 58, 0.52); + backdrop-filter: blur(2px); } .modal-card { - width: min(100%, 560px); - max-height: calc(100vh - 40px); + width: min(100%, 860px); + max-height: calc(100vh - 32px); overflow: auto; - padding: 30px; - border: 1px solid #e2e8f2; + padding: 32px; + border: 1px solid #b9cbe0; border-radius: 22px; background: #fff; - box-shadow: 0 24px 70px rgba(19, 38, 79, 0.25); + box-shadow: + 0 30px 86px rgba(19, 38, 79, 0.34), + 0 0 0 5px rgba(227, 237, 248, 0.72), + inset 0 1px 0 rgba(255, 255, 255, 0.96); +} +.ssh-key-modal { + width: min(100%, 1080px); + overflow: hidden; + padding: 30px 34px; + background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%); +} +.ssh-key-modal form { + display: grid; + grid-template-columns: minmax(0, 1.05fr) minmax(360px, 0.95fr); + align-items: start; + gap: 24px; +} +.ssh-key-modal .ssh-key-guide { + grid-column: 1; + margin-bottom: 0; +} +.ssh-key-form-fields { + grid-column: 2; + min-width: 0; + padding: 18px 18px 16px; + border: 1px solid #cfdeed; + border-radius: 14px; + background: rgba(255, 255, 255, 0.94); + box-shadow: 0 8px 22px rgba(45, 79, 123, 0.06); +} +.ssh-key-form-fields .field:last-of-type { + margin-bottom: 14px; +} +.ssh-key-form-fields .field textarea { + min-height: 230px; +} +.ssh-key-form-fields .modal-actions { + margin-top: 20px; + padding-top: 16px; + border-top: 1px solid #dbe5f0; } .modal-heading { display: flex; @@ -277,6 +371,8 @@ code { justify-content: space-between; gap: 20px; margin-bottom: 24px; + padding-bottom: 18px; + border-bottom: 1px solid #dbe5f0; } .modal-heading h2 { margin-bottom: 0; @@ -312,12 +408,12 @@ code { .field select, .field textarea { width: 100%; - border: 1px solid #d8e0eb; + border: 1px solid #bdcde0; border-radius: 10px; outline: 0; padding: 11px 12px; color: #172033; - background: #fbfcfe; + background: #ffffff; font: inherit; font-weight: 500; } @@ -443,6 +539,9 @@ code { .metrics-grid { grid-template-columns: repeat(2, 1fr); } + .operation-columns { + grid-template-columns: 1fr; + } .panel { padding: 20px; } @@ -473,6 +572,20 @@ code { } } +@media (max-width: 900px) { + .ssh-key-modal { + width: min(100%, 760px); + } + + .ssh-key-modal form { + display: block; + } + + .ssh-key-modal .ssh-key-guide { + margin-bottom: 18px; + } +} + .field-label-row { display: flex; align-items: center; @@ -504,9 +617,10 @@ code { .ssh-key-guide { margin: 0 0 18px; padding: 16px; - border: 1px solid #dbe7f7; + border: 1px solid #c4d7eb; border-radius: 12px; - background: linear-gradient(135deg, #f7fbff, #f3f7fc); + background: linear-gradient(135deg, #f4f9ff, #edf4fc); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.9); } .ssh-key-guide-heading { @@ -544,6 +658,7 @@ code { gap: 9px; min-width: 0; padding: 11px; + border: 1px solid #d7e3f0; border-radius: 9px; background: #ffffff; } @@ -605,10 +720,58 @@ code { font-weight: 700; } +.ssh-key-path-line, +.ssh-key-path-summary { + display: grid; + gap: 8px; + margin: 8px 0; + padding: 8px 10px; + border: 1px solid #c7d8e9; + border-radius: 9px; + color: #3b5778; + background: #ffffff; + font-size: 11px; +} + +.ssh-key-path-line { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + +.ssh-key-path-line code, +.ssh-key-path-summary code { + overflow-wrap: anywhere; + color: #294765; + font-family: Consolas, "SFMono-Regular", monospace; +} + +.ssh-key-path-summary { + grid-template-columns: repeat(2, minmax(0, 1fr)); + margin-top: 0; + gap: 6px; + background: #f8fbff; +} + +.ssh-key-path-summary > div { + display: grid; + gap: 4px; + min-width: 0; +} + +.ssh-key-path-summary > div:last-child { + grid-column: 1 / -1; +} + +.ssh-key-path-summary span { + color: #71839a; +} + .ssh-command-card { margin-top: 10px; padding: 11px 12px; - border: 1px solid #dfe8f3; + border: 1px solid #c7d8e9; border-radius: 9px; background: #ffffff; } @@ -661,6 +824,14 @@ code { grid-template-columns: 1fr; } + .ssh-key-path-summary { + grid-template-columns: 1fr; + } + + .ssh-key-path-summary > div:last-child { + grid-column: auto; + } + .field-label-row { align-items: flex-start; } @@ -686,4 +857,30 @@ code { background: #e2efff; font-size: 11px; white-space: nowrap; +} + +.certificate-import-modal { + width: min(100%, 680px); +} + +.import-result { + display: grid; + gap: 6px; + margin: 16px 0; + padding: 14px 16px; + border: 1px solid #bfe7d1; + border-radius: 12px; + color: #24734b; + background: #effbf4; +} + +.import-result span { + color: #4c7a61; + font-size: 13px; +} + +@media (min-width: 1100px) { + .settings-modal { + width: min(100%, 980px); + } } \ No newline at end of file diff --git a/frontend/src/views/Dashboard/Dashboard.js b/frontend/src/views/Dashboard/Dashboard.js index 7c3c46f..9f2edf0 100644 --- a/frontend/src/views/Dashboard/Dashboard.js +++ b/frontend/src/views/Dashboard/Dashboard.js @@ -1,4 +1,4 @@ -import { computed, onMounted, ref } from "vue"; +import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue"; export function useDashboard() { const scertLogo = "/Scert.png"; @@ -7,6 +7,10 @@ export function useDashboard() { const domains = ref([]); const servers = ref([]); const sshKeys = ref([]); + const certificates = ref([]); + const tasks = ref([]); + const auditLogs = ref([]); + const settings = ref(null); const domainServers = ref({}); const loading = ref(true); const saving = ref(false); @@ -24,19 +28,63 @@ export function useDashboard() { const sshKeyFormError = ref(""); const sshKeyPlatform = ref("windows"); const sshKeyPassphraseVisible = ref(false); + const sshKeyCommandUsername = ref("用户名"); + const sshKeyCommandHost = ref("服务器地址"); + const sshKeyRandomSuffix = ref(createSSHKeyRandomSuffix()); + const showSettings = ref(false); + const settingsSaving = ref(false); + const settingsError = ref(""); + const settingsForm = ref(createEmptySettingsForm()); + const showCertificateImport = ref(false); + const importDomain = ref(null); + const importSaving = ref(false); + const importError = ref(""); + const importResult = ref(null); + const importFiles = ref({ + certificate: null, + private_key: null, + issuer_bundle: null, + }); + const hasOpenModal = computed( + () => + showForm.value || + showServerForm.value || + showSSHKeyForm.value || + showSettings.value, + ); + let previousBodyOverflow = ""; - const sshKeyCommands = { + watch(hasOpenModal, (isOpen) => { + if (isOpen) { + previousBodyOverflow = document.body.style.overflow; + document.body.style.overflow = "hidden"; + return; + } + document.body.style.overflow = previousBodyOverflow; + }); + + const sshKeyFileName = computed( + () => + `${sanitizeSSHKeySegment(sshKeyCommandUsername.value, "用户名")}+scert-${sshKeyRandomSuffix.value}`, + ); + const sshKeyPath = computed(() => `/ssl/ssh/${sshKeyFileName.value}`); + const sshKeyPublicPath = computed(() => `${sshKeyPath.value}.pub`); + const sshKeyRemoteTarget = computed( + () => + `${sanitizeSSHKeySegment(sshKeyCommandUsername.value, "用户名")}@${sanitizeSSHHost(sshKeyCommandHost.value)}`, + ); + const sshKeyCommands = computed(() => ({ windows: - 'ssh-keygen -t ed25519 -C "scert-deploy" -f "$HOME\\.ssh\\scert_deploy_ed25519"', + `New-Item -ItemType Directory -Force -Path "/ssl/ssh" | Out-Null; ssh-keygen -t ed25519 -C "scert-deploy" -f "${sshKeyPath.value}"`, linux: - 'ssh-keygen -t ed25519 -C "scert-deploy" -f ~/.ssh/scert_deploy_ed25519', - }; - const sshPublicKeyCommands = { + `sudo install -d -m 700 -o "$(id -un)" -g "$(id -gn)" /ssl/ssh && ssh-keygen -t ed25519 -C "scert-deploy" -f "${sshKeyPath.value}"`, + })); + const sshPublicKeyCommands = computed(() => ({ windows: - 'Get-Content "$HOME\\.ssh\\scert_deploy_ed25519.pub" | ssh root@服务器地址 "umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys"', + `Get-Content "${sshKeyPublicPath.value}" | ssh ${sshKeyRemoteTarget.value} "umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys"`, linux: - 'ssh-copy-id -i ~/.ssh/scert_deploy_ed25519.pub 用户名@服务器地址', - }; + `ssh-copy-id -i "${sshKeyPublicPath.value}" ${sshKeyRemoteTarget.value}`, + })); const certificateTypeLabels = { single: "单域名", @@ -81,6 +129,18 @@ export function useDashboard() { const serverForm = ref(createEmptyServerForm()); const sshKeyForm = ref(createEmptySSHKeyForm()); + async function fetchAdmin(path, options = {}) { + const response = await fetch(path, { + ...options, + credentials: "include", + }); + if (response.status === 401) { + window.location.assign("/login"); + throw new Error("登录会话已过期,请重新登录"); + } + return response; + } + function createEmptyForm() { return { name: "", @@ -114,6 +174,94 @@ export function useDashboard() { return { name: "", private_key: "", passphrase: "" }; } + function createSSHKeyRandomSuffix() { + const bytes = new Uint8Array(6); + crypto.getRandomValues(bytes); + return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join( + "", + ); + } + + function sanitizeSSHKeySegment(value, fallback) { + const normalized = String(value || "") + .trim() + .replace(/[^\p{L}\p{N}._-]+/gu, "-") + .replace(/^-+|-+$/g, ""); + return normalized || fallback; + } + + function sanitizeSSHHost(value) { + const normalized = String(value || "") + .trim() + .replace(/[^a-zA-Z0-9.:[\]-]+/g, ""); + return normalized || "服务器地址"; + } + + function createEmptySettingsForm() { + return { + server: { host: "", port: 5200, https_mode: "direct" }, + web: { enabled: true, hostname: "", public_ip: "" }, + paths: { certificate: "" }, + acme: { + ca: "letsencrypt", + environment: "staging", + account_email: "", + renewal_threshold_days: 6, + propagation_timeout_secs: 900, + propagation_polling_interval_secs: 10, + }, + dns: { provider: "" }, + notification: { + http_enabled: false, + smtp_enabled: false, + provider: "", + endpoint: "", + http_path: "/api/email/send", + http_login_path: "/api/login", + http_auth_mode: "none", + event_mode: "detailed", + include_deployment_details: true, + include_certificate_serial: false, + include_management_url: false, + sender_name: "Scert", + sender_email: "", + recipients: [], + timeout_secs: 10, + retry_count: 3, + retry_intervals_secs: [30, 120, 600], + smtp_host: "", + smtp_port: 587, + smtp_username: "", + smtp_password: "", + smtp_mode: "starttls", + smtp_allow_plaintext_auth: false, + smtp_credential_configured: false, + }, + }; + } + + function normalizeSettings(value) { + const defaults = createEmptySettingsForm(); + const source = value || {}; + return { + ...defaults, + ...source, + server: { ...defaults.server, ...(source.server || {}) }, + web: { ...defaults.web, ...(source.web || {}) }, + paths: { ...defaults.paths, ...(source.paths || {}) }, + acme: { ...defaults.acme, ...(source.acme || {}) }, + dns: { ...defaults.dns, ...(source.dns || {}) }, + notification: { + ...defaults.notification, + ...(source.notification || {}), + smtp_password: "", + recipients: Array.isArray(source.notification?.recipients) + ? source.notification.recipients + : [], + }, + }; + } + function displayLabel(labels, value) { return labels[value] || (value ? "未知" : "—"); } @@ -195,6 +343,10 @@ export function useDashboard() { sshKeyFormError.value = ""; sshKeyPlatform.value = "windows"; sshKeyPassphraseVisible.value = false; + sshKeyCommandUsername.value = serverForm.value.username.trim() || "用户名"; + sshKeyCommandHost.value = serverForm.value.address.trim() || "服务器地址"; + sshKeyRandomSuffix.value = createSSHKeyRandomSuffix(); + sshKeyForm.value.name = sshKeyFileName.value; showSSHKeyForm.value = true; } @@ -234,7 +386,7 @@ export function useDashboard() { sshKeyFormError.value = ""; sshKeySaving.value = true; try { - const response = await fetch("/api/v1/ssh-keys", { + const response = await fetchAdmin("/api/v1/ssh-keys", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(sshKeyForm.value), @@ -260,7 +412,7 @@ export function useDashboard() { ) return; try { - const response = await fetch(`/api/v1/ssh-keys/${item.id}`, { + const response = await fetchAdmin(`/api/v1/ssh-keys/${item.id}`, { method: "DELETE", }); const result = await response.json().catch(() => ({})); @@ -299,7 +451,7 @@ export function useDashboard() { const path = serverEditingId.value ? `/api/v1/servers/${serverEditingId.value}` : "/api/v1/servers"; - const response = await fetch(path, { + const response = await fetchAdmin(path, { method: serverEditingId.value ? "PUT" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), @@ -318,11 +470,147 @@ export function useDashboard() { } } + async function runDomainAction(item, action, successMessage) { + error.value = ""; + notice.value = ""; + try { + const response = await fetchAdmin(`/api/v1/domains/${item.id}/${action}`, { + method: "POST", + }); + const result = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(result.error || "域名操作失败"); + notice.value = successMessage; + await loadData(); + } catch (err) { + error.value = err.message || "域名操作失败"; + } + } + + function issueDomain(item) { + return runDomainAction(item, "issue", `已提交 ${item.name} 的证书申请`); + } + + function validateDomain(item) { + return runDomainAction(item, "certificate/validate", `已提交 ${item.name} 的证书校验`); + } + + function deployDomain(item) { + return runDomainAction(item, "deploy", `已提交 ${item.name} 的证书部署`); + } + + async function runRenewalNow() { + error.value = ""; + notice.value = ""; + try { + const response = await fetchAdmin("/api/v1/renewal/run", { method: "POST" }); + const result = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(result.error || "执行续期检查失败"); + const report = result.report || {}; + notice.value = `续期检查完成:检查 ${report.checked || 0} 项,选中 ${report.selected || 0} 项,成功 ${report.succeeded || 0} 项,失败 ${report.failed || 0} 项`; + await loadData(); + } catch (err) { + error.value = err.message || "执行续期检查失败"; + } + } + + function openSettings() { + settingsError.value = ""; + settingsForm.value = normalizeSettings(settings.value); + showSettings.value = true; + } + + function closeSettings() { + if (!settingsSaving.value) showSettings.value = false; + } + + async function saveSettings() { + settingsError.value = ""; + settingsSaving.value = true; + try { + const response = await fetchAdmin("/api/v1/settings", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(settingsForm.value), + }); + const result = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(result.error || "保存系统设置失败"); + settings.value = result.settings; + showSettings.value = false; + notice.value = result.message || "系统设置已保存"; + await loadData(); + } catch (err) { + settingsError.value = err.message || "保存系统设置失败"; + } finally { + settingsSaving.value = false; + } + } + + function openCertificateImport(item) { + importDomain.value = item; + importFiles.value = { + certificate: null, + private_key: null, + issuer_bundle: null, + }; + importResult.value = null; + importError.value = ""; + showCertificateImport.value = true; + } + + function closeCertificateImport() { + if (!importSaving.value) showCertificateImport.value = false; + } + + function selectCertificateImportFile(kind, event) { + importFiles.value[kind] = event.target.files?.[0] || null; + event.target.value = ""; + importError.value = ""; + } + + async function importCertificate() { + importError.value = ""; + importResult.value = null; + if (!importFiles.value.certificate || !importFiles.value.private_key) { + importError.value = "请选择证书文件和私钥文件"; + return; + } + const maxSize = 20 * 1024 * 1024; + const files = Object.values(importFiles.value).filter(Boolean); + if (files.some((file) => file.size > maxSize)) { + importError.value = "单个证书文件不能超过 20 MB"; + return; + } + importSaving.value = true; + try { + const body = new FormData(); + body.append("certificate", importFiles.value.certificate); + body.append("private_key", importFiles.value.private_key); + if (importFiles.value.issuer_bundle) { + body.append("issuer_bundle", importFiles.value.issuer_bundle); + } + const response = await fetchAdmin( + `/api/v1/domains/${importDomain.value.id}/certificate/import`, + { method: "POST", body }, + ); + const result = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(result.error || "导入证书失败"); + } + importResult.value = result; + notice.value = `域名 ${importDomain.value.name} 的证书已导入`; + await loadData(); + } catch (err) { + importError.value = err.message || "导入证书失败"; + } finally { + importSaving.value = false; + } + } + async function deleteServer(item) { if (!window.confirm(`确定删除服务器“${item.name}”吗?关联域名也会解除。`)) return; try { - const response = await fetch(`/api/v1/servers/${item.id}`, { + const response = await fetchAdmin(`/api/v1/servers/${item.id}`, { method: "DELETE", }); const result = await response.json().catch(() => ({})); @@ -335,7 +623,7 @@ export function useDashboard() { } async function saveDomainServers(domainId, serverIds) { - const response = await fetch(`/api/v1/domains/${domainId}/servers`, { + const response = await fetchAdmin(`/api/v1/domains/${domainId}/servers`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ server_ids: serverIds }), @@ -382,7 +670,7 @@ export function useDashboard() { const path = isEditing.value ? `/api/v1/domains/${editingId.value}` : "/api/v1/domains"; - const response = await fetch(path, { + const response = await fetchAdmin(path, { method: isEditing.value ? "PUT" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), @@ -412,7 +700,7 @@ export function useDashboard() { error.value = ""; notice.value = ""; try { - const response = await fetch(`/api/v1/domains/${item.id}`, { + const response = await fetchAdmin(`/api/v1/domains/${item.id}`, { method: "DELETE", }); if (!response.ok) { @@ -430,27 +718,42 @@ export function useDashboard() { loading.value = true; error.value = ""; try { - const [statusResponse, domainResponse, serverResponse, sshKeyResponse] = - await Promise.all([ - fetch("/api/v1/status"), - fetch("/api/v1/domains"), - fetch("/api/v1/servers"), - fetch("/api/v1/ssh-keys"), - ]); - if ( - !statusResponse.ok || - !domainResponse.ok || - !serverResponse.ok || - !sshKeyResponse.ok - ) - throw new Error("服务接口返回失败"); + const [ + statusResponse, + domainResponse, + serverResponse, + sshKeyResponse, + certificateResponse, + taskResponse, + auditResponse, + settingsResponse, + ] = await Promise.all([ + fetchAdmin("/api/v1/status"), + fetchAdmin("/api/v1/domains"), + fetchAdmin("/api/v1/servers"), + fetchAdmin("/api/v1/ssh-keys"), + fetchAdmin("/api/v1/certificates"), + fetchAdmin("/api/v1/tasks?limit=20"), + fetchAdmin("/api/v1/audit-logs?limit=20"), + fetchAdmin("/api/v1/settings"), + ]); + if ([statusResponse, domainResponse, serverResponse, sshKeyResponse, certificateResponse, taskResponse, auditResponse, settingsResponse].some((response) => !response.ok)) { + throw new Error("读取管理数据失败"); + } status.value = await statusResponse.json(); domains.value = (await domainResponse.json()).items || []; servers.value = (await serverResponse.json()).items || []; sshKeys.value = (await sshKeyResponse.json()).items || []; + certificates.value = (await certificateResponse.json()).items || []; + tasks.value = (await taskResponse.json()).items || []; + auditLogs.value = (await auditResponse.json()).items || []; + settings.value = await settingsResponse.json(); + settingsForm.value = normalizeSettings(settings.value); const associations = await Promise.all( domains.value.map(async (item) => { - const response = await fetch(`/api/v1/domains/${item.id}/servers`); + const response = await fetchAdmin( + `/api/v1/domains/${item.id}/servers`, + ); return [ item.id, response.ok ? (await response.json()).items || [] : [], @@ -466,6 +769,9 @@ export function useDashboard() { } onMounted(loadData); + onBeforeUnmount(() => { + document.body.style.overflow = previousBodyOverflow; + }); return { scertLogo, @@ -473,6 +779,11 @@ export function useDashboard() { domains, servers, sshKeys, + certificates, + tasks, + auditLogs, + settings, + settingsForm, domainServers, loading, saving, @@ -500,6 +811,19 @@ export function useDashboard() { sshKeyForm, sshKeyPlatform, sshKeyPassphraseVisible, + sshKeyCommandUsername, + sshKeyCommandHost, + sshKeyFileName, + sshKeyPath, + sshKeyPublicPath, + showSettings, + settingsSaving, + settingsError, + showCertificateImport, + importDomain, + importSaving, + importError, + importResult, sshKeyCommands, sshPublicKeyCommands, defaultCertificatePath, @@ -517,6 +841,10 @@ export function useDashboard() { copySSHKeyCommand, saveSSHKey, deleteSSHKey, + openCertificateImport, + closeCertificateImport, + selectCertificateImportFile, + importCertificate, saveServer, deleteServer, saveDomain, diff --git a/frontend/src/views/Dashboard/Dashboard.vue b/frontend/src/views/Dashboard/Dashboard.vue index bb0354e..5ffcffd 100644 --- a/frontend/src/views/Dashboard/Dashboard.vue +++ b/frontend/src/views/Dashboard/Dashboard.vue @@ -7,6 +7,11 @@ const { domains, servers, sshKeys, + certificates, + tasks, + auditLogs, + settings, + settingsForm, domainServers, loading, saving, @@ -34,6 +39,14 @@ const { sshKeyForm, sshKeyPlatform, sshKeyPassphraseVisible, + sshKeyCommandUsername, + sshKeyCommandHost, + sshKeyFileName, + sshKeyPath, + sshKeyPublicPath, + showSettings, + settingsSaving, + settingsError, sshKeyCommands, sshPublicKeyCommands, defaultCertificatePath, @@ -56,6 +69,13 @@ const { saveDomain, deleteDomain, loadData, + openSettings, + closeSettings, + saveSettings, + issueDomain, + validateDomain, + deployDomain, + runRenewalNow, displayLabel, formatDate, daysRemaining, @@ -74,6 +94,12 @@ const { + + + + + + +
+

服务监听

+
+ + +
+
+ + +
+
+ + +
+

ACME 设置

+
+ + +
+
+ + +
+

HTTP 通知

+
+ + +
+
+ + +
+ +

SMTP 通知

+ +
+ + +
+
+ + +
+
+ + +
+

+ {{ settingsForm.notification.smtp_credential_configured ? "SMTP 凭据已配置;密码不会回显。填写新密码后保存即可更新。" : "SMTP 凭据尚未配置;启用 SMTP 时请填写用户名和密码。" }} +

+

{{ settingsError }}

+ +
+ + + + + +
+ 本次密钥文件名 + {{ sshKeyFileName }} + 每次随机生成 +
+
+
+ 本地私钥位置 + {{ sshKeyPath }} +
+
+ 本地公钥位置 + {{ sshKeyPublicPath }} +
+
+ 远程登录目标 + {{ sshKeyCommandUsername }}@{{ sshKeyCommandHost }} +
+
生成命令 @@ -700,8 +924,8 @@ const {
{{ sshPublicKeyCommands[sshKeyPlatform] }} - Linux 服务器默认位置:~/.ssh/authorized_keys;Windows - OpenSSH 服务器请按照系统说明配置授权文件。 + 本地公钥文件是上面显示的随机路径;安装后会追加到远程用户的 + ~/.ssh/authorized_keys。每台主机、每次新建配置都会生成新的文件名。

@@ -709,67 +933,69 @@ const { .pub 公钥内容追加到授权文件,最后在下方选择私钥文件即可。

- - - - +

+ 保存后私钥和口令只进入本机加密敏感信息存储,后续接口不会返回明文。 +

+

{{ sshKeyFormError }}

+ diff --git a/frontend/src/views/Login/Login.js b/frontend/src/views/Login/Login.js index bb9ce01..b8e6c15 100644 --- a/frontend/src/views/Login/Login.js +++ b/frontend/src/views/Login/Login.js @@ -24,7 +24,7 @@ export function useLogin() { if (stage.value === "complete") { return `${roleLabels[accountRole.value] || "用户"}登录成功`; } - return "管理员登录"; + return "用户登录"; }); const stageMessage = computed(() => { if (stage.value === "totp") return "该账户还需完成两步验证。"; diff --git a/frontend/src/views/Login/Login.vue b/frontend/src/views/Login/Login.vue index 67bb511..4026c11 100644 --- a/frontend/src/views/Login/Login.vue +++ b/frontend/src/views/Login/Login.vue @@ -20,7 +20,7 @@ const { - + \ No newline at end of file diff --git a/frontend/src/views/SetupWizard/SetupWizard.css b/frontend/src/views/SetupWizard/SetupWizard.css index b74fcd2..8b20875 100644 --- a/frontend/src/views/SetupWizard/SetupWizard.css +++ b/frontend/src/views/SetupWizard/SetupWizard.css @@ -124,25 +124,31 @@ background: #d5deeb; } +/* 中间步骤内容独立滚动,避免高级配置展开后被外层卡片裁切。 */ .setup-form { min-width: 0; min-height: 0; display: grid; grid-template-rows: minmax(0, 1fr) auto; gap: 10px; + overflow: hidden; } .setup-step-grid { min-width: 0; min-height: 0; display: block; + overflow-x: hidden; + overflow-y: auto; + scrollbar-gutter: stable; } .setup-step-card { width: 100%; - height: 100%; + height: auto; min-width: 0; - min-height: 0; + min-height: 100%; + box-sizing: border-box; overflow: visible; } @@ -264,6 +270,20 @@ label > small { display: grid; grid-template-columns: minmax(0, 1fr) minmax(88px, 112px); gap: 6px; + position: relative; +} + +.email-autofill-probe { + position: absolute; + top: 0; + left: 0; + z-index: -1; + width: 1px; + height: 1px; + padding: 0; + border: 0; + opacity: 0; + pointer-events: none; } .email-input-group input, @@ -275,6 +295,11 @@ label > small { white-space: nowrap; } +.email-input-group input.email-autofill-probe { + width: 1px; + height: 1px; +} + .email-primary-grid, .email-delivery-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); @@ -341,6 +366,12 @@ label > small { min-width: 0; } +.compact-row > span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + .compact-row strong, .compact-row small, .confirm-row strong, @@ -379,8 +410,28 @@ label > small { background: #f6f8fc; } +.setup-section-heading { + display: grid; + gap: 3px; + margin: 12px 0 2px; + padding-bottom: 2px; +} + +.setup-section-heading strong { + color: #263c63; + font-size: 11px; +} + +.setup-section-heading span { + color: #53647b; + font-size: 9px; + font-weight: 500; + line-height: 1.35; +} + .provider-description, -.dns-verification-success { +.dns-verification-success, +.dns-verification-report { min-width: 0; display: grid; gap: 4px; @@ -536,11 +587,92 @@ label > small { background: #effbf4; } +.dns-verification-report { + display: grid; + gap: 7px; + margin-top: 9px; + padding: 9px 11px; + border: 1px solid #d7e2f0; + border-radius: 10px; + color: #435571; + background: #f7faff; +} + +.dns-report-heading { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 10px; +} + +.dns-report-heading strong { + color: #2d4775; + font-size: 11px; +} + +.dns-report-heading span { + min-width: 0; + overflow: hidden; + color: #53647b; + font-size: 9px; + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dns-verification-stage { + display: grid; + grid-template-columns: 72px auto minmax(0, 1fr); + align-items: center; + gap: 7px; + padding: 6px 7px; + border-radius: 7px; + background: #eef4fb; + font-size: 9px; +} + +.dns-verification-stage .dns-stage-name { + color: #34445f; + font-weight: 800; +} + +.dns-verification-stage strong { + color: #28734c; + font-size: 9px; + white-space: nowrap; +} + +.dns-verification-stage small { + min-width: 0; + overflow: hidden; + color: #53647b; + font-size: 9px; + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dns-verification-stage.is-warning { + background: #fff8e8; +} + +.dns-verification-stage.is-warning strong { + color: #996d16; +} + +.dns-verification-stage.is-failed { + background: #fff1f1; +} + +.dns-verification-stage.is-failed strong { + color: #a33d3d; +} + .target-switch { width: fit-content; display: inline-flex; gap: 4px; - margin-top: 8px; + margin-top: 0; padding: 4px; border: 1px solid #e1e8f3; border-radius: 11px; @@ -564,6 +696,18 @@ label > small { box-shadow: 0 3px 10px rgba(36, 64, 107, 0.1); } +.access-target-field { + min-width: 0; + display: grid; + gap: 5px; + align-content: start; + margin-top: 8px; + color: #34445f; + font-size: 10px; + font-weight: 800; + line-height: 1.25; +} + footer { min-width: 0; display: grid; @@ -851,6 +995,14 @@ button:disabled { display: none; } + .dns-verification-stage { + grid-template-columns: 64px auto; + } + + .dns-verification-stage small { + grid-column: 1 / -1; + } + .dns-test-actions { margin-top: 5px; } @@ -991,7 +1143,8 @@ button:disabled { .notification-bottom-row .compact-row { min-height: 34px; margin-top: 0; - padding: 6px 8px; + padding: 6px 5px; + column-gap: 3px; } @media (max-width: 900px) and (min-width: 641px) { @@ -1024,4 +1177,231 @@ button:disabled { .notification-bottom-row .email-option-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } -} \ No newline at end of file +} +/* 第二步默认只展示基础配置,高级参数按需展开。 */ +.notification-guide { + display: flex; + align-items: center; + gap: 8px 12px; + min-width: 0; + padding: 9px 11px; + border: 1px solid #dce8f8; + border-radius: 10px; + color: #526783; + background: linear-gradient(135deg, #f7faff, #f2f7ff); + font-size: 10px; + line-height: 1.4; +} + +.notification-guide strong { + flex: 0 0 auto; + color: #285398; + font-size: 11px; +} + +.notification-guide span { + min-width: 0; +} + +.notification-service-row { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.smtp-basic-panel { + background: linear-gradient(135deg, #fbfdff, #f6faff); +} + +.smtp-config-row { + grid-template-columns: minmax(180px, 1.35fr) minmax(100px, 0.55fr) minmax(160px, 1fr) minmax(180px, 1.2fr); +} + +.smtp-options-row { + grid-template-columns: minmax(180px, 0.7fr) minmax(260px, 1.3fr); + align-items: stretch; +} + +.smtp-plaintext-row { + min-height: 34px; + margin-top: 7px !important; + padding: 7px 9px; + border: 1px dashed #e2c98b; + border-radius: 9px; + background: #fffaf0; +} + +.notification-smtp-tip { + margin-top: 8px; + padding: 7px 9px; + border-radius: 8px; + color: #6b7180; + background: #f5f7fa; + font-size: 9px; + line-height: 1.45; +} + +.notification-basic-panel { + min-width: 0; + padding: 12px; + border: 1px solid #e0e8f3; + border-radius: 12px; + background: #fcfdff; +} + +.notification-section-heading { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 10px; + min-width: 0; + margin-bottom: 3px; +} + +.notification-section-heading > div { + display: grid; + gap: 3px; + min-width: 0; +} + +.notification-section-heading strong { + color: #243653; + font-size: 11px; +} + +.notification-section-heading span { + color: #687891; + font-size: 9px; + font-weight: 500; + line-height: 1.4; +} + +.notification-recommended-badge { + flex: 0 0 auto; + padding: 4px 7px; + border-radius: 999px; + color: #2e6a50; + background: #e8f6ed; + font-size: 9px; + font-weight: 800; + white-space: nowrap; +} + +.notification-basic-row { + grid-template-columns: minmax(0, 1.35fr) minmax(0, 0.65fr); +} + +.notification-basic-panel .notification-sender-row { + grid-template-columns: minmax(0, 0.8fr) minmax(0, 1fr) minmax(0, 1.35fr); +} + +.notification-basic-panel label { + margin-top: 7px; +} + +.notification-advanced-panel { + min-width: 0; + border: 1px solid #e2e8f2; + border-radius: 12px; + background: #f9fbfe; + overflow: hidden; +} + +.notification-advanced-toggle { + width: 100%; + min-width: 0; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 10px 12px; + border: 0; + border-radius: 0; + color: #34445f; + background: transparent; + text-align: left; +} + +.notification-advanced-toggle:hover { + background: #f1f6fd; +} + +.notification-advanced-toggle > span:first-child { + display: grid; + gap: 3px; + min-width: 0; +} + +.notification-advanced-toggle strong { + color: #34445f; + font-size: 11px; +} + +.notification-advanced-toggle small { + color: #718198; + font-size: 9px; + font-weight: 500; + line-height: 1.35; +} + +.notification-advanced-action { + flex: 0 0 auto; + color: #3565ae; + font-size: 10px; + font-weight: 800; + white-space: nowrap; +} + +.notification-advanced-content { + display: grid; + gap: 8px; + padding: 0 12px 12px; + border-top: 1px solid #e7edf5; +} + +.notification-advanced-tip { + padding: 7px 9px; + border-radius: 8px; + color: #687891; + background: #f1f5fa; + font-size: 9px; + line-height: 1.4; +} + +.notification-advanced-content .notification-row label { + margin-top: 0; +} + +@media (max-width: 900px) and (min-width: 641px) { + .notification-service-row, + .notification-basic-row, + .notification-basic-panel .notification-sender-row { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .notification-basic-panel .notification-sender-row label:last-child { + grid-column: 1 / -1; + } +} + +@media (max-width: 640px) { + .notification-guide { + align-items: flex-start; + flex-direction: column; + gap: 4px; + } + + .notification-service-row, + .notification-basic-row, + .notification-basic-panel .notification-sender-row { + grid-template-columns: minmax(0, 1fr); + } + + .notification-basic-panel .notification-sender-row label:last-child { + grid-column: auto; + } + + .notification-section-heading { + align-items: flex-start; + flex-direction: column; + gap: 5px; + } +} diff --git a/frontend/src/views/SetupWizard/SetupWizard.js b/frontend/src/views/SetupWizard/SetupWizard.js index f2776b8..87379e9 100644 --- a/frontend/src/views/SetupWizard/SetupWizard.js +++ b/frontend/src/views/SetupWizard/SetupWizard.js @@ -34,9 +34,14 @@ export function useSetupWizard(props, emit) { const dnsVerification = ref(null); const verificationClock = ref(Date.now()); const currentStep = ref(1); + const notificationAdvancedVisible = ref(false); const selectedEmailDomain = ref(""); const emailLocalPart = ref(""); + const emailInputElement = ref(null); + const emailAutofillElement = ref(null); + let emailVisibleEdited = false; let verificationTimer; + let emailAutofillTimer; const targetType = ref(props.status.web_public_ip ? "ip" : "hostname"); const form = ref({ admin_username: "", @@ -45,6 +50,13 @@ export function useSetupWizard(props, emit) { confirm_password: "", server_port: props.status.server_port || 8080, email_http_enabled: false, + email_smtp_enabled: false, + email_smtp_host: "", + email_smtp_port: 587, + email_smtp_username: "", + email_smtp_password: "", + email_smtp_mode: "starttls", + email_smtp_allow_plaintext_auth: false, email_provider: "", email_endpoint: "", email_http_path: "/api/email/send", @@ -142,7 +154,47 @@ export function useSetupWizard(props, emit) { }).format(new Date(value)); } + function formatVerificationStageStatus(status) { + switch (status) { + case "completed": + return "已完成"; + case "warning": + return "警告"; + case "failed": + return "失败"; + default: + return "处理中"; + } + } + + function findCommonEmailDomain(domain) { + const normalizedDomain = String(domain || "").trim().toLowerCase(); + return commonEmailDomains.find( + (option) => + option.value && + option.value !== "custom" && + option.value === normalizedDomain, + ); + } + + function getEmailLocalPart(value) { + const text = String(value || "").trim(); + const atIndex = text.indexOf("@"); + return (atIndex >= 0 ? text.slice(0, atIndex) : text).trim(); + } + + function isCompleteEmail(localPart, domain) { + return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test( + `${localPart}@${domain}`, + ); + } + function updateEmailAutofillValue(value) { + if (!emailAutofillElement.value) return; + emailAutofillElement.value.value = String(value || ""); + } + function handleEmailInput(value) { + emailVisibleEdited = true; error.value = ""; const rawValue = String(value || "").trim(); @@ -150,6 +202,7 @@ export function useSetupWizard(props, emit) { emailLocalPart.value = ""; selectedEmailDomain.value = ""; form.value.admin_email = ""; + updateEmailAutofillValue(""); return; } @@ -159,6 +212,7 @@ export function useSetupWizard(props, emit) { form.value.admin_email = selectedEmailDomain.value && selectedEmailDomain.value !== "custom" ? `${rawValue}@${selectedEmailDomain.value}` : rawValue; + updateEmailAutofillValue(form.value.admin_email); return; } @@ -167,16 +221,87 @@ export function useSetupWizard(props, emit) { if (!localPart || !domain) { emailLocalPart.value = rawValue; - selectedEmailDomain.value = ""; + selectedEmailDomain.value = domain ? "custom" : ""; form.value.admin_email = rawValue; + updateEmailAutofillValue(form.value.admin_email); return; } - emailLocalPart.value = localPart; - selectedEmailDomain.value = commonEmailDomains.some( - (option) => option.value === domain && option.value !== "custom", - ) ? domain : "custom"; - form.value.admin_email = `${localPart}@${domain}`; + const commonDomain = findCommonEmailDomain(domain); + if (commonDomain) { + emailLocalPart.value = localPart; + selectedEmailDomain.value = commonDomain.value; + form.value.admin_email = `${localPart}@${commonDomain.value}`; + updateEmailAutofillValue(form.value.admin_email); + return; + } + + emailLocalPart.value = rawValue; + selectedEmailDomain.value = ""; + form.value.admin_email = rawValue; + updateEmailAutofillValue(form.value.admin_email); + } + + function synchronizeEmailField(value) { + const visibleValue = emailInputElement.value?.value?.trim() || ""; + const autofillValue = emailAutofillElement.value?.value?.trim() || ""; + const inputValue = + value !== undefined + ? value + : visibleValue.includes("@") + ? visibleValue + : emailVisibleEdited + ? visibleValue + : autofillValue.includes("@") + ? autofillValue + : visibleValue; + const rawValue = String(inputValue || "").trim(); + + if (!rawValue) return; + + if (rawValue.includes("@") || rawValue !== emailLocalPart.value) { + handleEmailInput(rawValue); + return; + } + + if ( + selectedEmailDomain.value && + selectedEmailDomain.value !== "custom" + ) { + form.value.admin_email = `${rawValue}@${selectedEmailDomain.value}`; + updateEmailAutofillValue(form.value.admin_email); + } + } + function handleEmailAutofill() { + synchronizeEmailField(); + } + + function handleEmailPaste(event) { + const pastedValue = event.clipboardData?.getData("text") || ""; + if (!pastedValue.includes("@")) return; + + event.preventDefault(); + handleEmailInput(pastedValue); + handleEmailBlur(); + } + + function handleEmailBlur(value) { + synchronizeEmailField(value); + const rawValue = String(emailLocalPart.value || "").trim(); + const atIndex = rawValue.indexOf("@"); + if (atIndex < 0) { + handleEmailInput(rawValue); + return; + } + + const localPart = rawValue.slice(0, atIndex).trim(); + const domain = rawValue.slice(atIndex + 1).trim().toLowerCase(); + if (localPart && isCompleteEmail(localPart, domain)) { + emailLocalPart.value = localPart; + selectedEmailDomain.value = findCommonEmailDomain(domain)?.value || "custom"; + form.value.admin_email = `${localPart}@${domain}`; + updateEmailAutofillValue(form.value.admin_email); + } } function applyEmailDomain(domain) { @@ -184,7 +309,8 @@ export function useSetupWizard(props, emit) { if (!domain || domain === "custom") return; const currentEmail = form.value.admin_email.trim(); - const localPart = emailLocalPart.value.trim() || currentEmail.split("@")[0].trim(); + const localPart = + getEmailLocalPart(emailLocalPart.value) || getEmailLocalPart(currentEmail); if (!localPart) { selectedEmailDomain.value = ""; error.value = "请先输入邮箱名称,再选择常用邮箱。"; @@ -193,7 +319,13 @@ export function useSetupWizard(props, emit) { emailLocalPart.value = localPart; form.value.admin_email = `${localPart}@${domain}`; + updateEmailAutofillValue(form.value.admin_email); } + + function toggleNotificationAdvanced() { + notificationAdvancedVisible.value = !notificationAdvancedVisible.value; + } + async function loadDNSProviders() { dnsCatalogLoading.value = true; dnsCatalogError.value = ""; @@ -294,6 +426,9 @@ export function useSetupWizard(props, emit) { }), }); const result = await response.json().catch(() => ({})); + if (result.test_report) { + dnsVerification.value = { test_report: result.test_report }; + } if (!response.ok) throw new Error(result.error || "DNS API 在线验证失败"); dnsVerification.value = result; } catch (err) { @@ -304,6 +439,7 @@ export function useSetupWizard(props, emit) { } function validateCurrentStep() { + if (currentStep.value === 1) synchronizeEmailField(); error.value = ""; resultMessage.value = ""; @@ -320,22 +456,60 @@ export function useSetupWizard(props, emit) { error.value = "请输入合法的超级管理员绑定邮箱。"; return false; } - if (form.value.admin_password.length < 8) { - error.value = "超级管理员密码至少需要 8 个字符。"; + if ( + form.value.admin_password.length < 8 || + form.value.admin_password.length > 12 + ) { + error.value = "超级管理员密码长度必须为 8 至 12 个字符。"; return false; } if (form.value.admin_password !== form.value.confirm_password) { error.value = "两次输入的超级管理员密码不一致。"; return false; } - } - - if (currentStep.value === 2) { const port = Number(form.value.server_port); if (!Number.isInteger(port) || port < 1 || port > 65535) { error.value = "请输入 1 至 65535 之间的主服务端口。"; return false; } + const hostname = + targetType.value === "hostname" ? form.value.web_hostname.trim() : ""; + const publicIP = + targetType.value === "ip" ? form.value.web_public_ip.trim() : ""; + if (!hostname && !publicIP) { + error.value = `请填写${targetLabel.value}。`; + return false; + } + } + + if (currentStep.value === 2) { + if (form.value.email_smtp_enabled) { + if (!form.value.email_smtp_host.trim()) { + error.value = "启用 SMTP 通知后必须填写 SMTP 主机。"; + return false; + } + const smtpPort = Number(form.value.email_smtp_port); + if (!Number.isInteger(smtpPort) || smtpPort < 1 || smtpPort > 65535) { + error.value = "SMTP 端口必须在 1 至 65535 之间。"; + return false; + } + if (!form.value.email_smtp_username.trim()) { + error.value = "启用 SMTP 通知后必须填写 SMTP 用户名。"; + return false; + } + if (!form.value.email_smtp_password) { + error.value = "启用 SMTP 通知后必须填写 SMTP 密码。"; + return false; + } + if (!["plain", "starttls", "implicit_tls"].includes(form.value.email_smtp_mode)) { + error.value = "SMTP 连接模式无效。"; + return false; + } + if (form.value.email_smtp_mode === "plain" && !form.value.email_smtp_allow_plaintext_auth) { + error.value = "SMTP 明文模式必须明确允许明文认证,建议改用 STARTTLS 或隐式 TLS。"; + return false; + } + } if (form.value.email_http_enabled && !form.value.email_endpoint.trim()) { error.value = "启用 HTTP 邮件通知后必须填写 API 地址。"; return false; @@ -424,14 +598,6 @@ export function useSetupWizard(props, emit) { } if (currentStep.value === 4) { - const hostname = - targetType.value === "hostname" ? form.value.web_hostname.trim() : ""; - const publicIP = - targetType.value === "ip" ? form.value.web_public_ip.trim() : ""; - if (!hostname && !publicIP) { - error.value = `请填写${targetLabel.value}。`; - return false; - } if (!form.value.certificate_root.trim()) { error.value = "请填写证书部署根目录。"; return false; @@ -482,8 +648,11 @@ export function useSetupWizard(props, emit) { async function submit() { error.value = ""; resultMessage.value = ""; - if (form.value.admin_password.length < 8) { - error.value = "超级管理员密码至少需要 8 个字符。"; + if ( + form.value.admin_password.length < 8 || + form.value.admin_password.length > 12 + ) { + error.value = "超级管理员密码长度必须为 8 至 12 个字符。"; return; } if (form.value.admin_password !== form.value.confirm_password) { @@ -494,6 +663,29 @@ export function useSetupWizard(props, emit) { error.value = "必须先完成 DNS API 在线验证;验证结果已过期时请重新测试。"; return; } + if (form.value.email_smtp_enabled) { + const smtpPort = Number(form.value.email_smtp_port); + if (!form.value.email_smtp_host.trim()) { + error.value = "启用 SMTP 通知后必须填写 SMTP 主机。"; + return; + } + if (!Number.isInteger(smtpPort) || smtpPort < 1 || smtpPort > 65535) { + error.value = "SMTP 端口必须在 1 至 65535 之间。"; + return; + } + if (!form.value.email_smtp_username.trim()) { + error.value = "启用 SMTP 通知后必须填写 SMTP 用户名。"; + return; + } + if (!form.value.email_smtp_password) { + error.value = "启用 SMTP 通知后必须填写 SMTP 密码。"; + return; + } + if (form.value.email_smtp_mode === "plain" && !form.value.email_smtp_allow_plaintext_auth) { + error.value = "SMTP 明文模式必须明确允许明文认证,建议改用 STARTTLS 或隐式 TLS。"; + return; + } + } try { emailCredentialPayload(); } catch (err) { @@ -520,14 +712,21 @@ export function useSetupWizard(props, emit) { admin_password: form.value.admin_password, server_port: Number(form.value.server_port), email_http_enabled: form.value.email_http_enabled, + email_smtp_enabled: form.value.email_smtp_enabled, + email_smtp_host: form.value.email_smtp_host, + email_smtp_port: Number(form.value.email_smtp_port), + email_smtp_username: form.value.email_smtp_username, + email_smtp_password: form.value.email_smtp_password, + email_smtp_mode: form.value.email_smtp_mode, + email_smtp_allow_plaintext_auth: form.value.email_smtp_allow_plaintext_auth, email_provider: form.value.email_provider, 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_credentials: emailCredentialPayload(), - 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, @@ -581,6 +780,9 @@ export function useSetupWizard(props, emit) { onMounted(() => { loadDNSProviders(); + emailAutofillTimer = window.setInterval(() => { + if (currentStep.value === 1) synchronizeEmailField(); + }, 250); verificationTimer = window.setInterval(() => { verificationClock.value = Date.now(); }, 30000); @@ -588,6 +790,7 @@ export function useSetupWizard(props, emit) { onUnmounted(() => { if (verificationTimer) window.clearInterval(verificationTimer); + if (emailAutofillTimer) window.clearInterval(emailAutofillTimer); }); return { @@ -608,11 +811,15 @@ export function useSetupWizard(props, emit) { dnsTestDomain, dnsVerification, currentStep, + notificationAdvancedVisible, targetType, form, commonEmailDomains, selectedEmailDomain, emailLocalPart, + emailInputElement, + emailAutofillElement, + handleEmailAutofill, targetLabel, emailCredentialLabel, emailCredentialPlaceholder, @@ -620,8 +827,13 @@ export function useSetupWizard(props, emit) { selectedDNSProvider, dnsVerificationValid, formatVerificationExpiry, + formatVerificationStageStatus, applyEmailDomain, + toggleNotificationAdvanced, handleEmailInput, + synchronizeEmailField, + handleEmailPaste, + handleEmailBlur, testDNS, handleSubmit, previousStep, diff --git a/frontend/src/views/SetupWizard/SetupWizard.vue b/frontend/src/views/SetupWizard/SetupWizard.vue index b15ac73..c942ed0 100644 --- a/frontend/src/views/SetupWizard/SetupWizard.vue +++ b/frontend/src/views/SetupWizard/SetupWizard.vue @@ -24,21 +24,32 @@ const { dnsCredentials, dnsCredentialsVisible, maskCredential, + emailCredentials, + emailCredentialsVisible, dnsTestDomain, dnsVerification, currentStep, + notificationAdvancedVisible, targetType, form, commonEmailDomains, selectedEmailDomain, emailLocalPart, + emailInputElement, targetLabel, resetURLPreview, + emailCredentialLabel, + emailCredentialPlaceholder, selectedDNSProvider, dnsVerificationValid, formatVerificationExpiry, + formatVerificationStageStatus, applyEmailDomain, + toggleNotificationAdvanced, handleEmailInput, + synchronizeEmailField, + handleEmailPaste, + handleEmailBlur, testDNS, handleSubmit, previousStep, @@ -82,7 +93,7 @@ const { 2服务通知端口与邮件2服务通知邮件通知 绑定邮箱 +
+ 密码重置地址预览 + {{ resetURLPreview }} + 只有手动启动 Scert-admin 后,此地址才会临时可用。 +
02服务与通知
+
+ 先完成基础配置 + 填写邮件服务地址即可继续,其他项目已经提供合理默认值。 +
+
- -
-
- - - -
- -
- - -
- 当前接口不启用认证,不需要填写凭据。 +
+
+
+ SMTP 通知配置 + Scert 只作为 SMTP 出站客户端,不提供 SMTP、IMAP 或 POP3 服务端。 +
+ 推荐 STARTTLS
-
-
-
- {{ emailCredentialLabel }} -
-
+
+
+
+ 邮件通知基础配置 + 填写服务地址、发件人和收件人即可,技术参数无需修改。 +
+ 推荐配置 +
+ +
+ + +
+ +
+ + + +
+
+ +
密码重置地址 {{ resetURLPreview }} - - 无需配置独立端口;只有手动启动 Scert-admin - 后,此地址才会临时可用。 - + 只有手动启动 Scert-admin 后,此地址才会临时可用。
-
- - - -
+
+ -
- - - - -
+
+
+ 默认值适用于常见 HTTP 邮件服务。只有服务方提供了特殊要求时,才需要修改这里的内容。 +
-
- -
@@ -582,7 +787,11 @@ const { " @click="testDNS" > - {{ dnsTesting ? "正在创建并清理测试记录……" : "测试 DNS API" }} + {{ + dnsTesting + ? "正在创建、查询并清理测试记录……" + : "测试 DNS API" + }} 测试会临时创建 DNS-01 TXT @@ -599,55 +808,45 @@ const { }}。修改服务商、测试域名或凭据后需要重新测试。
+ +
+
+ 在线测试过程 + + 临时记录:{{ dnsVerification.test_report.record_name }} + +
+
+ {{ stage.name }} + {{ formatVerificationStageStatus(stage.status) }} + {{ stage.message }} +
+
- 04管理页面与证书目录 -
- -
+ 04证书目录与剩余设置
- - - - + +
- + /> + + 初始化完成后开启管理页面 + 桌面端可通过此开关决定是否启用浏览器管理页面。 + +
diff --git a/frontend/src/views/SuperAdminReset/SuperAdminReset.js b/frontend/src/views/SuperAdminReset/SuperAdminReset.js index 2a33388..3bbb0a4 100644 --- a/frontend/src/views/SuperAdminReset/SuperAdminReset.js +++ b/frontend/src/views/SuperAdminReset/SuperAdminReset.js @@ -52,8 +52,8 @@ export function useSuperAdminReset() { if (!verificationCode.value.trim()) { return "请输入一次性校验码。"; } - if (password.value.length < 8) { - return "新密码至少需要 8 个字符。"; + if (password.value.length < 8 || password.value.length > 12) { + return "新密码长度必须为 8 至 12 个字符。"; } if (password.value !== confirmPassword.value) { return "两次输入的新密码不一致。"; @@ -138,4 +138,4 @@ export function useSuperAdminReset() { submit, loadSession, }; -} \ No newline at end of file +} diff --git a/frontend/src/views/SuperAdminReset/SuperAdminReset.vue b/frontend/src/views/SuperAdminReset/SuperAdminReset.vue index cd4f18c..990e0ca 100644 --- a/frontend/src/views/SuperAdminReset/SuperAdminReset.vue +++ b/frontend/src/views/SuperAdminReset/SuperAdminReset.vue @@ -60,8 +60,9 @@ const { v-model="password" type="password" autocomplete="new-password" - placeholder="至少 8 个字符" + placeholder="8-12 个字符" minlength="8" + maxlength="12" :disabled="loading || submitting || success" required /> @@ -77,6 +78,7 @@ const { autocomplete="new-password" placeholder="请再次输入新密码" minlength="8" + maxlength="12" :disabled="loading || submitting || success" required /> @@ -111,4 +113,4 @@ const { - \ No newline at end of file + diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 92e788a..5549d18 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -4,26 +4,34 @@ import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], publicDir: 'logo', - server: { - host: process.env.SCERT_DEV_HOST || '127.0.0.1', - port: Number(process.env.SCERT_DEV_PORT || 5173), - proxy: { - '/api': process.env.SCERT_API_TARGET || 'http://127.0.0.1:5200', - '/healthz': process.env.SCERT_API_TARGET || 'http://127.0.0.1:5200', - '/reset': { - target: process.env.SCERT_API_TARGET || 'http://127.0.0.1:5200', - changeOrigin: false, - bypass(request) { - if ( - request.method === 'GET' && - request.headers.accept && - request.headers.accept.includes('text/html') - ) { - return '/index.html'; - } - return undefined; + server: (() => { + const apiTarget = process.env.SCERT_API_TARGET || 'http://127.0.0.1:5200'; + const apiProxy = { + target: apiTarget, + changeOrigin: false, + secure: false, + }; + + return { + host: process.env.SCERT_DEV_HOST || '127.0.0.1', + port: Number(process.env.SCERT_DEV_PORT || 5173), + proxy: { + '/api': apiProxy, + '/healthz': apiProxy, + '/reset': { + ...apiProxy, + bypass(request) { + if ( + request.method === 'GET' && + request.headers.accept && + request.headers.accept.includes('text/html') + ) { + return '/index.html'; + } + return undefined; + }, }, }, - }, - }, + }; + })(), })