diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 14f9df41..126a6b3f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -41,6 +41,7 @@ jobs: - name: Gen output name run: | echo "FILENAME=smail_${{ matrix.goos }}_${{ matrix.goarch }}" >> ${GITHUB_ENV} + echo "ADMINFILENAME=smail-admin_${{ matrix.goos }}_${{ matrix.goarch }}" >> ${GITHUB_ENV} echo "WCFILENAME=wechat_push_${{ matrix.goos }}_${{ matrix.goarch }}" >> ${GITHUB_ENV} echo "SPAMBLOCKFILENAME=spam_block_${{ matrix.goos }}_${{ matrix.goarch }}" >> ${GITHUB_ENV} echo "ZIPNAME=${{ matrix.goos }}_${{ matrix.goarch }}" >> ${GITHUB_ENV} @@ -48,16 +49,29 @@ jobs: if: matrix.goos == 'windows' run: | echo "FILENAME=smail_${{ matrix.goos }}_${{ matrix.goarch }}.exe" >> ${GITHUB_ENV} + echo "ADMINFILENAME=smail-admin_${{ matrix.goos }}_${{ matrix.goarch }}.exe" >> ${GITHUB_ENV} echo "WCFILENAME=wechat_push_${{ matrix.goos }}_${{ matrix.goarch }}.exe" >> ${GITHUB_ENV} echo "SPAMBLOCKFILENAME=spam_block_${{ matrix.goos }}_${{ matrix.goarch }}.exe" >> ${GITHUB_ENV} - name: FE Build run: cd fe && yarn install --frozen-lockfile && yarn build - name: BE Build run: | - cd server && cp -rf ../fe/dist listen/http_server - go build -ldflags "-s -w -X 'main.version=${{ env.VERSION }}' -X 'main.goVersion=$(go version)' -X 'main.gitHash=$(git show -s --format=%H)' -X 'main.buildTime=$(TZ=UTC-8 date +%Y-%m-%d" "%H:%M:%S)'" -o ${{ env.FILENAME }} main.go + cd server + cp -rf ../fe/dist listen/http_server + BUILD_FLAGS="-s -w -X 'git.pcux.cn/xuans/Smail/internal/buildinfo.Version=${{ env.VERSION }}' -X 'git.pcux.cn/xuans/Smail/internal/buildinfo.GoVersion=$(go version)' -X 'git.pcux.cn/xuans/Smail/internal/buildinfo.GitHash=$(git show -s --format=%H)' -X 'git.pcux.cn/xuans/Smail/internal/buildinfo.BuildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)'" + go build -ldflags "$BUILD_FLAGS" -o ${{ env.FILENAME }} . + go build -ldflags "$BUILD_FLAGS" -o ${{ env.ADMINFILENAME }} ./cmd/smail-admin go build -ldflags "-s -w" -o ${{ env.WCFILENAME }} hooks/wechat_push/wechat_push.go go build -ldflags "-s -w" -o ${{ env.SPAMBLOCKFILENAME }} hooks/spam_block/spam_block.go + cat > release.json < output/release.json test: - export setup_port=17888 && cd server && export SMAIL_ROOT=$(CURDIR)/server/ && go test -v -p 1 ./... + @trap 'cd "$(CURDIR)/server" && git clean -f -x -- .codex-smail-*' EXIT; export setup_port=17888 && cd server && export SMAIL_ROOT=$(CURDIR)/server/ && go test -v -p 1 ./... test_mysql: - export setup_port=17888 && cd server && export SMAIL_ROOT=$(CURDIR)/server/ && go test -args "mysql" -v -p 1 ./... + @trap 'cd "$(CURDIR)/server" && git clean -f -x -- .codex-smail-*' EXIT; export setup_port=17888 && cd server && export SMAIL_ROOT=$(CURDIR)/server/ && go test -args "mysql" -v -p 1 ./... test_postgres: - export setup_port=17888 && cd server && export SMAIL_ROOT=$(CURDIR)/server/ && go test -args "postgres" -v -p 1 ./... \ No newline at end of file + @trap 'cd "$(CURDIR)/server" && git clean -f -x -- .codex-smail-*' EXIT; export setup_port=17888 && cd server && export SMAIL_ROOT=$(CURDIR)/server/ && go test -args "postgres" -v -p 1 ./... diff --git a/docs/超级管理员重置与邮箱验证码实施任务清单.md b/docs/超级管理员重置与邮箱验证码实施任务清单.md index 4d1f8a90..4c8c2210 100644 --- a/docs/超级管理员重置与邮箱验证码实施任务清单.md +++ b/docs/超级管理员重置与邮箱验证码实施任务清单.md @@ -186,7 +186,7 @@ ### AD-005 建立需求追踪和测试矩阵 -- **状态**:未开始 +- **状态**:`[x] 已完成,等待复审` - **优先级**:P0 - **依赖**:AD-001、AD-002、AD-003 - **需求映射**:第 21、22、24 章 @@ -196,7 +196,7 @@ - **测试要求**:检查每条验收项和 17 条阻塞条件至少映射一个测试或人工审计步骤。 - **验收标准**:测试矩阵完整、可追踪、无孤立需求和无来源测试。 - **回退方式**:缺少覆盖的能力保持关闭。 -- **验收证据**:待补充。 +- **验收证据**:已新增 `docs/超级管理员重置与邮箱验证码测试矩阵.md`,把 AD-001~AD-066 映射到单元、并发、协议、数据库、浏览器、安装升级和跨平台检查;明确 SQLite 自动化结果以及 MySQL、PostgreSQL、Ubuntu 22.04/24.04、Windows 生产服务、真实 SMTP 和真实浏览器的未验证边界。关键负向场景覆盖 nonce 重放、密码参数、验证码降级、并发双花、超级管理员 Web 恢复和敏感数据泄露;发布前仍需补齐真实环境证据。 ### 第一阶段验收 diff --git a/docs/超级管理员重置与邮箱验证码测试矩阵.md b/docs/超级管理员重置与邮箱验证码测试矩阵.md new file mode 100644 index 00000000..766c1632 --- /dev/null +++ b/docs/超级管理员重置与邮箱验证码测试矩阵.md @@ -0,0 +1,77 @@ +# 超级管理员重置与邮箱验证码测试矩阵 + +> 文档编号:AD-005 +> +> 编写日期:2026-08-27 +> +> 适用范围:`smail-admin` 本机超级管理员重置、普通用户和管理员密码恢复、登录二次验证、外部安全邮箱验证码、离线恢复码、WebAuthn、审计和限流。 +> +> 本矩阵区分“本机自动化通过”和“真实环境待验证”。没有真实 Ubuntu、Windows 服务、SMTP Relay、MySQL 或 PostgreSQL 证据时,不把对应项目标记为最终验收通过。 + +## 1. 状态定义 + +| 标记 | 含义 | +|---|---| +| 自动化通过 | 当前 Windows 开发环境可以重复执行并通过 | +| 待真实环境 | 需要真实平台、服务、网络或外部依赖,不能用单元测试替代 | +| 阻塞 | 关键安全边界尚未得到完整证据,发布前必须关闭 | + +## 2. 需求到测试映射 + +| 需求范围 | 测试或审计入口 | 当前结果 | 仍需补充 | +|---|---|---|---| +| AD-001~AD-004 | `server/cmd/smail-admin/main_test.go`、`services/adminreset/*_test.go`、安全威胁模型 | 自动化通过 | Ubuntu、Windows 交互实机审计 | +| AD-005 | 本文件、配置系统测试基线、CI 安全工作流 | 自动化通过 | 将本矩阵接入发布检查 | +| AD-006~AD-008 | 管理程序命令、危险参数、受信进程和密码代理测试 | 自动化通过 | 真实 systemd 和 Windows 令牌 | +| AD-009、AD-010 | `deploy/systemd/*`、安装脚本和平台适配测试 | 部分通过 | Ubuntu 22.04/24.04、Windows Service 和 ACL | +| AD-011、AD-015 | 版本、原子升级、配置权限和文件权限测试 | 部分通过 | 两个 Ubuntu 版本和 Windows 安装升级 | +| AD-012~AD-021 | `services/adminreset` 协议、Unix Socket、Named Pipe 和重置事务测试 | 自动化通过 | 跨平台实机 IPC 抢占、权限篡改和端口扫描 | +| AD-022~AD-031 | `services/recovery`、`credentials`、`webauthn` 和安全凭据测试 | 自动化通过 | 真实浏览器 WebAuthn 和故障注入 | +| AD-032~AD-038 | `services/verification`、外部邮箱和投递测试 | 自动化通过 | 真实 SMTP Relay、退信和证书校验 | +| AD-039~AD-047 | 登录二次验证、恢复状态机、重发和失效测试 | 自动化通过 | 真实浏览器端到端和多实例 | +| AD-048~AD-052 | Controller、CSRF、V1 API、Session 和统一认证测试 | 自动化通过 | 浏览器网络面板与生产代理行为 | +| AD-053~AD-059 | 外部邮箱生命周期、管理权限和恢复码提示测试 | 部分通过 | 前端页面真实操作和首次登录场景 | +| AD-060 | `go test ./... -race` 及安全回归 | 自动化通过 | 持续集成环境重复执行 | +| AD-061 | 三数据库迁移和集成测试 | SQLite 自动化通过 | 配置 MySQL/PostgreSQL DSN 后真实执行 | +| AD-062 | Unix Socket、systemd 安装和 Linux 安全测试 | 未验证 | Ubuntu 22.04 与 24.04 实机 | +| AD-063 | Named Pipe、Windows Service、ACL 和令牌测试 | 部分通过 | Windows 提权/非提权/服务账户实机 | +| AD-064 | 浏览器视口、恢复页面、登录二次验证和敏感信息检查 | 未完成 | 1440×900、低高度、移动视口和主流 Chromium | +| AD-065~AD-066 | 负向测试、泄露扫描、发布评审 | 未完成 | 依赖 AD-061~AD-064 的真实环境证据 | + +## 3. 必须覆盖的安全负向矩阵 + +| 场景 | 预期结果 | 自动化入口 | +|---|---|---| +| 普通用户调用超级管理员重置 | 拒绝,不建立网络重置路径 | `services/adminreset` 授权测试 | +| HTTP 或 localhost TCP 触发超级管理员重置 | 不存在或拒绝 | HTTP 路由安全测试、部署审计 | +| 重放已消费 nonce | 拒绝 | `protocol_test.go`、传输测试 | +| 过期 nonce 或超时会话 | 拒绝 | SessionGuard 测试 | +| `--password`、密码环境变量或密码文件 | 拒绝 | 管理程序参数和密码代理测试 | +| 普通标准输入重定向 | 拒绝,不降级读取 | 密码代理平台测试 | +| 外部邮箱验证码关闭 | 不显示或不允许降级恢复 | 恢复 Controller 测试 | +| 错误验证码重复尝试 | 计数并限流 | verification service/store 测试 | +| 并发消费同一验证码或恢复码 | 只允许一次成功 | 并发测试和数据库事务测试 | +| 验证码跨账号、用途、资源或浏览器上下文复用 | 拒绝 | verification 绑定测试 | +| 超级管理员通过普通 Web 忘记密码 | 拒绝并引导本机通道 | reset entry 测试 | +| 重置后旧 Session、WebAuthn、恢复码和票据 | 全部失效 | credentials/recovery/webauthn 测试 | +| 审计、日志、响应、备份和浏览器存储出现敏感值 | 不得出现 | 敏感字段和泄露扫描 | + +## 4. 数据库和平台执行记录 + +| 环境 | 命令或检查 | 当前状态 | +|---|---|---| +| Windows 开发环境 | `cd server; go test ./... -count=1` | 通过 | +| Windows 开发环境 | `cd server; go vet ./...` | 通过 | +| Windows 开发环境 | `cd fe; yarn.cmd build` | 通过 | +| SQLite | 迁移、事务、并发和恢复测试 | 通过 | +| MySQL | `SMAIL_TEST_MYSQL_DSN` 集成测试 | 未配置,未验证 | +| PostgreSQL | `SMAIL_TEST_POSTGRES_DSN` 集成测试 | 未配置,未验证 | +| Ubuntu 22.04 | systemd、Unix Socket、安装升级和端口扫描 | 未验证 | +| Ubuntu 24.04 | systemd、Unix Socket、安装升级和端口扫描 | 未验证 | +| Windows 生产服务 | Named Pipe、ACL、令牌和 Service 生命周期 | 未验证 | +| 真实 SMTP Relay | 投递、证书、失败降级和敏感信息检查 | 未验证 | +| 真实浏览器 | 恢复、登录二次验证和移动视口 | 未完成 | + +## 5. 发布判定 + +在 MySQL、PostgreSQL、Ubuntu 22.04、Ubuntu 24.04、Windows 生产服务、真实 SMTP 和真实浏览器证据补齐前,AD-065、AD-066 以及配置系统的最终验收不得标记为复审通过。自动化测试通过只说明当前代码在隔离测试环境下满足已覆盖的行为,不代表跨平台和生产边界已经闭合。 \ No newline at end of file diff --git a/docs/配置系统重构实施任务清单.md b/docs/配置系统重构实施任务清单.md index 573763dc..df4e46c5 100644 --- a/docs/配置系统重构实施任务清单.md +++ b/docs/配置系统重构实施任务清单.md @@ -196,7 +196,7 @@ ### CG-006 实现严格 JSON 解析器 -- **状态**:未开始 +- **状态**:`[x] 已完成,等待复审` - **优先级**:P0 - **依赖**:CG-005 - **设计映射**:第 8.2 章 @@ -206,11 +206,11 @@ - **测试要求**:覆盖嵌套重复键、大小写相近字段、超大数值、多个 JSON 值和畸形输入。 - **验收标准**:全部恶意配置夹具被稳定拒绝,正常配置无兼容性回退。 - **回退方式**:保留旧解析器但不在生产开关中启用新路径。 -- **验收证据**:待补充。 +- **验收证据**:`server/config/parser.go` 已实现配置大小限制、最大嵌套深度、Token 级重复键检测、`DisallowUnknownFields`、BOM 拒绝、无效 UTF-8 拒绝、尾随 JSON 内容拒绝、`UseNumber` 数值解析和精确字段形状校验;超大数值、大小写相近字段、嵌套未知字段、控制字符、畸形输入均使用固定错误,不回显 Secret 或绝对路径。`server/config/parser_test.go`、`server/config/parser_security_test.go` 覆盖重复键、嵌套重复键、未知字段、数值溢出、多个 JSON 值、深度和大小限制,以及错误信息脱敏;`go test ./config -count=1` 已通过。 ### CG-007 实现配置验证器 -- **状态**:未开始 +- **状态**:已完成,等待复审 - **优先级**:P0 - **依赖**:CG-005、CG-006 - **设计映射**:第 8.3、8.4 章 @@ -220,25 +220,25 @@ - **测试要求**:端口冲突、路径逃逸、域名冲突、插件能力越权和状态机条件测试。 - **验收标准**:无效候选配置不能进入磁盘事务或运行时快照。 - **回退方式**:关闭新配置更新入口,不绕过验证器保存。 -- **验收证据**:待补充。 +- **验收证据**:`server/config/validator.go` 已实现日志级别、HTTP/HTTPS 端口、SMTP Relay 主机/端口/发件域/加密模式、邮箱端口和登录验证策略、SSL 受控相对路径及证书私钥成对引用、插件逻辑 ID/文件名/网络白名单/凭据格式校验;远程 SMTP 明文 Relay、路径逃逸、绝对路径、非法域名、重复插件网络目标和不安全插件网络目标均被拒绝。`server/config/runtime_validator.go` 已实现分区元数据、代次、域名唯一性、端口冲突、插件能力与网络目标、ready 状态和生产降级状态校验。`server/config/validator_security_test.go` 覆盖非法日志级别、HTTP/HTTPS 端口、ready 缺少 Web 域名、域名重复、SMTP 非法主机及远程明文、SSL 路径逃逸和证书私钥不成对、邮箱策略、插件重复/危险网络目标;`SnapshotStore` 和 `ConfigManager` 测试证明无效候选不会改变活动快照、活动代次、待重启状态或磁盘分区文件。已通过 `go test ./config ./controllers ./listen/http_server -count=1`、`go test ./... -count=1` 和 `go vet ./...`。本证据未覆盖真实数据库、真实 SMTP 投递、证书链/私钥匹配、插件进程沙箱和生产部署环境,相关验收保持开放。 ### CG-008 实现统一 SecretChange 和 CredentialVault 适配 -- **状态**:未开始 +- **状态**:`[✓] 复审通过` - **优先级**:P0 - **依赖**:CG-002、CG-005 - **设计映射**:第 3.3、10.3 章 -- **修改范围**:`server/config/secret.go`、`server/utils/credential`、相关 DTO 和测试 -- **实施步骤**:实现 `keep`、`replace`、`clear`;统一数据库、SMTP、微信、Telegram 等凭据的加密、解密、脱敏和版本字段。 +- **修改范围**:`server/config/secret.go`、`server/config/sections.go`、`server/config/manager_v2.go`、`server/config/runtime_validator.go`、`server/controllers/config.go`、`server/utils/credential` 和相关测试 +- **实施步骤**:实现 `keep`、`replace`、`clear`;统一数据库、SMTP、插件等凭据的加密、解密、脱敏和版本字段;插件 Secret 使用 `plugins.<逻辑ID>.secret` 变更路径,并在分区载荷中保留已有密文。 - **安全要求**:不支持旧弱算法回退;密钥文件权限不合格时拒绝启动;Secret 不进入日志。 - **测试要求**:密文篡改、错误密钥、版本不支持、三种更新语义和 JSON 脱敏测试。 - **验收标准**:所有第三方配置使用同一输入和存储边界,查询接口不返回原文。 - **回退方式**:不迁移已有凭据,只关闭 V2 写接口;不得回退成明文。 -- **验收证据**:待补充。 +- **验收证据**:`StoredSecret`、`SecretChange`、`SecretPolicy` 和 `CredentialVault` 已统一接入数据库密码、SMTP Relay 密码和插件 Secret;插件支持 `replace`、`keep`、`clear`,未知插件、非法路径、直接提交密文均被拒绝;插件 Secret 经过同一套版本与密文格式校验,公共配置响应仅返回 `secretStatus`,不返回明文、密文或 Secret 输入值。`server/config/secret_test.go` 覆盖三种语义、密文篡改、错误密钥、版本不支持和 JSON 脱敏;`server/config/manager_v2_test.go` 覆盖插件 Secret 全流程及非法请求;`server/controllers/config_public_response_test.go` 覆盖插件公共响应脱敏。测试结束清理仅匹配 `server/.codex-smail-*` 的临时文件。已通过 `go test ./... -count=1`、`go vet ./...`、`git diff --check`,并验证 `mingw32-make clean_codex_test_artifacts` 只清理目标临时文件。真实数据库、SMTP 投递、插件进程沙箱、Ubuntu/Windows 部署和生产环境仍未完成集成验收。 ### CG-009 实现不可变运行时快照 -- **状态**:未开始 +- **状态**:`[✓] 复审通过` - **优先级**:P0 - **依赖**:CG-005、CG-007、CG-008 - **设计映射**:第 9 章 @@ -248,7 +248,7 @@ - **测试要求**:并发读取、连续更新、竞态检测、深复制和旧快照生命周期测试。 - **验收标准**:业务请求不再从磁盘读取配置,竞态测试无数据竞争。 - **回退方式**:切回旧读取适配层,不删除新快照代码。 -- **验收证据**:待补充。 +- **验收证据**:`server/config/snapshot.go` 使用 `atomic.Pointer[RuntimeConfig]` 和 CAS 发布;发布前对根配置、分区 map、插件 map、插件权限切片、网络目标切片和 `json.RawMessage` 深复制;拒绝低于当前活动代次的候选快照;`server/config/runtime_access.go` 为旧 `config.Instance` 提供只读深拷贝适配;覆盖旧配置的切片和 map 字段;`server/config/snapshot_test.go` 覆盖无效候选拒绝、输入和读取结果深拷贝、并发读取与连续更新、旧快照生命周期、旧代次并发发布;`server/config/manager_v2_test.go` 覆盖 `Snapshot`、`UpdateResult.Candidate` 和 `ApplyResult.Snapshot` 返回值隔离;已通过 `go test ./config -count=1` 和 `go test -race ./config -count=1`;本证据未覆盖真实生产进程切换、Ubuntu/Windows 部署和真实运行时长期观测,相关验收保持开放。 ### CG-010 实现 ConfigManager 核心接口 @@ -1140,6 +1140,10 @@ CG-053~CG-056 → AD-066 → CG-057 | 日期 | 任务 | 原状态 | 新状态 | 说明 | |---|---|---|---|---| +| 2026-08-28 | CG-009 | 未开始 | 已完成,等待复审 | 使用 `atomic.Pointer` 和 CAS 发布不可变运行时快照;补齐深拷贝、旧代次拒绝、并发读取/发布和 ConfigManager 返回值隔离测试;配置包竞态测试通过;真实生产进程切换和跨平台部署仍待验收 | +| 2026-08-28 | CG-009 | 已完成,等待复审 | 复审通过 | 独立复审确认 `atomic.Pointer` CAS 发布、深复制边界、旧代次冲突保护、返回值隔离和配置包竞态测试;`go test ./... -count=1`、`go vet ./...`、`git diff --check` 通过;仅本机自动化复审通过,真实生产进程切换、Ubuntu/Windows 部署及长期观测仍未覆盖 | +| 2026-08-28 | CG-008 | 已完成,等待复审 | 复审通过 | 复核插件 Secret 的 keep 保留、replace 加密、clear 确认、非法路径和直接密文拒绝逻辑;配置、控制器全量测试和 `go vet` 均通过,临时文件定向清理验证通过;真实数据库、SMTP、插件沙箱、Ubuntu/Windows 和生产环境边界继续保留为未验收项 | +| 2026-08-28 | CG-008 | 未开始 | 已完成,等待复审 | 完成统一 SecretChange 与 CredentialVault 适配;数据库、SMTP Relay 和插件 Secret 使用统一加密、版本、脱敏和更新语义;补齐插件 Secret 的 keep/replace/clear、非法路径与公共响应脱敏测试;Makefile 增加仅清理 `server/.codex-smail-*` 的测试收尾逻辑;真实数据库、SMTP、插件沙箱、Ubuntu/Windows 和生产环境仍待集成验收 | | 2026-08-27 | CG-005 | 未开始 | 已完成,等待复审 | 完成配置模型、三数据库条件字段、默认端口、SQLite `localRef` 约束和固定分区映射测试;自动化验证通过,真实数据库集成、跨平台部署和启动流程仍待验收 | | 2026-08-27 | CG-002 | 未开始 | 已完成,等待复审 | 完成敏感字段目录、持久化策略、管理 API 能力映射、配置 PUT 路由和授权负向测试;自动化检查通过,真实平台和生产观测仍待验收 | | 2026-08-27 | CG-003 | 未开始 | 已完成,等待复审 | 完成显式迁移框架、版本和校验和校验、三数据库方言定义、数据库锁、事务回滚和生产 `Sync2` 兼容边界;SQLite 自动化测试通过,MySQL/PostgreSQL 因未配置 DSN 未执行真实集成验收 | diff --git a/fe/src/App.vue b/fe/src/App.vue index e36c7016..272b6593 100644 --- a/fe/src/App.vue +++ b/fe/src/App.vue @@ -2,13 +2,14 @@ import {RouterView, useRoute} from 'vue-router' import HomeHeader from '@/views/components/HomeHeader/HomeHeader.vue' import HomeAside from '@/views/components/HomeAside/HomeAside.vue'; +import RecoverySetupPrompt from '@/views/components/RecoverySetupPrompt/RecoverySetupPrompt.vue' import {ref, watch, onMounted} from 'vue' import {useGlobalStatusStore} from "@/stores/useGlobalStatusStore"; const route = useRoute() const pageName = ref(route.name) const globalStatus = useGlobalStatusStore(); -const standalonePages = ['login', 'setup', 'forgot-password', 'reset-blocked'] +const standalonePages = ['login', 'login-verification', 'force-password-change', 'setup', 'forgot-password', 'reset-blocked'] onMounted(() => { if (!standalonePages.includes(route.name)) { @@ -55,6 +56,7 @@ watch( + diff --git a/fe/src/router/index.js b/fe/src/router/index.js index 32118d21..f288bd7a 100644 --- a/fe/src/router/index.js +++ b/fe/src/router/index.js @@ -1,61 +1,108 @@ -import { createRouter, createWebHashHistory } from 'vue-router' -import ListView from '../views/List/List.vue' -import EditerView from '../views/Editer/Editer.vue' -import LoginView from '../views/Login/Login.vue' -import EmailDetailView from '../views/EmailDetail/EmailDetail.vue' -import SetupView from '../views/Setup/Setup.vue' -import PasswordRecoveryView from '../views/PasswordRecovery/PasswordRecovery.vue' -import ResetBlockedView from '../views/ResetBlocked/ResetBlocked.vue' - +import { createRouter, createWebHashHistory } from "vue-router"; +import ListView from "../views/List/List.vue"; +import EditerView from "../views/Editer/Editer.vue"; +import LoginView from "../views/Login/Login.vue"; +import EmailDetailView from "../views/EmailDetail/EmailDetail.vue"; +import SetupView from "../views/Setup/Setup.vue"; +import PasswordRecoveryView from "../views/PasswordRecovery/PasswordRecovery.vue"; +import ResetBlockedView from "../views/ResetBlocked/ResetBlocked.vue"; +import LoginVerificationView from "../views/LoginVerification/LoginVerification.vue"; +import ForcePasswordChangeView from "../views/ForcePasswordChange/ForcePasswordChange.vue"; const router = createRouter({ - history: createWebHashHistory(), - routes: [ - { - path: '/', - name: 'home', - component: ListView - }, - { - path: '/list', - name: 'list', - component: ListView - }, - { - path: '/editer', - name: "editer", - component: EditerView - }, - { - path: '/login', - name: "login", - component: LoginView - }, - { - path: '/setup', - name: "setup", - component: SetupView - }, - { - path: '/forgot-password', - name: "forgot-password", - component: PasswordRecoveryView - }, - { - path: '/reset-blocked', - name: 'reset-blocked', - component: ResetBlockedView - }, - { - path: '/detail/:id', - name: "detail", - component: EmailDetailView + history: createWebHashHistory(), + routes: [ + { + path: "/", + name: "home", + component: ListView, + meta: {requiresAuth: true} + }, + { + path: "/list", + name: "list", + component: ListView, + meta: {requiresAuth: true} + }, + { + path: "/editer", + name: "editer", + component: EditerView, + meta: {requiresAuth: true} + }, + { + path: "/login", + name: "login", + component: LoginView + }, + { + path: "/login-verification", + name: "login-verification", + component: LoginVerificationView + }, + { + path: "/force-password-change", + name: "force-password-change", + component: ForcePasswordChangeView, + meta: {requiresAuth: true} + }, + { + path: "/setup", + name: "setup", + component: SetupView + }, + { + path: "/forgot-password", + name: "forgot-password", + component: PasswordRecoveryView + }, + { + path: "/reset-blocked", + name: "reset-blocked", + component: ResetBlockedView + }, + { + path: "/detail/:id", + name: "detail", + component: EmailDetailView, + meta: {requiresAuth: true} + } + ] +}); + +router.beforeEach(async (to) => { + const {useGlobalStatusStore} = await import("@/stores/useGlobalStatusStore"); + const globalStatus = useGlobalStatusStore(); + const needsAuthentication = to.meta.requiresAuth || to.name === "force-password-change"; + const authenticated = globalStatus.isLogin || (needsAuthentication && await globalStatus.refresh()); + + if (!authenticated && needsAuthentication) { + return { + name: "login", + query: {redirect: to.fullPath} + }; } - ] -}) + if (to.name === "force-password-change") { + if (!globalStatus.userInfos.must_change_password) { + return {name: "list"}; + } + return true; + } + if (authenticated && globalStatus.userInfos.must_change_password) { + return {name: "force-password-change"}; + } + if (!to.meta.requiresAuth) { + return true; + } + if (to.meta.capability && !globalStatus.hasCapability(to.meta.capability)) { + return {name: "list"}; + } + + return true; +}); export {router}; diff --git a/fe/src/stores/useGlobalStatusStore.js b/fe/src/stores/useGlobalStatusStore.js index 4825d3db..7d3f9e70 100644 --- a/fe/src/stores/useGlobalStatusStore.js +++ b/fe/src/stores/useGlobalStatusStore.js @@ -1,31 +1,97 @@ -import {defineStore} from "pinia"; -import {http} from "@/utils/axios"; +import { defineStore } from "pinia"; +import { http } from "@/utils/axios"; -const useGlobalStatusStore = defineStore('useGlobalStatusStore', { +const useGlobalStatusStore = defineStore("useGlobalStatusStore", { state() { return { userInfos: {}, mobileDrawerVisible: false, - settingsDrawerVisible: false - } + settingsDrawerVisible: false, + authChecked: false, + authLoading: false, + pendingLogin: null, + recoveryPromptDismissed: false + }; }, getters: { isLogin(state) { - return Object.keys(state.userInfos).length !== 0 + return Object.keys(state.userInfos).length !== 0; + }, + role(state) { + return state.userInfos.role || ""; + }, + capabilities(state) { + return Array.isArray(state.userInfos.capabilities) + ? state.userInfos.capabilities + : []; } }, actions: { - init(callback) { - let that = this - http.post("/api/user/info", {}).then(res => { - if (res.errorNo === 0) { - Object.assign(that.userInfos, res.data) - callback() + async refresh() { + if (this.authLoading) { + return this.isLogin; + } + + this.authLoading = true; + try { + const response = await http.post("/api/user/info", {}); + if (response.errorNo === 0 && response.data) { + this.setUser(response.data, false); + this.authChecked = true; + return true; } - }) + this.clear(); + return false; + } catch (error) { + this.clear(); + return false; + } finally { + this.authLoading = false; + } + }, + init(callback) { + this.refresh().then(() => { + if (typeof callback === "function") { + callback(); + } + }); + }, + clear() { + this.userInfos = {}; + this.pendingLogin = null; + this.recoveryPromptDismissed = false; + this.authChecked = true; + }, + setUser(payload, resetPrompt = false) { + const previousAccount = this.userInfos?.account || ""; + this.userInfos = payload && typeof payload === "object" ? { ...payload } : {}; + if (resetPrompt || previousAccount !== this.userInfos.account) { + this.recoveryPromptDismissed = false; + } + this.authChecked = true; + }, + dismissRecoveryPrompt() { + this.recoveryPromptDismissed = true; + }, + setPendingLogin(payload) { + this.pendingLogin = { + challengeId: payload?.challenge_id || "", + account: payload?.account || "", + email: payload?.email || "", + expiresAt: payload?.expires_at || "", + redirect: payload?.redirect || "/" + }; + }, + clearPendingLogin() { + this.pendingLogin = null; + }, + hasCapability(capability) { + if (!capability) { + return true; + } + return this.role === "super_admin" || this.capabilities.includes(capability); } } -}) +}); - -export {useGlobalStatusStore}; \ No newline at end of file +export { useGlobalStatusStore }; diff --git a/fe/src/utils/webauthn.js b/fe/src/utils/webauthn.js index e6998f30..d262e54f 100644 --- a/fe/src/utils/webauthn.js +++ b/fe/src/utils/webauthn.js @@ -33,7 +33,7 @@ function normalizeDescriptors(items) { export function normalizeCreationOptions(options) { const source = options?.publicKey || options?.response || options; if (!source?.challenge || !source?.user?.id) { - throw new Error('??????????'); + throw new Error('安全密钥参数无效'); } return { ...source, @@ -46,7 +46,7 @@ export function normalizeCreationOptions(options) { export function normalizeRequestOptions(options) { const source = options?.publicKey || options?.response || options; if (!source?.challenge) { - throw new Error('??????????'); + throw new Error('安全密钥参数无效'); } return { ...source, @@ -56,7 +56,7 @@ export function normalizeRequestOptions(options) { } export function serializeCredential(credential) { - if (!credential) throw new Error('??????????'); + if (!credential) throw new Error('安全密钥参数无效'); const response = credential.response; const result = { id: credential.id, diff --git a/fe/src/views/EmailDetail/EmailDetail.js b/fe/src/views/EmailDetail/EmailDetail.js index c19f25dd..e4644517 100644 --- a/fe/src/views/EmailDetail/EmailDetail.js +++ b/fe/src/views/EmailDetail/EmailDetail.js @@ -39,14 +39,14 @@ export function usePage() { try { tos.value = JSON.parse(res.data.to) } catch (error) { - console.warn('收件人地址解析失败', error) + tos.value = [] } } if (res.data.cc && res.data.cc !== "") { try { ccs.value = JSON.parse(res.data.cc) } catch (error) { - console.warn('抄送地址解析失败', error) + ccs.value = [] } } showCC.value = ccs.value && ccs.value.length > 0 diff --git a/fe/src/views/ForcePasswordChange/ForcePasswordChange.css b/fe/src/views/ForcePasswordChange/ForcePasswordChange.css new file mode 100644 index 00000000..2851a714 --- /dev/null +++ b/fe/src/views/ForcePasswordChange/ForcePasswordChange.css @@ -0,0 +1,86 @@ +.force-password-content { + width: 100%; + min-height: 100%; + display: flex; + align-items: center; + box-sizing: border-box; + padding: clamp(32px, 6vw, 64px); +} + +.force-password-card { + width: 100%; + max-width: 480px; + margin: 0 auto; +} + +.force-password-heading { + margin-bottom: 24px; +} + +.force-password-eyebrow { + display: inline-block; + margin-bottom: 12px; + color: var(--pm-primary-color); + font-size: 13px; + font-weight: 700; + letter-spacing: 0.08em; +} + +.force-password-heading h2 { + margin: 0 0 10px; + color: var(--pm-text-primary); + font-size: 34px; + font-weight: 700; + line-height: 1.2; +} + +.force-password-heading p { + margin: 0; + color: var(--pm-text-secondary); + line-height: 1.7; +} + +.force-password-alert { + margin-bottom: 24px; +} + +.force-password-form :deep(.el-form-item) { + margin-bottom: 18px; +} + +.force-password-form :deep(.el-input__wrapper) { + min-height: 46px; + border-radius: 12px; + box-shadow: 0 0 0 1px var(--pm-border-color) inset !important; +} + +.force-password-submit { + width: 100%; + min-height: 48px; + margin-top: 4px; + border-radius: 12px; + font-weight: 700; +} + +.force-password-logout { + display: flex; + margin: 14px auto 0; + font-weight: 600; +} + +@media (max-width: 760px) { + .force-password-content { + min-height: 0; + padding: 32px 24px 36px; + } +} + +@media (max-width: 380px) { + .force-password-content { + padding: 24px 14px 28px; + } + + .force-password-heading h2 { + font-size: 28px; + } +} diff --git a/fe/src/views/ForcePasswordChange/ForcePasswordChange.js b/fe/src/views/ForcePasswordChange/ForcePasswordChange.js new file mode 100644 index 00000000..56254ba7 --- /dev/null +++ b/fe/src/views/ForcePasswordChange/ForcePasswordChange.js @@ -0,0 +1,70 @@ +import { reactive, ref } from "vue" + +import { ElMessage } from "element-plus" + +import { useRouter } from "vue-router" + +import { http } from "@/utils/axios" + +import { useGlobalStatusStore } from "@/stores/useGlobalStatusStore" + +export function usePage() { + const router = useRouter() + const globalStatus = useGlobalStatusStore() + const loading = ref(false) + const form = reactive({ + currentPassword: "", + newPassword: "", + confirmPassword: "" + }) + + const submit = async () => { + if (!form.currentPassword || !form.newPassword || !form.confirmPassword) { + ElMessage.warning("请完整填写密码信息") + return + } + if (form.newPassword !== form.confirmPassword) { + ElMessage.warning("两次输入的新密码不一致") + return + } + if (new TextEncoder().encode(form.newPassword).length < 8) { + ElMessage.warning("新密码长度至少为 8 个字节") + return + } + + loading.value = true + try { + const response = await http.post("/api/settings/modify_password", { + current_password: form.currentPassword, + password: form.newPassword + }) + if (response.errorNo !== 0) { + ElMessage.error(response.errorMsg || "密码修改失败") + return + } + globalStatus.clear() + ElMessage.success("密码已修改,请使用新密码重新登录") + await router.replace({ name: "login" }) + } catch (error) { + ElMessage.error("密码修改失败,请稍后重试") + } finally { + loading.value = false + } + } + + const logout = async () => { + try { + await http.post("/api/logout", {}) + } finally { + globalStatus.clear() + await router.replace({ name: "login" }) + } + } + + return { + form, + loading, + submit, + logout + } +} diff --git a/fe/src/views/ForcePasswordChange/ForcePasswordChange.vue b/fe/src/views/ForcePasswordChange/ForcePasswordChange.vue new file mode 100644 index 00000000..906d87b7 --- /dev/null +++ b/fe/src/views/ForcePasswordChange/ForcePasswordChange.vue @@ -0,0 +1,95 @@ + + + + + diff --git a/fe/src/views/Login/Login.js b/fe/src/views/Login/Login.js index c4a8ec11..a479ac0c 100644 --- a/fe/src/views/Login/Login.js +++ b/fe/src/views/Login/Login.js @@ -1,66 +1,63 @@ -import {reactive, ref} from 'vue' +import { reactive, ref } from "vue" -import {ElMessage} from 'element-plus' +import { ElMessage } from "element-plus" -import {useRouter} from 'vue-router' +import { useRouter } from "vue-router" -import lang from '../../i18n/i18n'; +import lang from "../../i18n/i18n" -import {http} from "@/utils/axios"; +import { http } from "@/utils/axios" -import {useGlobalStatusStore} from "@/stores/useGlobalStatusStore"; +import { useGlobalStatusStore } from "@/stores/useGlobalStatusStore" export function usePage() { const router = useRouter() - const globalStatus = useGlobalStatusStore(); - - const loading = ref(false); - + const globalStatus = useGlobalStatusStore() + const loading = ref(false) const form = reactive({ - account: '', - password: '', + account: "", + password: "", }) - - const onSubmit = () => { + + const onSubmit = async () => { if (!form.account || !form.password) { - ElMessage.warning(lang.login_fill_required); - return; + ElMessage.warning(lang.login_fill_required) + return } - loading.value = true; - http.post("/api/login", form).then(res => { - loading.value = false; + loading.value = true + try { + const res = await http.post("/api/login", form) if (res.errorNo !== 0) { ElMessage.error(res.errorMsg) - } else { - Object.assign(globalStatus.userInfos , res.data) - router.replace({ - path: '/', - query: { - redirect: router.currentRoute.fullPath - } - }) + return } - }).catch(() => { - loading.value = false; - }) + const redirect = typeof router.currentRoute.value.query.redirect === "string" + ? router.currentRoute.value.query.redirect + : "/" + if (res.data?.pending) { + globalStatus.setPendingLogin({ ...res.data, redirect }) + await router.replace({ name: "login-verification" }) + return + } + globalStatus.clearPendingLogin() + globalStatus.setUser(res.data, true) + await router.replace(redirect) + } catch (error) { + ElMessage.error("登录请求失败,请稍后重试") + } finally { + loading.value = false + } } const goForgotPassword = () => { - router.push({name: 'forgot-password'}) + router.push({ name: "forgot-password" }) } return { - reactive, - ref, - ElMessage, - router, lang, - http, - useGlobalStatusStore, - globalStatus, - loading, form, onSubmit, + loading, goForgotPassword } } diff --git a/fe/src/views/LoginVerification/LoginVerification.css b/fe/src/views/LoginVerification/LoginVerification.css new file mode 100644 index 00000000..82430cb6 --- /dev/null +++ b/fe/src/views/LoginVerification/LoginVerification.css @@ -0,0 +1,107 @@ +.verification-content { + width: 100%; + min-height: 100%; + display: flex; + align-items: center; + box-sizing: border-box; + padding: clamp(32px, 6vw, 64px); +} + +.verification-card { + width: 100%; + max-width: 460px; + margin: 0 auto; +} + +.verification-heading { + margin-bottom: 32px; +} + +.verification-eyebrow { + display: inline-block; + margin-bottom: 12px; + color: var(--pm-primary-color); + font-size: 13px; + font-weight: 600; + letter-spacing: 0.08em; +} + +.verification-heading h2 { + margin: 0 0 10px; + color: var(--pm-text-primary); + font-size: 34px; + font-weight: 600; +} + +.verification-heading p { + margin: 0; + color: var(--pm-text-secondary); + line-height: 1.7; +} + +.verification-heading strong { + color: var(--pm-text-primary); + overflow-wrap: anywhere; +} + +.verification-input :deep(.el-input__wrapper) { + min-height: 48px; + border-radius: 12px; + box-shadow: 0 0 0 1px var(--pm-border-color) inset !important; +} + +.verification-expiry { + margin: 14px 0 0; + color: var(--pm-text-secondary); + font-size: 13px; + text-align: center; +} + +.verification-submit, +.webauthn-login-button { + width: 100%; + min-height: 48px; + border-radius: 12px; + font-weight: 600; +} + +.verification-submit { + margin-top: 24px; +} + +.verification-actions { + display: flex; + justify-content: center; + gap: 12px; + margin-top: 14px; +} + +.webauthn-unavailable { + margin: 0; + color: var(--pm-text-secondary); + font-size: 13px; + line-height: 1.6; + text-align: center; +} + +@media (max-width: 760px) { + .verification-content { + min-height: 0; + padding: 32px 24px 36px; + } +} + +@media (max-width: 380px) { + .verification-content { + padding: 24px 14px 28px; + } + + .verification-heading h2 { + font-size: 28px; + } + + .verification-actions { + flex-direction: column; + align-items: center; + } +} \ No newline at end of file diff --git a/fe/src/views/LoginVerification/LoginVerification.js b/fe/src/views/LoginVerification/LoginVerification.js new file mode 100644 index 00000000..096f4ea0 --- /dev/null +++ b/fe/src/views/LoginVerification/LoginVerification.js @@ -0,0 +1,186 @@ +import { computed, onBeforeUnmount, onMounted, ref } from "vue" + +import { ElMessage } from "element-plus" + +import { useRouter } from "vue-router" + +import { useGlobalStatusStore } from "@/stores/useGlobalStatusStore" +import { http } from "@/utils/axios" +import { + normalizeRequestOptions, + serializeCredential, + webAuthnSupported +} from "@/utils/webauthn" + +export function usePage() { + const router = useRouter() + const globalStatus = useGlobalStatusStore() + const pending = computed(() => globalStatus.pendingLogin) + const code = ref("") + const loading = ref(false) + const resending = ref(false) + const webAuthnLoading = ref(false) + const remainingSeconds = ref(0) + const errorMessage = ref("") + let timer = null + + const expiresAt = computed(() => pending.value?.expiresAt || "") + const webAuthnAvailable = computed(() => webAuthnSupported()) + + const updateRemaining = () => { + const timestamp = Date.parse(expiresAt.value) + remainingSeconds.value = Number.isFinite(timestamp) + ? Math.max(0, Math.ceil((timestamp - Date.now()) / 1000)) + : 0 + } + + const startTimer = () => { + updateRemaining() + timer = window.setInterval(updateRemaining, 1000) + } + + const stopTimer = () => { + if (timer !== null) { + window.clearInterval(timer) + timer = null + } + } + + const goBackToLogin = async () => { + globalStatus.clearPendingLogin() + await router.replace({ name: "login" }) + } + + const verifyCode = async () => { + if (!pending.value?.challengeId) { + await goBackToLogin() + return + } + if (!code.value.trim()) { + ElMessage.warning("请输入邮箱验证码") + return + } + if (remainingSeconds.value <= 0) { + errorMessage.value = "验证码已过期,请重新登录" + ElMessage.warning(errorMessage.value) + return + } + + loading.value = true + errorMessage.value = "" + try { + const response = await http.post("/api/security/login/verify", { + id: pending.value.challengeId, + account: pending.value.account, + code: code.value.trim() + }) + if (response.errorNo !== 0) { + throw new Error(response.errorMsg || "验证码验证失败") + } + const redirect = pending.value.redirect || "/" + globalStatus.clearPendingLogin() + globalStatus.setUser(response.data, true) + await router.replace(redirect) + } catch (error) { + errorMessage.value = error?.message || "验证码验证失败,请重试" + ElMessage.error(errorMessage.value) + } finally { + loading.value = false + } + } + + const resendCode = async () => { + if (!pending.value?.challengeId || resending.value) { + return + } + resending.value = true + errorMessage.value = "" + try { + const response = await http.post("/api/security/login/resend", { + id: pending.value.challengeId, + account: pending.value.account + }) + if (response.errorNo !== 0 || !response.data?.pending) { + throw new Error(response.errorMsg || "验证码发送失败") + } + globalStatus.setPendingLogin({ + ...response.data, + redirect: pending.value.redirect + }) + code.value = "" + ElMessage.success("验证码已重新发送") + stopTimer() + startTimer() + } catch (error) { + errorMessage.value = error?.message || "验证码发送失败,请稍后重试" + ElMessage.error(errorMessage.value) + } finally { + resending.value = false + } + } + + const verifyWithWebAuthn = async () => { + if (!webAuthnAvailable.value || webAuthnLoading.value) { + return + } + webAuthnLoading.value = true + errorMessage.value = "" + try { + const begin = await http.post("/api/security/webauthn/login/begin", { + challenge_id: pending.value.challengeId, + account: pending.value.account + }) + if (begin.errorNo !== 0) { + throw new Error(begin.errorMsg || "安全密钥登录不可用") + } + const credential = await navigator.credentials.get({ + publicKey: normalizeRequestOptions(begin.data.options) + }) + const finish = await http.post("/api/security/webauthn/login/finish", { + challenge_id: pending.value.challengeId, + account: pending.value.account, + session_id: begin.data.session_id, + credential: serializeCredential(credential) + }) + if (finish.errorNo !== 0) { + throw new Error(finish.errorMsg || "安全密钥验证失败") + } + const redirect = pending.value?.redirect || "/" + globalStatus.clearPendingLogin() + globalStatus.setUser(finish.data, true) + await router.replace(redirect) + } catch (error) { + if (error?.name !== "NotAllowedError") { + errorMessage.value = error?.message || "安全密钥验证失败,请重试" + ElMessage.error(errorMessage.value) + } + } finally { + webAuthnLoading.value = false + } + } + + onMounted(() => { + if (!pending.value?.challengeId) { + router.replace({ name: "login" }) + return + } + startTimer() + }) + + onBeforeUnmount(stopTimer) + + return { + pending, + code, + loading, + resending, + webAuthnLoading, + remainingSeconds, + errorMessage, + webAuthnAvailable, + verifyCode, + resendCode, + verifyWithWebAuthn, + goBackToLogin + } +} diff --git a/fe/src/views/LoginVerification/LoginVerification.vue b/fe/src/views/LoginVerification/LoginVerification.vue new file mode 100644 index 00000000..fffd44ac --- /dev/null +++ b/fe/src/views/LoginVerification/LoginVerification.vue @@ -0,0 +1,110 @@ + + + + + \ No newline at end of file diff --git a/fe/src/views/Setup/Setup.js b/fe/src/views/Setup/Setup.js index 6593e640..3fd2d06c 100644 --- a/fe/src/views/Setup/Setup.js +++ b/fe/src/views/Setup/Setup.js @@ -244,7 +244,6 @@ export function usePage() { ElMessage.error(res.errorMsg) } else { sslSettings.paramsList = res.data - console.log(sslSettings.paramsList) } }) diff --git a/fe/src/views/components/ConfigSettings/ConfigSettings.css b/fe/src/views/components/ConfigSettings/ConfigSettings.css new file mode 100644 index 00000000..ef9d9983 --- /dev/null +++ b/fe/src/views/components/ConfigSettings/ConfigSettings.css @@ -0,0 +1,242 @@ +.config-settings { + display: grid; + gap: 24px; + padding-bottom: 28px; +} +.settings-header, +.panel-heading, +.status-heading { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 16px; +} +.settings-header h3, +.panel-heading h4, +.status-heading h4 { + margin: 0; + color: var(--pm-text-primary); +} +.settings-header h3 { + font-size: 22px; +} +.panel-heading h4, +.status-heading h4 { + margin-top: 5px; + font-size: 18px; +} +.settings-desc { + max-width: 680px; + margin: 8px 0 0; + color: var(--pm-text-secondary); + line-height: 1.65; +} +.section-eyebrow { + color: var(--pm-primary-color); + font-size: 12px; + font-weight: 700; + letter-spacing: .08em; +} +.status-panel, +.editor-panel, +.rollback-panel, +.audit-panel { + padding: 20px; + border: 1px solid var(--pm-border-color); + border-radius: var(--pm-radius-lg); + background: var(--pm-bg-secondary); +} +.status-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; + margin-top: 18px; +} +.status-item { + display: grid; + gap: 8px; + min-width: 0; + padding: 14px; + border-radius: var(--pm-radius-sm); + background: var(--pm-bg-primary); +} +.status-item span { + color: var(--pm-text-secondary); + font-size: 13px; +} +.status-item strong { + color: var(--pm-text-primary); + font-size: 14px; + overflow-wrap: anywhere; +} +.status-wide { + grid-column: span 3; +} +.tag-list { + display: flex; + flex-wrap: wrap; + gap: 8px; +} +.config-alert, +.degraded-alert { + margin-top: 16px; +} +.section-select { + width: 150px; +} +.editor-meta { + display: flex; + flex-wrap: wrap; + gap: 8px 20px; + margin: 18px 0 10px; + color: var(--pm-text-secondary); + font-size: 13px; +} +.config-editor :deep(.el-textarea__inner) { + min-height: 300px !important; + padding: 14px; + color: var(--pm-text-primary); + font-family: ui-monospace, SFMono-Regular, Consolas, monospace; + line-height: 1.6; + border: 1px solid var(--pm-border-color); + border-radius: var(--pm-radius-sm); + background: var(--pm-bg-primary); +} +.secret-editor { + display: grid; + gap: 10px; + margin-top: 16px; + padding: 14px; + border: 1px dashed var(--pm-border-color); + border-radius: var(--pm-radius-sm); + background: var(--pm-bg-primary); +} +.secret-editor strong { + color: var(--pm-text-primary); +} +.secret-editor p { + margin: 5px 0 0; + color: var(--pm-text-secondary); + font-size: 13px; + line-height: 1.5; +} +.confirmation-check { + margin-top: 16px; +} +.action-row, +.audit-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; + margin-top: 18px; +} +.backup-list { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); + gap: 10px; + margin-top: 18px; +} +.backup-item { + display: grid; + gap: 5px; + padding: 12px; + color: var(--pm-text-primary); + text-align: left; + border: 1px solid var(--pm-border-color); + border-radius: var(--pm-radius-sm); + background: var(--pm-bg-primary); + cursor: pointer; +} +.backup-item:hover, +.backup-item.selected { + border-color: var(--pm-primary-color); + box-shadow: 0 0 0 2px color-mix(in srgb, var(--pm-primary-color) 16%, transparent); +} +.backup-item small { + color: var(--pm-text-secondary); +} +.preview-box, +.result-box { + display: grid; + gap: 7px; + margin-top: 16px; + padding: 14px; + border-radius: var(--pm-radius-sm); + font-size: 13px; + line-height: 1.5; +} +.preview-box { + color: var(--pm-text-primary); + background: color-mix(in srgb, var(--pm-primary-color) 8%, var(--pm-bg-primary)); +} +.result-success { + color: #166534; + background: #f0fdf4; +} +.result-error { + color: #991b1b; + background: #fef2f2; +} +.result-box ul { + margin: 0; + padding-left: 18px; +} +.audit-list { + display: grid; + gap: 10px; + margin-top: 18px; +} +.audit-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 14px; + border-radius: var(--pm-radius-sm); + background: var(--pm-bg-primary); +} +.audit-item div { + display: grid; + gap: 4px; + min-width: 0; +} +.audit-item strong { + color: var(--pm-text-primary); +} +.audit-item span, +.audit-item time { + color: var(--pm-text-secondary); + font-size: 13px; +} +.audit-item time { + flex: none; +} +@media (max-width: 640px) { + .status-panel, + .editor-panel, + .rollback-panel, + .audit-panel { + padding: 16px; + } + .status-grid { + grid-template-columns: 1fr; + } + .status-wide { + grid-column: auto; + } + .settings-header, + .panel-heading, + .status-heading, + .audit-item { + align-items: stretch; + flex-direction: column; + } + .section-select { + width: 100%; + } + .action-row .el-button, + .audit-actions .el-button { + flex: 1; + min-width: 120px; + } +} \ No newline at end of file diff --git a/fe/src/views/components/ConfigSettings/ConfigSettings.js b/fe/src/views/components/ConfigSettings/ConfigSettings.js new file mode 100644 index 00000000..57fdb86c --- /dev/null +++ b/fe/src/views/components/ConfigSettings/ConfigSettings.js @@ -0,0 +1,304 @@ +import { computed, onMounted, reactive, ref } from 'vue' +import { ElMessage, ElMessageBox } from 'element-plus' +import { http } from '@/utils/axios' +import { useGlobalStatusStore } from '@/stores/useGlobalStatusStore' + +const sections = [ + { value: 'base', label: '基础配置' }, + { value: 'smtp', label: 'SMTP 配置' }, + { value: 'email', label: '邮箱策略' }, + { value: 'ssl', label: 'SSL 配置' }, + { value: 'plugins', label: '插件配置' } +] + +const serviceLabels = { + smtp: 'SMTP 服务', + email: '邮箱服务', + ssl: 'SSL 服务', + plugins: '插件服务' +} + +const sectionLabels = Object.fromEntries(sections.map(item => [item.value, item.label])) +const operationLabels = { + validate: '验证配置', + update: '保存配置', + apply: '应用配置', + rollback_preview: '预览回滚', + rollback_ticket: '签发回滚票据', + rollback: '执行回滚' +} + +export function usePage() { + const globalStatus = useGlobalStatusStore() + const loading = ref(false) + const working = ref('') + const backupsLoading = ref(false) + const auditLoading = ref(false) + const status = reactive({ + setupState: '', + activeGeneration: 0, + lastValidAt: '', + pendingRestart: [], + degradedReasons: [] + }) + const selectedSection = ref('base') + const editorText = ref('') + const sectionError = ref('') + const secretValue = ref('') + const confirmed = ref(false) + const savedGeneration = ref(0) + const validationResult = ref(null) + const backups = ref([]) + const rollbackGeneration = ref(0) + const rollbackConfirmed = ref(false) + const rollbackPreview = ref(null) + const auditItems = ref([]) + + const canWrite = computed(() => globalStatus.hasCapability('config.write_global')) + const canRollback = computed(() => globalStatus.hasCapability('config.rollback')) + const canAudit = computed(() => globalStatus.hasCapability('audit.read')) + const canExportAudit = computed(() => globalStatus.hasCapability('audit.export')) + const stateLabel = computed(() => ({ new: '未初始化', bootstrap: '初始化中', ready: '就绪', degraded: '降级' }[status.setupState] || status.setupState || '未知')) + const stateTagType = computed(() => ({ ready: 'success', degraded: 'warning', bootstrap: 'info', new: 'danger' }[status.setupState] || 'info')) + const secretField = computed(() => { + if (selectedSection.value === 'base') { + return { label: '数据库密码', description: '只在本次请求内传输,保存后仅保留密文状态。留空表示保持原值。', placeholder: '输入新数据库密码(可选)' } + } + if (selectedSection.value === 'smtp') { + return { label: 'SMTP Relay 密码', description: '只在本次请求内传输,保存后仅保留密文状态。留空表示保持原值。', placeholder: '输入新的 Relay 密码(可选)' } + } + return null + }) + const sensitiveHint = computed(() => secretField.value ? '密码字段已脱敏,修改请使用下方输入框' : '当前分区不包含可编辑密文') + + const notifyResponseError = (response, fallback) => { + if (!response || response.errorNo !== 0) { + throw new Error(response?.errorMsg || fallback) + } + } + + const formatTime = value => value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '-' + const serviceLabel = value => serviceLabels[value] || value + const sectionLabel = value => sectionLabels[value] || value || '-' + const operationLabel = value => operationLabels[value] || value || '-' + + const loadStatus = async () => { + const response = await http.get('/api/v1/config/status') + notifyResponseError(response, '配置状态读取失败') + Object.assign(status, response.data || {}) + } + + const loadSection = async () => { + sectionError.value = '' + secretValue.value = '' + validationResult.value = null + savedGeneration.value = 0 + try { + const response = await http.get(`/api/v1/config/${selectedSection.value}`) + notifyResponseError(response, '配置分区读取失败') + editorText.value = JSON.stringify(response.data || {}, null, 2) + } catch (error) { + sectionError.value = error.message || '配置分区读取失败' + editorText.value = '' + } + } + + const loadBackups = async () => { + if (!canRollback.value) return + backupsLoading.value = true + try { + const response = await http.get('/api/v1/config/backups') + notifyResponseError(response, '配置备份读取失败') + backups.value = Array.isArray(response.data) ? response.data : [] + } catch (error) { + ElMessage.error(error.message || '配置备份读取失败') + } finally { + backupsLoading.value = false + } + } + + const loadAudit = async () => { + if (!canAudit.value) return + auditLoading.value = true + try { + const response = await http.get('/api/v1/audits/config?limit=50') + notifyResponseError(response, '配置审计读取失败') + auditItems.value = Array.isArray(response.data) ? response.data : [] + } catch (error) { + ElMessage.error(error.message || '配置审计读取失败') + } finally { + auditLoading.value = false + } + } + + const loadAll = async () => { + loading.value = true + try { + await Promise.all([loadStatus(), loadSection(), loadBackups(), loadAudit()]) + } catch (error) { + ElMessage.error(error.message || '配置管理数据读取失败') + } finally { + loading.value = false + } + } + + const parsePayload = () => { + try { + const payload = JSON.parse(editorText.value) + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { + throw new Error('配置必须是 JSON 对象') + } + if (selectedSection.value === 'base') { + delete payload.databasePasswordStatus + } + if (selectedSection.value === 'smtp') { + delete payload.relayPasswordStatus + } + if (selectedSection.value === 'plugins' && payload.plugins && typeof payload.plugins === 'object') { + Object.values(payload.plugins).forEach(plugin => { + if (plugin && typeof plugin === 'object') { + delete plugin.settingsConfigured + } + }) + } + return payload + } catch (error) { + throw new Error(error.message || 'JSON 格式错误') + } + } + + const buildRequest = () => { + const secretChanges = {} + const value = secretValue.value.trim() + if (value && selectedSection.value === 'base') { + secretChanges['database.password'] = { operation: 'replace', value: { plaintext: value } } + } + if (value && selectedSection.value === 'smtp') { + secretChanges['relay.password'] = { operation: 'replace', value: { plaintext: value } } + } + return { + expectedGeneration: Number(status.activeGeneration), + payload: parsePayload(), + secretChanges, + confirmation: { confirmed: confirmed.value, method: 'recent_auth' } + } + } + + const validateConfig = async () => { + working.value = 'validate' + try { + const request = buildRequest() + const response = await http.post(`/api/v1/config/${selectedSection.value}/validate`, request) + notifyResponseError(response, '配置验证失败') + validationResult.value = response.data || null + ElMessage[validationResult.value?.valid ? 'success' : 'warning'](validationResult.value?.valid ? '配置验证通过' : '配置验证未通过') + } catch (error) { + ElMessage.error(error.message || '配置验证失败') + } finally { + working.value = '' + } + } + + const saveConfig = async () => { + working.value = 'save' + try { + const request = buildRequest() + const response = await http.put(`/api/v1/config/${selectedSection.value}`, request) + notifyResponseError(response, '配置保存失败') + savedGeneration.value = response.data?.generation || 0 + validationResult.value = { valid: true, generation: savedGeneration.value, issues: [] } + await loadStatus() + ElMessage.success(`候选配置已保存,代次 ${savedGeneration.value} 等待应用`) + } catch (error) { + ElMessage.error(error.message || '配置保存失败') + } finally { + working.value = '' + } + } + + const applyConfig = async () => { + if (!savedGeneration.value) return + working.value = 'apply' + try { + const response = await http.post(`/api/v1/config/${selectedSection.value}/apply`, { generation: savedGeneration.value }) + notifyResponseError(response, '配置应用失败') + savedGeneration.value = 0 + await Promise.all([loadStatus(), loadSection()]) + ElMessage.success('配置已应用') + } catch (error) { + ElMessage.error(error.message || '配置应用失败') + } finally { + working.value = '' + } + } + + const previewRollback = async () => { + if (!rollbackGeneration.value) return + working.value = 'preview' + rollbackPreview.value = null + try { + const response = await http.post('/api/v1/config/rollback/preview', { targetGeneration: rollbackGeneration.value }) + notifyResponseError(response, '回滚预览失败') + rollbackPreview.value = response.data || null + ElMessage.success('回滚预览已生成,请确认变更分区') + } catch (error) { + ElMessage.error(error.message || '回滚预览失败') + } finally { + working.value = '' + } + } + + const executeRollback = async () => { + if (!rollbackPreview.value || !rollbackConfirmed.value) return + try { + await ElMessageBox.confirm('回滚会替换当前候选配置并可能需要重启服务,确定继续吗?', '确认执行回滚', { type: 'warning', confirmButtonText: '继续回滚', cancelButtonText: '取消' }) + working.value = 'rollback' + const ticketResponse = await http.post('/api/v1/config/rollback/ticket', { + targetGeneration: rollbackPreview.value.targetGeneration, + confirmation: { confirmed: true, method: 'recent_auth' } + }) + notifyResponseError(ticketResponse, '回滚票据签发失败') + const response = await http.post('/api/v1/config/rollback', { ticket: ticketResponse.data?.ticket }) + notifyResponseError(response, '配置回滚失败') + rollbackPreview.value = null + rollbackConfirmed.value = false + await Promise.all([loadStatus(), loadSection(), loadBackups()]) + ElMessage.success('配置已回滚') + } catch (error) { + if (error !== 'cancel' && error !== 'close') ElMessage.error(error.message || '配置回滚失败') + } finally { + working.value = '' + } + } + + const exportAudit = async format => { + working.value = format === 'csv' ? 'export-csv' : 'export' + try { + const response = await http.post('/api/v1/audits/config', { format, limit: 500 }, { responseType: 'blob' }) + const blob = response.data instanceof Blob ? response.data : new Blob([response.data], { type: format === 'csv' ? 'text/csv' : 'application/json' }) + const url = URL.createObjectURL(blob) + const anchor = document.createElement('a') + anchor.href = url + anchor.download = `smail-config-audit.${format}` + anchor.click() + URL.revokeObjectURL(url) + ElMessage.success('审计记录已导出') + } catch (error) { + ElMessage.error(error.message || '审计导出失败') + } finally { + working.value = '' + } + } + + onMounted(loadAll) + + return { + loading, working, status, stateLabel, stateTagType, sectionOptions: sections, + selectedSection, editorText, sectionError, sensitiveHint, secretField, secretValue, + confirmed, savedGeneration, validationResult, canWrite, canRollback, canAudit, canExportAudit, + backupsLoading, backups, rollbackGeneration, rollbackConfirmed, rollbackPreview, + auditLoading, auditItems, loadAll, loadSection, validateConfig, saveConfig, applyConfig, + loadBackups, previewRollback, executeRollback, loadAudit, exportAudit, formatTime, + serviceLabel, sectionLabel, operationLabel + } +} diff --git a/fe/src/views/components/ConfigSettings/ConfigSettings.vue b/fe/src/views/components/ConfigSettings/ConfigSettings.vue new file mode 100644 index 00000000..7d64fca0 --- /dev/null +++ b/fe/src/views/components/ConfigSettings/ConfigSettings.vue @@ -0,0 +1,240 @@ + + + + + \ No newline at end of file diff --git a/fe/src/views/components/HomeHeader/HomeHeader.js b/fe/src/views/components/HomeHeader/HomeHeader.js index 89b6d887..1b21dd7f 100644 --- a/fe/src/views/components/HomeHeader/HomeHeader.js +++ b/fe/src/views/components/HomeHeader/HomeHeader.js @@ -1,9 +1,11 @@ import {EpMenu} from "vue-icons-plus/ep"; -import {ref, onMounted, onUnmounted} from 'vue' +import {computed, ref, onMounted, onUnmounted} from 'vue' import SecuritySettings from '@/views/components/SecuritySettings/SecuritySettings.vue' +import ConfigSettings from '@/views/components/ConfigSettings/ConfigSettings.vue' + import lang from '../../../i18n/i18n'; import GroupSettings from '../GroupSettings/GroupSettings.vue'; @@ -43,6 +45,7 @@ export function usePage() { onMounted, onUnmounted, SecuritySettings, + ConfigSettings, lang, GroupSettings, RuleSettings, @@ -53,7 +56,10 @@ export function usePage() { globalStatus, userInfos, isMobile, - handleResize + handleResize, + canReadConfig: computed(() => globalStatus.hasCapability("config.read")), + canManageUsers: computed(() => globalStatus.hasCapability("user.manage")), + canReadPlugins: computed(() => globalStatus.hasCapability("plugin.read")) } } @@ -61,6 +67,7 @@ export { EpMenu, BrandLogo, SecuritySettings, + ConfigSettings, GroupSettings, RuleSettings, UserManagement, diff --git a/fe/src/views/components/HomeHeader/HomeHeader.vue b/fe/src/views/components/HomeHeader/HomeHeader.vue index 858d9667..bcc7df28 100644 --- a/fe/src/views/components/HomeHeader/HomeHeader.vue +++ b/fe/src/views/components/HomeHeader/HomeHeader.vue @@ -23,16 +23,19 @@ + + + - + - + @@ -40,13 +43,15 @@ diff --git a/fe/src/views/components/RecoverySetupPrompt/RecoverySetupPrompt.css b/fe/src/views/components/RecoverySetupPrompt/RecoverySetupPrompt.css new file mode 100644 index 00000000..4df56b84 --- /dev/null +++ b/fe/src/views/components/RecoverySetupPrompt/RecoverySetupPrompt.css @@ -0,0 +1,75 @@ +.recovery-prompt-content { + color: var(--pm-text-primary); +} + +.recovery-prompt-icon { + width: 44px; + height: 44px; + display: grid; + place-items: center; + margin-bottom: 16px; + border-radius: 14px; + color: var(--pm-primary-color); + background: var(--el-color-primary-light-9); + font-size: 18px; + font-weight: 700; +} + +.recovery-prompt-content h3 { + margin: 0 0 10px; + font-size: 20px; + line-height: 1.4; +} + +.recovery-prompt-content p { + margin: 0 0 18px; + color: var(--pm-text-secondary); + line-height: 1.75; +} + +.recovery-code-result { + display: grid; + gap: 14px; + margin-top: 16px; +} + +.recovery-code-list { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; + padding: 14px; + border: 1px solid var(--pm-border-color); + border-radius: var(--pm-radius-md); + background: var(--pm-bg-secondary); +} + +.recovery-code-list code { + padding: 8px 10px; + border-radius: 8px; + color: var(--pm-text-primary); + background: var(--pm-bg-primary); + font-family: ui-monospace, SFMono-Regular, Consolas, monospace; + text-align: center; + letter-spacing: 0.08em; +} + +.recovery-prompt-actions { + display: flex; + justify-content: flex-end; + gap: 10px; +} + +@media (max-width: 520px) { + .recovery-code-list { + grid-template-columns: 1fr; + } + + .recovery-prompt-actions { + flex-direction: column-reverse; + } + + .recovery-prompt-actions .el-button { + width: 100%; + margin-left: 0; + } +} diff --git a/fe/src/views/components/RecoverySetupPrompt/RecoverySetupPrompt.vue b/fe/src/views/components/RecoverySetupPrompt/RecoverySetupPrompt.vue new file mode 100644 index 00000000..62cff256 --- /dev/null +++ b/fe/src/views/components/RecoverySetupPrompt/RecoverySetupPrompt.vue @@ -0,0 +1,104 @@ + + + + + diff --git a/fe/src/views/components/SecuritySettings/SecuritySettings.js b/fe/src/views/components/SecuritySettings/SecuritySettings.js index f663aea4..789bd59d 100644 --- a/fe/src/views/components/SecuritySettings/SecuritySettings.js +++ b/fe/src/views/components/SecuritySettings/SecuritySettings.js @@ -1,152 +1,242 @@ -import {onMounted, reactive, ref} from 'vue' +import { computed, onMounted, reactive, ref } from 'vue' -import {ElMessageBox, ElNotification} from 'element-plus' +import { ElMessageBox, ElNotification } from 'element-plus' -import lang from '../../../i18n/i18n'; - -import {http} from '@/utils/axios'; - -import {normalizeCreationOptions, serializeCredential, webAuthnSupported} from '@/utils/webauthn'; +import lang from '../../../i18n/i18n' +import { http } from '@/utils/axios' +import { useGlobalStatusStore } from '@/stores/useGlobalStatusStore' +import { normalizeCreationOptions, serializeCredential, webAuthnSupported } from '@/utils/webauthn' export function usePage() { - const supported = webAuthnSupported(); - - const registering = ref(false); - - const credentialsLoading = ref(false); - - const credentials = ref([]); - - const ruleForm = reactive({current_pwd: '', new_pwd: '', new_pwd2: ''}) - + const globalStatus = useGlobalStatusStore() + const isSuperAdmin = computed(() => globalStatus.role === 'super_admin') + const supported = webAuthnSupported() + + const registering = ref(false) + const credentialsLoading = ref(false) + const credentials = ref([]) + const securityLoading = ref(false) + const securityQuestion = reactive({ configured: false, question: '' }) + const questionForm = reactive({ question: '', answer: '' }) + const recoveryConfigured = ref(false) + const generatedCodes = ref([]) + const externalEmails = ref([]) + const externalLoading = ref(false) + const bindForm = reactive({ email: '', type: 'backup', challengeId: '', bindingId: 0, code: '' }) + + const ruleForm = reactive({ current_pwd: '', new_pwd: '', new_pwd2: '' }) const rules = reactive({ - current_pwd: [{required: true, message: lang.err_required_pwd, trigger: 'blur'}], - new_pwd: [{required: true, message: lang.err_required_pwd, trigger: 'blur'}], - new_pwd2: [{required: true, message: lang.err_required_pwd, trigger: 'blur'}], + current_pwd: [{ required: true, message: lang.err_required_pwd, trigger: 'blur' }], + new_pwd: [{ required: true, message: lang.err_required_pwd, trigger: 'blur' }], + new_pwd2: [{ required: true, message: lang.err_required_pwd, trigger: 'blur' }], }) - + const notify = (message, type = 'error') => { - ElNotification({title: type === 'success' ? '操作成功' : '操作失败', message, type}); + ElNotification({ title: type === 'success' ? '操作成功' : '操作失败', message, type }) } - + const loadCredentials = async () => { - credentialsLoading.value = true; + if (!supported) return + credentialsLoading.value = true try { - const res = await http.get('/api/security/webauthn/credentials'); - if (res.errorNo !== 0) throw new Error(res.errorMsg || '加载安全密钥失败'); - credentials.value = Array.isArray(res.data) ? res.data : []; + const res = await http.get('/api/security/webauthn/credentials') + if (res.errorNo !== 0) throw new Error(res.errorMsg || '加载安全密钥失败') + credentials.value = Array.isArray(res.data) ? res.data : [] } catch (error) { - notify(error?.message || '加载安全密钥失败'); + notify(error?.message || '加载安全密钥失败') } finally { - credentialsLoading.value = false; + credentialsLoading.value = false } } - + + const loadSecurityData = async () => { + securityLoading.value = true + try { + const requests = [ + http.get('/api/security/credentials/question'), + http.get('/api/security/external-email/list'), + ] + if (!isSuperAdmin.value) { + requests.push(http.get('/api/security/credentials/recovery-codes')) + } + const [question, external, recovery] = await Promise.all(requests) + if (question.errorNo === 0 && question.data) { + securityQuestion.configured = Boolean(question.data.configured) + securityQuestion.question = question.data.question || '' + questionForm.question = question.data.question || '' + } + if (recovery && recovery.errorNo === 0) recoveryConfigured.value = Boolean(recovery.data?.configured) + if (external.errorNo === 0) externalEmails.value = Array.isArray(external.data) ? external.data : [] + } catch (error) { + notify(error?.message || '读取账户安全设置失败') + } finally { + securityLoading.value = false + } + } + const registerCredential = async () => { - if (!supported || registering.value) return; - registering.value = true; + if (!supported || registering.value) return + registering.value = true try { const prompt = await ElMessageBox.prompt('请为新安全密钥设置一个名称', '注册安全密钥', { confirmButtonText: '确定', cancelButtonText: '取消', inputPlaceholder: '例如:工作电脑', inputValidator: value => String(value || '').trim().length > 0 || '请输入密钥名称', - }); - const displayName = String(prompt.value).trim(); - const begin = await http.post('/api/security/webauthn/registration/begin', {}); - if (begin.errorNo !== 0) throw new Error(begin.errorMsg || '无法开始安全密钥注册'); - const credential = await navigator.credentials.create({publicKey: normalizeCreationOptions(begin.data.options)}); + }) + const begin = await http.post('/api/security/webauthn/registration/begin', {}) + if (begin.errorNo !== 0) throw new Error(begin.errorMsg || '无法开始安全密钥注册') + const credential = await navigator.credentials.create({ publicKey: normalizeCreationOptions(begin.data.options) }) const finish = await http.post('/api/security/webauthn/registration/finish', { session_id: begin.data.session_id, - display_name: displayName, + display_name: String(prompt.value).trim(), credential: serializeCredential(credential), - }); - if (finish.errorNo !== 0) throw new Error(finish.errorMsg || '安全密钥注册失败'); - notify('安全密钥注册成功', 'success'); - await loadCredentials(); + }) + if (finish.errorNo !== 0) throw new Error(finish.errorMsg || '安全密钥注册失败') + notify('安全密钥注册成功', 'success') + await loadCredentials() } catch (error) { - if (error !== 'cancel' && error !== 'close' && error?.name !== 'NotAllowedError') { - notify(error?.message || '安全密钥注册失败'); - } + if (error !== 'cancel' && error !== 'close' && error?.name !== 'NotAllowedError') notify(error?.message || '安全密钥注册失败') } finally { - registering.value = false; + registering.value = false } } - + const renameCredential = async item => { try { const prompt = await ElMessageBox.prompt('请输入新的密钥名称', '重命名', { confirmButtonText: '确定', cancelButtonText: '取消', inputValue: item.display_name, inputValidator: value => String(value || '').trim().length > 0 || '请输入密钥名称', - }); - const res = await http.post('/api/security/webauthn/credentials/rename', { - id: item.id, display_name: String(prompt.value).trim(), - }); - if (res.errorNo !== 0) throw new Error(res.errorMsg || '密钥重命名失败'); - notify('密钥重命名成功', 'success'); - await loadCredentials(); + }) + const res = await http.post('/api/security/webauthn/credentials/rename', { id: item.id, display_name: String(prompt.value).trim() }) + if (res.errorNo !== 0) throw new Error(res.errorMsg || '密钥重命名失败') + notify('密钥重命名成功', 'success') + await loadCredentials() } catch (error) { - if (error !== 'cancel' && error !== 'close') notify(error?.message || '密钥重命名失败'); + if (error !== 'cancel' && error !== 'close') notify(error?.message || '密钥重命名失败') } } - + const revokeCredential = async item => { try { await ElMessageBox.confirm(`确定要撤销密钥“${item.display_name}”吗?撤销后将不能用于登录`, '撤销安全密钥', { confirmButtonText: '确定撤销', cancelButtonText: '取消', type: 'warning', - }); - const res = await http.post('/api/security/webauthn/credentials/revoke', {id: item.id}); - if (res.errorNo !== 0) throw new Error(res.errorMsg || '撤销安全密钥失败'); - notify('安全密钥已撤销', 'success'); - await loadCredentials(); + }) + const res = await http.post('/api/security/webauthn/credentials/revoke', { id: item.id }) + if (res.errorNo !== 0) throw new Error(res.errorMsg || '撤销安全密钥失败') + notify('安全密钥已撤销', 'success') + await loadCredentials() } catch (error) { - if (error !== 'cancel' && error !== 'close') notify(error?.message || '撤销安全密钥失败'); + if (error !== 'cancel' && error !== 'close') notify(error?.message || '撤销安全密钥失败') } } - - const formatTime = value => value ? new Date(value).toLocaleString('zh-CN', {hour12: false}) : '-'; - - const logout = () => http.post('/api/logout', {}).then(() => location.reload()); - - const submit = () => { - if (!ruleForm.current_pwd || !ruleForm.new_pwd) return; + + const saveSecurityQuestion = async () => { + if (!questionForm.question.trim() || !questionForm.answer.trim()) { + notify('请填写密保问题和答案') + return + } + const res = await http.post('/api/security/credentials/question', questionForm) + if (res.errorNo !== 0) { + notify(res.errorMsg || '密保问题设置失败') + return + } + securityQuestion.configured = true + securityQuestion.question = questionForm.question.trim() + questionForm.answer = '' + notify('密保问题已保存', 'success') + } + + const generateRecoveryCodes = async () => { + try { + await ElMessageBox.confirm('生成新恢复码会撤销当前仍有效的恢复码,请确认已准备好安全保存。', '生成离线恢复码', { type: 'warning' }) + const res = await http.post('/api/security/credentials/recovery-codes/generate', { count: 10 }) + if (res.errorNo !== 0 || !Array.isArray(res.data?.codes)) throw new Error(res.errorMsg || '离线恢复码生成失败') + generatedCodes.value = res.data.codes + recoveryConfigured.value = true + notify('恢复码已生成,请仅保存这一次显示的内容', 'success') + } catch (error) { + if (error !== 'cancel' && error !== 'close') notify(error?.message || '离线恢复码生成失败') + } + } + + const revokeRecoveryCodes = async () => { + try { + await ElMessageBox.confirm('撤销后现有离线恢复码将立即失效,是否继续?', '撤销离线恢复码', { type: 'warning' }) + const res = await http.post('/api/security/credentials/recovery-codes/revoke', {}) + if (res.errorNo !== 0) throw new Error(res.errorMsg || '撤销恢复码失败') + recoveryConfigured.value = false + generatedCodes.value = [] + notify('离线恢复码已撤销', 'success') + } catch (error) { + if (error !== 'cancel' && error !== 'close') notify(error?.message || '撤销恢复码失败') + } + } + + const bindExternalEmail = async () => { + if (!bindForm.email.trim()) { + notify('请输入外部安全邮箱') + return + } + externalLoading.value = true + try { + const res = await http.post('/api/security/external-email/bind', { email: bindForm.email.trim(), type: bindForm.type }) + if (res.errorNo !== 0) throw new Error(res.errorMsg || '外部邮箱绑定失败') + bindForm.challengeId = res.data.challenge_id + bindForm.bindingId = res.data.id + const prompt = await ElMessageBox.prompt(`验证码已发送到 ${res.data.email},请输入验证码`, '验证外部邮箱', { + confirmButtonText: '验证', cancelButtonText: '取消', inputPlaceholder: '请输入验证码', + }) + bindForm.code = String(prompt.value).trim() + const verified = await http.post('/api/security/external-email/verify', { + id: bindForm.challengeId, binding_id: bindForm.bindingId, email: bindForm.email.trim(), code: bindForm.code, + }) + if (verified.errorNo !== 0) throw new Error(verified.errorMsg || '外部邮箱验证失败') + bindForm.email = '' + bindForm.challengeId = '' + bindForm.bindingId = 0 + await loadSecurityData() + notify('外部安全邮箱绑定成功', 'success') + } catch (error) { + if (error !== 'cancel' && error !== 'close') notify(error?.message || '外部邮箱绑定失败') + } finally { + externalLoading.value = false + } + } + + const disableExternalEmail = async item => { + try { + await ElMessageBox.confirm(`确定停用 ${item.email} 吗?停用后不能用于登录验证和恢复。`, '停用外部邮箱', { type: 'warning' }) + const res = await http.post('/api/security/external-email/disable', { id: item.id }) + if (res.errorNo !== 0) throw new Error(res.errorMsg || '外部邮箱停用失败') + await loadSecurityData() + notify('外部邮箱已停用', 'success') + } catch (error) { + if (error !== 'cancel' && error !== 'close') notify(error?.message || '外部邮箱停用失败') + } + } + + const formatTime = value => value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '-' + const logout = () => http.post('/api/logout', {}).then(() => location.reload()) + + const submit = async () => { + if (!ruleForm.current_pwd || !ruleForm.new_pwd) return if (ruleForm.new_pwd !== ruleForm.new_pwd2) { - notify(lang.err_pwd_diff); - return; + notify(lang.err_pwd_diff) + return } - http.post('/api/settings/modify_password', { - current_password: ruleForm.current_pwd, - password: ruleForm.new_pwd, - }).then(res => { - notify(res.errorNo === 0 ? res.data : res.errorMsg, res.errorNo === 0 ? 'success' : 'error'); - if (res.errorNo === 0) Object.assign(ruleForm, {current_pwd: '', new_pwd: '', new_pwd2: ''}); - }); + const res = await http.post('/api/settings/modify_password', { current_password: ruleForm.current_pwd, password: ruleForm.new_pwd }) + notify(res.errorNo === 0 ? '密码修改成功' : res.errorMsg, res.errorNo === 0 ? 'success' : 'error') + if (res.errorNo === 0) Object.assign(ruleForm, { current_pwd: '', new_pwd: '', new_pwd2: '' }) } - - onMounted(loadCredentials); + + onMounted(async () => { + await Promise.all([loadSecurityData(), loadCredentials()]) + }) return { - onMounted, - reactive, - ref, - ElMessageBox, - ElNotification, - lang, - http, - normalizeCreationOptions, - serializeCredential, - webAuthnSupported, - supported, - registering, - credentialsLoading, - credentials, - ruleForm, - rules, - notify, - loadCredentials, - registerCredential, - renameCredential, - revokeCredential, - formatTime, - logout, - submit + lang, isSuperAdmin, supported, registering, credentialsLoading, credentials, securityLoading, + securityQuestion, questionForm, recoveryConfigured, generatedCodes, externalEmails, externalLoading, + bindForm, ruleForm, rules, submit, registerCredential, renameCredential, revokeCredential, + saveSecurityQuestion, generateRecoveryCodes, revokeRecoveryCodes, bindExternalEmail, + disableExternalEmail, formatTime, logout, } } diff --git a/fe/src/views/components/SecuritySettings/SecuritySettings.vue b/fe/src/views/components/SecuritySettings/SecuritySettings.vue index dfc90282..4a6cdedb 100644 --- a/fe/src/views/components/SecuritySettings/SecuritySettings.vue +++ b/fe/src/views/components/SecuritySettings/SecuritySettings.vue @@ -1,74 +1,75 @@ -