Merge main safeguards and verify startup resource improvements

This commit is contained in:
abaishu0730 committed 2026-10-28 15:44:44 +08:00
commit 95dd4dc8fd
19 files changed
+194 -33

No files matched your search

+13 -16
View File
@@ -2,7 +2,7 @@
面向团队的 BPM 订单工作台,提供业务日历、异常待办与转交、连接管理和运行监管配置;保留 Chrome 已登录订单页导出本地 PDF 的能力。 面向团队的 BPM 订单工作台,提供业务日历、异常待办与转交、连接管理和运行监管配置;保留 Chrome 已登录订单页导出本地 PDF 的能力。
**订单通知流程**:以 Excel 的15类为准,从真实 BPM 待办按流程、版本和节点识别订单,导出并校验归档文件,按北京时间每天两个有效时段同类别汇总一封。收件人由分类规则维护,BPM 节点人工办理,惠州额外通知条件待确认。自动发信保持暂停,类别字段、目录、邮箱与预览须现场核验后才可启用。旧通用通知写入和调度已退役,历史记录保留查询。当前要求见[设计要求](docs/design-requirements.md)。 **订单通知流程**:以 Excel 的15类为准,从真实 BPM 待办按流程和节点精确匹配订单,再按表单版本适配字段,导出并校验归档文件,按北京时间每天两个有效时段同类别汇总一封。收件人由分类规则维护,BPM 节点人工办理,惠州额外通知条件待确认。自动发信保持暂停,类别字段、目录、邮箱与预览须现场核验后才可启用。旧通用通知写入和调度已退役,历史记录保留查询。当前要求见[设计要求](docs/design-requirements.md)。
## 设计与部署入口 ## 设计与部署入口
@@ -18,7 +18,7 @@
## Web 看板 ## Web 看板
侧栏七项:工作总览、订单通知管理、订单与导出记录、异常待办、ZCode 助手、业务设置、系统设置。订单通知管理集中通知总览、订单执行、通知订单、待发批次、发送记录,以及发送计划/日历/模板/发送设置。业务设置维护分类通知规则与字段映射,系统设置维护服务连接、健康、账号及审计。顶部直接接入 Tabler 1.6.1 圆角分段横栏,支持手机滚动和旧地址;团队账号仅管理员可见,个人改密保留右上角。 侧栏七项:业务首页、订单中心、邮件批次、工具、异常待办、业务设置、系统设置。工具中包含流程到达记录、PDF 导出记录和 DSH 助手;系统设置维护服务连接、邮箱、助手权限、健康和审计。首页展示实际发送窗口、批次与异常,支持窄屏与减少动态效果。
1. 启动工具后,在部署机打开 http://127.0.0.1:18766 ,自行创建管理员账号(至少 12 位密码)。没有默认账号或默认密码。 1. 启动工具后,在部署机打开 http://127.0.0.1:18766 ,自行创建管理员账号(至少 12 位密码)。没有默认账号或默认密码。
2. 管理员在“团队账号”中创建同事账号;同事使用启动窗口打印的局域网地址访问。默认监听 0.0.0.0:18766,能否跨机器访问取决于路由和 Windows 防火墙;本工具不自动修改防火墙。 2. 管理员在“团队账号”中创建同事账号;同事使用启动窗口打印的局域网地址访问。默认监听 0.0.0.0:18766,能否跨机器访问取决于路由和 Windows 防火墙;本工具不自动修改防火墙。
@@ -35,16 +35,16 @@
## 邮箱与邮件模板 ## 邮箱与邮件模板
1. 管理员进入 **邮箱管理 → 添加邮箱**,填写邮箱地址、SMTP / IMAP 服务器、端口、加密方式、登录账号和密码或授权码。支持 SSL/TLS 和必须升级加密的 STARTTLS,证书正常校验;不会猜测公司服务器参数。新邮箱默认暂停收信。 1. 管理员进入 **邮箱管理 → 添加邮箱**,默认使用一份邮箱地址与授权码。163/126/QQ 等有服务器预设;自定义服务器和独立收发凭据位于高级设置。SMTP 用于发信,IMAP 收信/历史查询可选;模板自动收信另有开关。
2. 填写 **允许提交模板的发件人**,保存后点击 **检查连接**。此操作验证 SMTP、IMAP 及 INBOX 访问,不发送邮件。确认正常后在管理邮箱中开启 **模板收信**,服务每分钟检查;也可点击 **立即收信**。 2. 填写 **允许提交模板的发件人**,保存后点击 **检查连接**。此操作验证 SMTP、IMAP 及 INBOX 访问,不发送邮件。确认正常后在管理邮箱中开启 **模板收信**,服务每分钟检查;也可点击 **立即收信**。
3. 从名单内的邮箱新建邮件发送到托管邮箱,主题为 `[模板][海外运营]订单通知 {{日期}}`;正文和附件作为对应产品线模板。`[模板]订单通知` 表示默认模板。回复/转发主题、范围标记不完整、未授权发件人和超出 10 MB 的邮件不导入。首次及邮箱 UID 变化只处理近 7 天邮件,保留该日期边界和 UID 游标;只读访问,不标记已读、不移动或删除邮件。 3. 从名单内的邮箱新建邮件发送到托管邮箱,主题为 `[模板][海外运营]订单通知 {{日期}}`;正文和附件作为对应产品线模板。`[模板]订单通知` 表示默认模板。回复/转发主题、范围标记不完整、未授权发件人和超出 10 MB 的邮件不导入。首次及邮箱 UID 变化只处理近 7 天邮件,保留该日期边界和 UID 游标;只读访问,不标记已读、不移动或删除邮件。
4. 打开 **模板与收件群组 → 预览并确认**,核对来源、发信标题、产品线、表格、图片和附件后点击 **确认生效**。可调整标题和产品线,或切换为纯文本编辑正文。旧版本留作历史;多人确认发生冲突时不覆盖新版本。名单控制导入,管理员确认后才生效。 4. 打开 **模板与收件群组 → 预览并确认**,核对来源、发信标题、产品线、表格、图片和附件后点击 **确认生效**。可调整标题和产品线,或切换为纯文本编辑正文。旧版本留作历史;多人确认发生冲突时不覆盖新版本。名单控制导入,管理员确认后才生效。
5. 支持明确变量 `{{产品线}}`、`{{订单号}}`、`{{日期}}`、`{{订单列表}}`,不执行模板表达式。HTML 预览隔离,阻断脚本及外链图片;保留原 EML,管理员可下载原邮件与附件。邮件中的 To/Cc 不会修改业务收件群组。 5. 支持明确变量 `{{产品线}}`、`{{订单号}}`、`{{日期}}`、`{{订单列表}}`,不执行模板表达式。HTML 预览隔离,阻断脚本及外链图片;保留原 EML,管理员可下载原邮件与附件。邮件中的 To/Cc 不会修改业务收件群组。
6. 已生效模板可点击 **发送测试到本邮箱** 并确认目标。使用真实 SMTP 发送到托管邮箱自身,先记录发送任务,不自动重试不确定结果。此操作不会发给产品线群组。业务通知另在“业务通知”中配置来源映射,正文直接使用来源简要说明,不使用模板附件。 6. 已生效模板可点击 **发送测试到隔离邮箱**,固定发送至 `2639266652@qq.com`,空 Cc、无附件。发送前和 SMTP 验证后复查测试期限与模板版本;结果不明禁止重复发送。分类业务通知使用规则绑定模板,PDF 仅归档,不作为附件。
旧模板草稿首次启动迁为待确认版本,确认时选择实际托管邮箱。邮箱维护须从部署机回环地址或已配置的 HTTPS 反向代理访问;与 BPM 登录使用同一传输要求。密码留空保留原值,更换邮箱、登录账号或服务器时须重新录入。后台持续检查不要求一直打开网页。 旧模板草稿首次启动迁为待确认版本,确认时选择实际托管邮箱。邮箱维护须从部署机回环地址或已配置的 HTTPS 反向代理访问;与 BPM 登录使用同一传输要求。密码留空保留原值,更换邮箱、登录账号或服务器时须重新录入。后台持续检查不要求一直打开网页。
复用 [Nodemailer](https://nodemailer.com/) 10.1.1、[ImapFlow](https://imapflow.com/) 2.4.3、[MailParser](https://nodemailer.com/extras/mailparser/) 3.9.39 和 [sanitize-html](https://github.com/apostrophecms/sanitize-html) 2.18.1,版本已锁定。公司邮箱真实连接需管理员录入参数后检查。 复用 [Nodemailer](https://nodemailer.com/) 10.2.1、[ImapFlow](https://imapflow.com/) 2.4.3、[MailParser](https://nodemailer.com/extras/mailparser/) 3.12.4 和 [sanitize-html](https://github.com/apostrophecms/sanitize-html) 2.18.1,版本已锁定。公司邮箱真实连接需管理员录入参数后检查。
## 存储服务器与业务通知 ## 存储服务器与业务通知
@@ -84,19 +84,16 @@
守护控制、事件和安装记录保存在本机 `supervisor/supervisor.sqlite`;当前用户 ACL 保护 `control.key` 与日志,管理令牌不发送到 HTTP,业务心跳每次启动使用独立随机令牌。`supervisor/service.log` 达 5 MiB 时轮转,保留 3 份历史。停服备份整个本机状态目录,勿将控制密钥或运行状态提交到 Git。实现与验证见 [服务守护设计](docs/superpowers/specs/2026-10-18-service-health-design.md)。 守护控制、事件和安装记录保存在本机 `supervisor/supervisor.sqlite`;当前用户 ACL 保护 `control.key` 与日志,管理令牌不发送到 HTTP,业务心跳每次启动使用独立随机令牌。`supervisor/service.log` 达 5 MiB 时轮转,保留 3 份历史。停服备份整个本机状态目录,勿将控制密钥或运行状态提交到 Git。实现与验证见 [服务守护设计](docs/superpowers/specs/2026-10-18-service-health-design.md)。
## ZCode 对话助手 ## DSH 受控助手
工作台左侧 **ZCode 助手** 提供个人会话、连续追问、诊断依据、停止回复与操作结果。交互参考 [Open WebUI](https://github.com/open-webui/open-webui),界面在本项目内实现,共用工作台账号。 在 **工具 → DSH 助手** 查询授权范围内的订单、批次和运行状态。管理员在 **系统设置 → 助手设置** 配置模型。
1. 本机已安装并校验官方 [ZCode v3.14.3](https://github.com/zai-org/ZCode/releases/tag/v3.14.3) 运行包,其附带 CLI 的实际版本为 **0.16.9**。换机时安装 7-Zip,运行 `node scripts/setup-zcode.cjs`:从官方 release 获取固定安装包、核对 SHA-256 后解包,不执行桌面安装程序。运行包存于 `%LOCALAPPDATA%\OrderNotificationAutomation\zcode-runtime`,服务启动时核对清单及 CLI 文件摘要并自动识别。 1. 运行 `node scripts/install-dsh-runtime.cjs` 安装固定官方 DeepSeek Harness 运行包;`--check` 仅检查。运行包独立安装在 LocalAppData,项目依赖不变。
2. 管理员在 **ZCode 接入设置** 填写供应商的 OpenAI 兼容 API 根地址(例如含 `/v1` 的地址)、模型名和密钥,再启用并保存。仅本机或可信 HTTPS 可维护。密钥加密保存、不回传;留空保留,更换地址或模型须重新填写。**检查运行包** 仅验证本地入口,真实模型认证在发送对话时验证。 2. 使用 Messages 兼容 API 根地址(官方默认 `https://api.deepseek.com/anthropic`)、实际模型名称和密钥。密钥加密保存、不回传;未配置密钥时助手停用。检查运行包不代表真实模型认证成功。
3. 默认只诊断。可单独开放固定操作卡片:检查启用的存储连接(管理员)、扫描授权 BPM 连接、重试失败归档。模型不能直接执行,必须由用户点击,服务器再次校验权限与目标,记录单次执行结果。暂停助手后旧卡片同样不可执行。 3. 固定操作卡片按工作台权限执行,用户点击后重新核验目标。管理员可另行开放代码修复:明确选择已跟踪文件,先审查建议,再在独立 Git 工作区运行固定测试。通过后待人工审查,失败恢复基线并保留提交;结果不明停止并待核验,不自动合并或部署。
4. AI 操作记录只追加保存步骤、提交、测试与恢复结果,支持按账号查询历史。原生文件、Shell、网络、MCP 工具不注册;代码验证以本机服务身份运行,Git 工作区不等同操作系统沙箱。
助手仅发送允许范围内的运行状态与异常摘要,不读取凭据、完整 BPM 表单、邮件正文或服务器文件内容。固定 CLI 的原生工具全部禁用,插件、MCP、技能、子代理、记忆和 hooks 关闭;每轮使用独立临时配置及过滤环境。模型输出只接受规定 JSON,不能执行任意命令、URL、路径,不审批、不发邮件、不改配置。限制属于已核对版本的应用控制,不是操作系统沙箱。 已用官方 DSH + 本地假模型验证协议与空工具列表,真实模型密钥尚未配置。来源、设计与边界见 [受控助手设计](docs/superpowers/specs/2026-10-27-mail-dsh-controlled-optimization-design.md)。
消息与模型配置加密保存在本机 `assistant/assistant.sqlite`。个人会话互相隔离,每会话最多 100 轮、每用户最多 50 个会话;全服务最多 2 个同时回复,支持 15–180 秒超时和每日轮次上限。上限统计对话轮次,运行包自身可能在一轮内重试模型请求。重启会标记未完成任务为中断,不自动重复执行。
当前已用**官方 CLI + 本机测试模型接口** 验证对话协议、模型参数和禁用工具;尚未配置或验证真实供应商模型认证。没有后台自主监管循环。来源、版本与限制见 [接入记录](docs/zcode-integration-2026-10-18.md)。
## BPM 登录 ## BPM 登录
@@ -152,7 +149,7 @@ Chrome 加载扩展只需做一次。修改扩展源码、重新配对或变更
- 本地程序使用隔离的无界面 Chrome 排版,禁用页面脚本和网络;保存后关闭该排版进程,不影响你正在使用的 Chrome。 - 本地程序使用隔离的无界面 Chrome 排版,禁用页面脚本和网络;保存后关闭该排版进程,不影响你正在使用的 Chrome。
- 不导出密码、隐藏控件、ViewState、讨论输入和操作按钮,不提交或修改 BPM 订单。 - 不导出密码、隐藏控件、ViewState、讨论输入和操作按钮,不提交或修改 BPM 订单。
- **输出是页面导出样稿,不是服务器原版 PDF,也不保证与 XForm 原生打印完全一致。** 不支持的图片、资源读取失败会在扩展中提示。网页内的附件只显示名称,不会自动合并附件。 - **输出是页面导出样稿,不是服务器原版 PDF,也不保证与 XForm 原生打印完全一致。** 不支持的图片、资源读取失败会在扩展中提示。网页内的附件只显示名称,不会自动合并附件。
- 本版包含 PDF 导出、团队协作、BPM 托管、SMTP / IMAP 邮箱与模板审核及明确操作的测试发信。支持 SMB 服务器配置、PDF 归档、通用通知队列与受控 ZCode 对话;BPM 业务匹配与简要说明自动入队、后台自主监管仍待接入;不会自动处理知会或修改 BPM 审批。 - 本版包含按规则匹配、只读采集、PDF/SMB归档、分类模板与计划批次、确认未发送订单顺延、受控DSH助手和业务台账。历史表单及隔离回放通过不等于十五类真实通知与实收全部验收完成;正式服务机部署另行安排。
## 故障处理 ## 故障处理
+17
View File
@@ -1,5 +1,20 @@
# 开发交接(2026-10-23) # 开发交接(2026-10-23)
## 2026-10-28 路由按需加载与 Windows 启动资源优化
- 在 `codex/system-update` 延续前轮性能改动,首页按路由加载可选脚本。清单由服务端计算实际内容指纹,延迟资源保留长期缓存与 SRI;并行预加载、按各路由顺序执行,旧慢页面不阻塞未加载的新页面,失败可重试或重新加载。18 个页面入口、冷切换、完整性拒绝与重试均有浏览器覆盖。
- 与 `73773f9` 同一隔离 HTTP/合成首页比较、各 3 次中位:冷静态请求 44→13,压缩正文 299130→169652 B,首页就绪约 590→399 ms;重复刷新仍为 0 个静态网络请求。含 3000 个合成文件的跨进程 ACL 检查中位约 1142→587 ms;不是生产 SLA。
- Windows ACL 先检查原始 DACL 与 SID 规则,完全符合原有私有目录策略才复用,任何额外对象/回调/不透明 ACE 均不复用;真实目录验证不重写合规 ACL,并能修复放宽后的策略。DPAPI、路径身份核验和原超时保护保持。监督器连续三次未通过首次健康检查即退出时冷却,持久化安全启动诊断;成功健康检查或人工重试重置连续计数。
- 原目标 `codex/smb-storage` 已合入 `main` 并删除,旧请求 #2 已关闭;本轮纳入 `main` 的邮件期限/隔离发送、修复验证器和监督器异常退出清理修复,合并保留两边全部 70 个测试入口。新请求目标为 `main`,不操作 `dsh`。
- 最终 `npm test` 429/429 通过,0 失败、0 跳过,未再出现保护超时日志。集成安全与服务专项 20/20 通过;早期因 Windows 初始化超时失败的业务切片重跑 12/12 通过,保留原始失败日志。独立审查提出的三项 P2 均补回归并复核,提交内容/依赖/语法/差异检查通过;未运行历史 `test:full`。
- 未部署运行服务,未发送真实邮件、办理 BPM 或改动运行配置。实现、基准和限制见 [启动稳定性与首屏加载](startup-stability-2026-10-28.md),原始聚合收据留在忽略目录 `output/lazy-startup-20261028/`。未声称消除所有 Windows 超时或证明完整服务启动已经加速。
## 2026-10-27 PR #1 合并前审查修复
- 修复旧模板测试邮件旁路:固定隔离QQ、空Cc、无附件,发送前/SMTP验证后复查测试期限与模板版本;未知测试结果禁止重复。样例发送同样接入期限,UI文案与真实信封一致。
- 修复AI验证器关联共享Git目录时的dubious ownership;只为当前验证工作区设置命令级精确信任,不改变全局配置。新增真正执行固定与变更测试的回归。
- Windows守护异常退出的孤儿进程疑点被隔离实测排除,新增PID退出/定时任务停止/端口释放回归;无需修改生产守护行为。
- 审查范围、已修复问题和投产限制见docs/pr-1-review-2026-10-27.md。修复前业务292项、修复后针对性25项通过;最终候选测试单独记录。未手动发信或操作BPM,不更新正式服务机。
## 2026-10-28 缓存刷新收尾与按需区域校验 ## 2026-10-28 缓存刷新收尾与按需区域校验
- 接续 `codex/system-update` 上一轮中断前的静态指纹缓存、后端 revision 与前端区域刷新改动。新增 `GET /api/refresh/revisions?regions=assistant` 等按需校验,旧的无参数八区域响应兼容;校验区域白名单、重复/空参数,保持认证、账号隔离与 `no-store`。助手频繁轮询不再访问订单、BPM、存储或 PDF 台账等无关模块。 - 接续 `codex/system-update` 上一轮中断前的静态指纹缓存、后端 revision 与前端区域刷新改动。新增 `GET /api/refresh/revisions?regions=assistant` 等按需校验,旧的无参数八区域响应兼容;校验区域白名单、重复/空参数,保持认证、账号隔离与 `no-store`。助手频繁轮询不再访问订单、BPM、存储或 PDF 台账等无关模块。
@@ -311,3 +326,5 @@ node --test tests/bpm-vault.test.cjs
阅读顺序:[README](../README.md)、[当前设计要求](design-requirements.md)、[业务资料整理表](business-configuration.md),按任务查 [守护设计](superpowers/specs/2026-10-18-service-health-design.md)、[ZCode 接入记录](zcode-integration-2026-10-18.md)、[验证历史](verification.md)。早期阶段文档的“尚未实现”以最新基准及代码为准。 阅读顺序:[README](../README.md)、[当前设计要求](design-requirements.md)、[业务资料整理表](business-configuration.md),按任务查 [守护设计](superpowers/specs/2026-10-18-service-health-design.md)、[ZCode 接入记录](zcode-integration-2026-10-18.md)、[验证历史](verification.md)。早期阶段文档的“尚未实现”以最新基准及代码为准。
- 最终验证:当前业务回归173项、provider/采集恢复/版本兼容/期限保护专项60项通过;独立复核46项通过。新增缺字段/空明细/复制/汇总行回归均先复现失败再修复。 - 最终验证:当前业务回归173项、provider/采集恢复/版本兼容/期限保护专项60项通过;独立复核46项通过。新增缺字段/空明细/复制/汇总行回归均先复现失败再修复。
- 最终候选版本验证:301项业务测试全部通过,0失败/0跳过;修复专项25项通过,生产依赖审计0条已知漏洞。审查结论:两项确认问题已修复,可合并代码;正式投产验收边界不变。
+1 -1
View File
@@ -3,7 +3,7 @@
## 安装启动 ## 安装启动
1. 准备常驻 Windows 机器、Node.js 22.13+(建议 24)及 Chrome,确认可访问新版 BPM、SSO 和公司邮箱。 1. 准备常驻 Windows 机器、Node.js 22.13+(建议 24)及 Chrome,确认可访问新版 BPM、SSO 和公司邮箱。
2. 本轮更新源码位于本地工作区 `C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation`,分支 `codex/modular-refactor` 尚未推送;使用此工作区进入项目执行 `npm ci`。新克隆目前无法取得该分支;需使用仓库中已发布的分支,并按对应版本说明安装。后续若此分支已发布,才可在克隆后切换到它。后续开发见 [交接说明](HANDOFF.md)。 2. 从 `https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation.git` 获取源码,选择已审查的提交或发布版本,进入项目执行 `npm ci`。PR #1 合并后可使用 `main`;合并前审查分支为 `codex/smb-storage`。代码合并不自动更新正式服务机,上线前仍须按 [交接说明](HANDOFF.md) 完成业务验收。
3. 按需复制 `config.example.json` 为 `config.json`,调整监听端口、PDF 输出目录与代理设置。实际配置不提交 Git。 3. 按需复制 `config.example.json` 为 `config.json`,调整监听端口、PDF 输出目录与代理设置。实际配置不提交 Git。
4. 执行 `npm start` 或双击 `启动工具.cmd`。浏览器访问 `http://127.0.0.1:18766/`,首次自行创建管理员,无默认密码。 4. 执行 `npm start` 或双击 `启动工具.cmd`。浏览器访问 `http://127.0.0.1:18766/`,首次自行创建管理员,无默认密码。
5. 管理员创建团队账号,配置 BPM 连接及邮箱。账号密码在 Web 中录入,不写源码、命令行或文档。 5. 管理员创建团队账号,配置 BPM 连接及邮箱。账号密码在 Web 中录入,不写源码、命令行或文档。
+25
View File
@@ -0,0 +1,25 @@
# PR #1 合并前审查
审查基线:main 34770ed33897e856065c2f9b774e7b025b54c4e7,开发分支 dcea4a063f007006e1a4dd2208c700236689b0e4。用户授权审查后可直接合并。
## 审查范围与结论
独立审查邮件/订单状态机、DSH权限/隔离修复、服务生命周期/BPM/存储;主审核对HTTP入口、配置接线、历史证据、变更与测试。确认两项阻塞问题并修复:
1. 旧模板测试发信入口发往账户自身且带模板附件,绕过受限模式;发送测试现在固定隔离QQ、空Cc、无附件,发送前及SMTP验证后检查五天期限,模板版本变化阻断,sending/unknown回执禁止重复。样例邮件同时接入期限门槛;应用接线有专项测试。没有发送真实邮件。
2. AI代码修复验证器的Git命令未继承受控runner的精确safe.directory设置,关联共享仓库的本地worktree在运行测试前失败;现仅为该次命令信任真实工作目录,禁止hooks/外部diff/textconv,不持久化全局配置。真实临时Git工作区回归验证固定及新增测试均被执行。
疑点核验:Windows守护进程异常退出后的孤儿子进程未复现,PID-only终止与进程直接退出均终止业务子进程。保留Windows专属崩溃回归,验证调度停止、PID退出、端口释放;不外推为其他操作系统证明。
## 验证记录
- 修复前当前业务测试292项通过。
- 修复后邮件策略、旧邮件服务/HTTP/加密存储、应用启动关闭/期限接线、AI共享目录验证器、Windows守护崩溃专项25项通过。
- 最终候选版本业务测试结果见本轮交接与忽略output/business-flow-test/pr1-final-head-tests-20261027.log。
- 未重跑旧千项全量。旧web-closure-ui的5项失效断言/夹具已在先前mainline开发基线独立复现,仍有维护欠账,不把它们算通过。
## 合并不等于正式投产
代码可在上述修复与最终测试通过后合并。十五类真实通知节点及实际实收仍未全部覆盖,28流程历史表单/PDF及15类隔离回放不替代正式业务验收。DSH尚未配置真实模型密钥,只有官方本地假模型及隔离修复验证。正式服务机不随此次合并更新。保留BPM只读、PDF不作为附件、unknown不自动重发以及五天受限测试期限。
- 最终候选版本验证:301项业务测试全部通过,0失败/0跳过;修复专项25项通过,生产依赖审计0条已知漏洞。审查结论:两项确认问题已修复,可合并代码;正式投产验收边界不变。
+7 -1
View File
@@ -35,6 +35,12 @@
完整测试过程中定位到共享键目录已有约 2.2 万个文件,且已经具备正确的受保护 ACL。原逻辑在每个新进程中仍重设目录 ACL,可能重新传播到所有继承权限的子文件。现在先以 SID 读取并核验:DACL 受保护、所有者为当前用户、只有一条当前用户的显式 Allow FullControl 规则,且同时继承给文件和子目录、传播标志为 None;全部匹配才跳过重复写入。任何不一致仍按原策略重新保护,读失败仍报错,路径身份前后核验与 DPAPI 格式不变。 完整测试过程中定位到共享键目录已有约 2.2 万个文件,且已经具备正确的受保护 ACL。原逻辑在每个新进程中仍重设目录 ACL,可能重新传播到所有继承权限的子文件。现在先以 SID 读取并核验:DACL 受保护、所有者为当前用户、只有一条当前用户的显式 Allow FullControl 规则,且同时继承给文件和子目录、传播标志为 None;全部匹配才跳过重复写入。任何不一致仍按原策略重新保护,读失败仍报错,路径身份前后核验与 DPAPI 格式不变。
真实 Windows/.NET ACL 测试覆盖正确策略、未保护、其他所有者、权限不足、缺少继承、仅继承、Deny、其他用户及额外规则;使用真实目录 ctime 确认合规检查没有重写权限,另验证被取消保护后会修复。最初因初始化超时失败的 Excel 执行业务切片与该策略测试重跑 12/12 通过,未跳过原断言。 先读取原始二进制安全描述符,要求 DACL 中恰有一个普通非回调的 AccessAllowed ACE,且无不透明数据,再检查托管规则字段,避免 `GetAccessRules()` 隐藏额外对象 ACE。真实 Windows/.NET ACL 测试覆盖正确策略、未保护、其他所有者、权限不足、缺少继承、仅继承、Deny、其他用户、额外规则及隐藏对象 ACE;使用真实目录 ctime 确认合规检查没有重写权限,另验证取消保护或插入额外对象 ACE 后会修复。最初因初始化超时失败的 Excel 执行业务切片与该策略测试重跑 12/12 通过,未跳过原断言。
在含 3000 个合成文件的临时目录中,交替执行每项 3 次、取含 PowerShell 启动的跨进程中位耗时:原强制重写 1142 ms,核验后复用 587 ms。临时目录均已删除,原始聚合数据见忽略的 `output/lazy-startup-20261028/acl-benchmark.json`。这证明减少了一类重复权限写入;没有声称已经消除所有 Windows 超时,也未测量真实服务完整启动耗时。 在含 3000 个合成文件的临时目录中,交替执行每项 3 次、取含 PowerShell 启动的跨进程中位耗时:原强制重写 1142 ms,核验后复用 587 ms。临时目录均已删除,原始聚合数据见忽略的 `output/lazy-startup-20261028/acl-benchmark.json`。这证明减少了一类重复权限写入;没有声称已经消除所有 Windows 超时,也未测量真实服务完整启动耗时。
## 最终集成验证
原草稿请求 #2 的目标分支已合入 `main` 并删除,本轮合并 `main` 修复并保留两边全部 70 个测试入口。邮件期限与隔离发送、固定修复验证器以及 Windows 监督器异常退出清理均保留。最终 `npm test` 为 429/429 通过、0 失败、0 跳过,未再出现保护超时日志;集成原生 ACL/存储诊断/邮件策略/修复验证器/服务监督专项 20/20 通过。
最初完整测试的 Windows ACL 初始化超时与失败原始日志保留,不作为最终通过依据。独立复核提出的文档级脚本执行队列阻塞、部署后延迟脚本完整性及隐藏对象 ACE 三项 P2 均已补失败回归并修复复核。语法、依赖、差异和提交内容检查通过,本轮未运行历史 `test:full`。源码和测试在最终回归期间保持不变,未部署真实服务或修改运行配置。
+1 -1
View File
@@ -13,7 +13,7 @@
"service:stop": "node scripts/service.cjs stop", "service:stop": "node scripts/service.cjs stop",
"service:restart": "node scripts/service.cjs restart", "service:restart": "node scripts/service.cjs restart",
"test": "npm run test:business", "test": "npm run test:business",
"test:business": "node --test --test-concurrency=1 tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs tests/app/region-revisions.test.cjs tests/app/region-revisions-http.test.cjs tests/app/region-refresh.test.cjs tests/app/region-refresh-ui.test.cjs tests/app/region-selection.test.cjs tests/app/module-loader.test.cjs tests/app/module-loader-ui.test.cjs tests/service/service-supervisor.test.cjs tests/bpm/windows-directory.test.cjs", "test:business": "node --test --test-concurrency=1 tests/service/supervisor-crash.test.cjs tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-validator.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/template-test-policy.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs tests/app/region-revisions.test.cjs tests/app/region-revisions-http.test.cjs tests/app/region-refresh.test.cjs tests/app/region-refresh-ui.test.cjs tests/app/region-selection.test.cjs tests/app/module-loader.test.cjs tests/app/module-loader-ui.test.cjs tests/service/service-supervisor.test.cjs tests/bpm/windows-directory.test.cjs",
"test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"" "test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\""
}, },
"engines": { "engines": {
+1 -1
View File
@@ -90,7 +90,7 @@ async function main(options = {}) {
cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>orderRules?.close(),()=>assistantStore?.close(),()=>assistantJournal?.close()); cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>orderRules?.close(),()=>assistantStore?.close(),()=>assistantJournal?.close());
bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions'),accessClient:new BpmAccessClient()}); bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions'),accessClient:new BpmAccessClient()});
custodian=new BpmCustodian({workspace,manager:bpmSessions}); custodian=new BpmCustodian({workspace,manager:bpmSessions});
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore}); mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore,beforeSend:()=>{if(!orderRules)throw Object.assign(Error('通知业务状态尚未就绪。'),{status:503});require('../modules/order-rules/stability-period.cjs').assertActive(orderRules);}});
mailStore.migrateLegacy(store.settings().templates); mailStore.migrateLegacy(store.settings().templates);
scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()}); scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()});
storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir}); storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir});
+5 -2
View File
@@ -4,5 +4,8 @@ const fs=require('node:fs'),path=require('node:path'),{spawnSync,execFileSync}=r
const root=path.resolve(__dirname,'../../..'),script=JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8')).scripts['test:business']; const root=path.resolve(__dirname,'../../..'),script=JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8')).scripts['test:business'];
if(!script.startsWith('node --test --test-concurrency=1 '))throw Error('Unexpected fixed business validation command'); if(!script.startsWith('node --test --test-concurrency=1 '))throw Error('Unexpected fixed business validation command');
const baseline=script.slice('node --test --test-concurrency=1 '.length).split(' ');if(baseline.some(f=>!/^tests\/[\w./-]+\.test\.cjs$/.test(f)))throw Error('Invalid fixed test manifest'); const baseline=script.slice('node --test --test-concurrency=1 '.length).split(' ');if(baseline.some(f=>!/^tests\/[\w./-]+\.test\.cjs$/.test(f)))throw Error('Invalid fixed test manifest');
const changed=execFileSync('git',['-c','core.fsmonitor=false','diff','--name-only','HEAD~1','HEAD'],{encoding:'utf8',windowsHide:true}).trim().split(/\r?\n/).filter(f=>/^tests\/[\w./-]+\.test\.cjs$/.test(f)); // The runner supplies this isolated checkout. Trust only its canonical path for
const run=spawnSync(process.execPath,['--test','--test-concurrency=1',...new Set([...baseline,...changed])],{cwd:process.cwd(),env:process.env,windowsHide:true,stdio:'inherit'});process.exitCode=run.status===0?0:1; // this command; linked worktrees may have Git metadata on a shared filesystem.
const cwd=fs.realpathSync.native(process.cwd()),normalized=cwd.replaceAll('\\','/'),safeDirectory=normalized.startsWith('//')?'%(prefix)/'+normalized:normalized;
const changed=execFileSync('git',['-c','safe.directory='+safeDirectory,'-c','core.hooksPath=/dev/null','-c','core.fsmonitor=false','diff','--no-ext-diff','--no-textconv','--name-only','HEAD~1','HEAD','--'],{cwd,encoding:'utf8',windowsHide:true}).trim().split(/\r?\n/).filter(f=>/^tests\/[\w./-]+\.test\.cjs$/.test(f));
const run=spawnSync(process.execPath,['--test','--test-concurrency=1',...new Set([...baseline,...changed])],{cwd,env:process.env,windowsHide:true,stdio:'inherit'});process.exitCode=run.status===0?0:1;
+22 -4
View File
@@ -3,17 +3,17 @@ const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');cons
const fail=(message,status=502)=>{throw Object.assign(new Error(message),{status});}; const fail=(message,status=502)=>{throw Object.assign(new Error(message),{status});};
const safeError=(error,kind)=>error?.code==='EAUTH'||error?.authenticationFailed?`${kind} 登录失败,请检查账号和授权密码。`:/CERT|TLS|SSL|SELF_SIGNED/.test(error?.code||'')?`${kind} 加密连接失败,请检查服务器地址和证书。`:`${kind} 连接失败,请检查服务器、端口和网络后重试。`; const safeError=(error,kind)=>error?.code==='EAUTH'||error?.authenticationFailed?`${kind} 登录失败,请检查账号和授权密码。`:/CERT|TLS|SSL|SELF_SIGNED/.test(error?.code||'')?`${kind} 加密连接失败,请检查服务器地址和证书。`:`${kind} 连接失败,请检查服务器、端口和网络后重试。`;
class MailService{ class MailService{
constructor({store,imapFactory,smtpFactory,interval=60000}){this.store=store;this.imapFactory=imapFactory||((c)=>new ImapFlow({host:c.host,port:c.port,secure:c.security==='tls',doSTARTTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,disableAutoIdle:true,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,maxLiteralSize:MAX_MAIL,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.smtpFactory=smtpFactory||((c)=>nodemailer.createTransport({host:c.host,port:c.port,secure:c.security==='tls',requireTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,debug:false,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,disableFileAccess:true,disableUrlAccess:true,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.interval=interval;this.running=new Map();this.clients=new Set();this.stopped=false;} constructor({store,imapFactory,smtpFactory,interval=60000,beforeSend=()=>{}}){this.store=store;this.beforeSend=beforeSend;this.imapFactory=imapFactory||((c)=>new ImapFlow({host:c.host,port:c.port,secure:c.security==='tls',doSTARTTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,disableAutoIdle:true,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,maxLiteralSize:MAX_MAIL,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.smtpFactory=smtpFactory||((c)=>nodemailer.createTransport({host:c.host,port:c.port,secure:c.security==='tls',requireTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,debug:false,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,disableFileAccess:true,disableUrlAccess:true,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.interval=interval;this.running=new Map();this.clients=new Set();this.stopped=false;}
busy(id){return this.running.has(id);} busy(id){return this.running.has(id);}
async exclusive(id,work){if(this.stopped)fail('邮件服务正在停止。',503);if(this.busy(id))fail('此邮箱正在执行操作,请稍后重试。',409);const promise=Promise.resolve().then(work);this.running.set(id,promise);return promise.finally(()=>this.running.delete(id));} async exclusive(id,work){if(this.stopped)fail('邮件服务正在停止。',503);if(this.busy(id))fail('此邮箱正在执行操作,请稍后重试。',409);const promise=Promise.resolve().then(work);this.running.set(id,promise);return promise.finally(()=>this.running.delete(id));}
sendSample(id,input){return this.exclusive(id,async()=>{ sendSample(id,input){return this.exclusive(id,async()=>{
if(!input||Object.keys(input).some(k=>!['idempotencyKey','subject','text'].includes(k))||typeof input.idempotencyKey!=='string'||!/^[\w-]{1,80}$/.test(input.idempotencyKey)||typeof input.subject!=='string'||!input.subject.trim()||input.subject.length>250||/[\x00-\x1f]/.test(input.subject)||typeof input.text!=='string'||!input.text.trim()||input.text.length>20000||input.text.includes('\0'))fail('样例测试内容无效。',400); if(!input||Object.keys(input).some(k=>!['idempotencyKey','subject','text'].includes(k))||typeof input.idempotencyKey!=='string'||!/^[\w-]{1,80}$/.test(input.idempotencyKey)||typeof input.subject!=='string'||!input.subject.trim()||input.subject.length>250||/[\x00-\x1f]/.test(input.subject)||typeof input.text!=='string'||!input.text.trim()||input.text.length>20000||input.text.includes('\0'))fail('样例测试内容无效。',400);
const marker='sample:'+require('node:crypto').createHash('sha256').update(id+'\0'+input.idempotencyKey).digest('hex'),previous=this.store.findSampleSend(id,marker); const marker='sample:'+require('node:crypto').createHash('sha256').update(id+'\0'+input.idempotencyKey).digest('hex'),previous=this.store.findSampleSend(id,marker);
if(previous){if(previous.status==='sent')return {id:previous.id,status:'sent',to:'2639266652@qq.com',reused:true};fail('此样例发送已有结果待核实,不会自动重发。',409);} if(previous){if(previous.status==='sent')return {id:previous.id,status:'sent',to:'2639266652@qq.com',reused:true};fail('此样例发送已有结果待核实,不会自动重发。',409);}
const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发信。',409); this.beforeSend();const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发信。',409);
const text='本邮件仅用于样例测试,不表示BPM已处理或PDF已归档。\n\n'+input.text,transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId; const text='本邮件仅用于样例测试,不表示BPM已处理或PDF已归档。\n\n'+input.text,transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;
try{ try{
await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,marker); await transport.verify();this.beforeSend();this.store.guard(id,c.version);sendId=this.store.beginSend(id,marker);
const result=await transport.sendMail({from:{address:c.email,name:c.name},to:['2639266652@qq.com'],cc:[],subject:'[样例测试] '+input.subject,text,html:'<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>',attachments:[],messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true}); const result=await transport.sendMail({from:{address:c.email,name:c.name},to:['2639266652@qq.com'],cc:[],subject:'[样例测试] '+input.subject,text,html:'<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>',attachments:[],messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
if(result?.rejected?.length||!result?.accepted?.some(a=>String(a.address||a).toLowerCase()==='2639266652@qq.com'))throw Error('Sample recipient not fully accepted'); if(result?.rejected?.length||!result?.accepted?.some(a=>String(a.address||a).toLowerCase()==='2639266652@qq.com'))throw Error('Sample recipient not fully accepted');
this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:'2639266652@qq.com',messageId:result.messageId}; this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:'2639266652@qq.com',messageId:result.messageId};
@@ -41,7 +41,25 @@ class MailService{
}finally{lock.release();}}); }finally{lock.release();}});
this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected}; this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected};
}catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});} }catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});}
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST','类别名称':'测试通知','订单明细':'订单号:TEST 机芯号:CORE 产品型号:MODEL 客户简称:示例 出货方式:CBU 总数量:1','存放地址':'示例归档目录(测试数据)'};const rendered=require('./content.cjs').appendSignature(renderTemplate(t,values),{...c.signature,channelId:c.id,version:c.version});const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});} sendTest(id,templateId){return this.exclusive(id,async()=>{
this.beforeSend();
const previous=this.store.findSampleSend(id,templateId);
if(previous&&['sending','unknown'].includes(previous.status))fail('此模板测试发送结果待核实,禁止重复发送。',409);
const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);
const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);
const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST','类别名称':'测试通知','订单明细':'订单号:TEST 机芯号:CORE 产品型号:MODEL 客户简称:示例 出货方式:CBU 总数量:1','存放地址':'示例归档目录(测试数据)'};
const rendered=require('./content.cjs').appendSignature(renderTemplate(t,values),{...c.signature,channelId:c.id,version:c.version});
const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;
try{
await transport.verify();this.beforeSend();this.store.guard(id,c.version);
const current=this.store.template(templateId);if(current.version!==t.version||current.status!=='active'||current.channelId!==id)fail('模板已变化,请刷新后重试。',409);
sendId=this.store.beginSend(id,t.id);
const result=await transport.sendMail({from:{address:c.email,name:c.name},to:['2639266652@qq.com'],cc:[],subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:[]});
if(result?.rejected?.length||!result?.accepted?.some(a=>String(a.address||a).toLowerCase()==='2639266652@qq.com'))throw new Error('Test recipient not fully accepted');
this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:'2639266652@qq.com'};
}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核实,请核对固定QQ收件箱,禁止重复发送。':safeError(e,'SMTP'));}
finally{transport.close?.();this.clients.delete(transport);}
});}
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.receiveEnabled!==false&&c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();} start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.receiveEnabled!==false&&c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);} async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);}
} }
@@ -3,6 +3,10 @@
const privateDirectoryAcl=String.raw` const privateDirectoryAcl=String.raw`
function Test-PrivateDirectoryAcl($acl,$sid) { function Test-PrivateDirectoryAcl($acl,$sid) {
if(-not $acl.AreAccessRulesProtected -or -not $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Equals($sid)){return $false} if(-not $acl.AreAccessRulesProtected -or -not $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Equals($sid)){return $false}
$raw=New-Object System.Security.AccessControl.RawSecurityDescriptor($acl.GetSecurityDescriptorBinaryForm(),0)
if($null -eq $raw.DiscretionaryAcl -or $raw.DiscretionaryAcl.Count -ne 1){return $false}
$ace=$raw.DiscretionaryAcl[0]
if($ace -isnot [System.Security.AccessControl.CommonAce] -or $ace.AceType -ne [System.Security.AccessControl.AceType]::AccessAllowed -or $ace.IsCallback -or $ace.OpaqueLength -ne 0){return $false}
$rules=$acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) $rules=$acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
if($rules.Count -ne 1){return $false} if($rules.Count -ne 1){return $false}
$rule=$rules[0] $rule=$rules[0]
+1
View File
@@ -43,3 +43,4 @@ test('dashboard asset initialization failure closes the already-created session
Module._resolveFilename=function(id,...rest){if(id==='@tabler/core/dist/css/tabler.min.css')throw new Error('fixture missing asset');return originalResolve.call(this,id,...rest);};SessionStore.prototype.close=function(){closed++;return originalClose.call(this);}; Module._resolveFilename=function(id,...rest){if(id==='@tabler/core/dist/css/tabler.min.css')throw new Error('fixture missing asset');return originalResolve.call(this,id,...rest);};SessionStore.prototype.close=function(){closed++;return originalClose.call(this);};
try{assert.throws(()=>createDashboard({store:new Store(path.join(dir,'dashboard')),outputDir:dir}),/fixture missing asset/);assert.equal(closed,1);}finally{Module._resolveFilename=originalResolve;SessionStore.prototype.close=originalClose;} try{assert.throws(()=>createDashboard({store:new Store(path.join(dir,'dashboard')),outputDir:dir}),/fixture missing asset/);assert.equal(closed,1);}finally{Module._resolveFilename=originalResolve;SessionStore.prototype.close=originalClose;}
}); });
test('application wires test expiry to every manual mail submission path',async t=>{const options=await fixture(t),app=await main(options);t.after(async()=>{await app.stop();await fs.rm(options.stateDir,{recursive:true,force:true});});app.orderRules.put('stability-test',{id:'main',enabled:true,startedAt:'2026-01-01T00:00:00Z',endsAt:'2026-01-02T00:00:00Z'});assert.throws(()=>app.mail.beforeSend(),e=>e.code==='STABILITY_TEST_EXPIRED');});
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{execFileSync,spawnSync}=require('node:child_process');
test('host repair validator runs fixed and changed tests in a foreign-owned isolated checkout',t=>{
const base=fs.mkdtempSync(path.join(os.tmpdir(),'repair-validator-'));
t.after(()=>fs.rmSync(base,{recursive:true,force:true}));
const host=path.join(base,'host'),repo=path.join(base,'repo'),checkout=path.join(base,'checkout'),validator=path.join(host,'src','modules','assistant','repair-validator.cjs');
fs.mkdirSync(path.dirname(validator),{recursive:true});fs.mkdirSync(path.join(repo,'tests'),{recursive:true});
fs.copyFileSync(path.resolve(__dirname,'../../src/modules/assistant/repair-validator.cjs'),validator);
fs.writeFileSync(path.join(host,'package.json'),JSON.stringify({scripts:{'test:business':'node --test --test-concurrency=1 tests/fixed.test.cjs'}}));
const git=(cwd,...args)=>execFileSync('git',['-c','user.name=Test','-c','user.email=test@example.invalid',...args],{cwd,encoding:'utf8',stdio:['ignore','pipe','pipe']});
const receipt=path.join(base,'ran-tests.txt'),testSource=name=>"require('node:test')("+JSON.stringify(name)+",()=>require('node:fs').appendFileSync("+JSON.stringify(receipt)+","+JSON.stringify(name+'\n')+"));";
fs.writeFileSync(path.join(repo,'tests/fixed.test.cjs'),testSource('fixed manifest test'));
git(repo,'init');git(repo,'add','.');git(repo,'commit','-m','baseline');git(repo,'worktree','add','--detach',checkout);
fs.writeFileSync(path.join(checkout,'tests/changed.test.cjs'),testSource('changed repair test'));
git(checkout,'add','.');git(checkout,'commit','-m','proposal');
const env={...process.env,GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:process.platform==='win32'?'NUL':'/dev/null',GIT_TEST_ASSUME_DIFFERENT_OWNER:'1'};
delete env.NODE_TEST_CONTEXT; // Production runner also excludes test-runner internals.
const result=spawnSync(process.execPath,[validator],{cwd:checkout,env,encoding:'utf8',windowsHide:true});
assert.equal(result.status,0,result.stderr);assert.deepEqual(fs.readFileSync(receipt,'utf8').trim().split('\n').sort(),['changed repair test','fixed manifest test']);
// Trust applies to this one invocation; it must not persist globally or locally.
const untrusted=spawnSync('git',['rev-parse','HEAD'],{cwd:checkout,env,encoding:'utf8',windowsHide:true});
assert.notEqual(untrusted.status,0);assert.match(untrusted.stderr,/dubious ownership/);
});
+7 -1
View File
@@ -26,10 +26,13 @@ test('native ACL policy accepts only the current owner and one protected inherit
$extra=Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid $extra=Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid
$extra.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($other,'Read','ContainerInherit,ObjectInherit','None','Allow'))) $extra.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($other,'Read','ContainerInherit,ObjectInherit','None','Allow')))
$rows+=(Test-PrivateDirectoryAcl $extra $sid) $rows+=(Test-PrivateDirectoryAcl $extra $sid)
$hidden=New-Object System.Security.AccessControl.DirectorySecurity
$hidden.SetSecurityDescriptorSddlForm('O:'+$sid.Value+'D:P(A;OICI;FA;;;'+$sid.Value+')(OA;OICI;FA;00000000-0000-0000-0000-000000000001;;WD)')
$rows+=(Test-PrivateDirectoryAcl $hidden $sid)
ConvertTo-Json -Compress -InputObject $rows ConvertTo-Json -Compress -InputObject $rows
`; `;
const output=cp.execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop";'+privateDirectoryAcl+cases],{encoding:'utf8',windowsHide:true,timeout:15000}); const output=cp.execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop";'+privateDirectoryAcl+cases],{encoding:'utf8',windowsHide:true,timeout:15000});
assert.deepEqual(JSON.parse(output),[true,false,false,false,false,false,false,false,false]); assert.deepEqual(JSON.parse(output),[true,false,false,false,false,false,false,false,false,false]);
}); });
test('a compliant real directory is not rewritten and an unprotected directory is repaired',{skip:process.platform!=='win32'},t=>{ test('a compliant real directory is not rewritten and an unprotected directory is repaired',{skip:process.platform!=='win32'},t=>{
@@ -40,4 +43,7 @@ test('a compliant real directory is not rewritten and an unprotected directory i
run('$p=[Console]::In.ReadToEnd();$acl=[IO.Directory]::GetAccessControl($p);$acl.SetAccessRuleProtection($false,$true);[IO.Directory]::SetAccessControl($p,$acl)'); run('$p=[Console]::In.ReadToEnd();$acl=[IO.Directory]::GetAccessControl($p);$acl.SetAccessRuleProtection($false,$true);[IO.Directory]::SetAccessControl($p,$acl)');
run(secureDirectoryScript); run(secureDirectoryScript);
const verified=run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)');assert.equal(verified,'True'); const verified=run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)');assert.equal(verified,'True');
run('$p=[Console]::In.ReadToEnd();$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User;$acl=New-Object System.Security.AccessControl.DirectorySecurity;$acl.SetSecurityDescriptorSddlForm("O:"+$sid.Value+"D:P(A;OICI;FA;;;"+$sid.Value+")(OA;OICI;FA;00000000-0000-0000-0000-000000000001;;WD)",[System.Security.AccessControl.AccessControlSections]"Access,Owner");[IO.Directory]::SetAccessControl($p,$acl)');
assert.equal(run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)'),'False');
run(secureDirectoryScript);assert.equal(run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)'),'True');
}); });
+4 -4
View File
@@ -4,11 +4,11 @@ const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company
const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMessage-ID: <a@company.test>\r\n\r\nHello {{订单号}}'); const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMessage-ID: <a@company.test>\r\n\r\nHello {{订单号}}');
async function fixture(t,options={}){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-service-'));const store=new MailStore(dir);const service=new MailService({store,...options});t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,service};} async function fixture(t,options={}){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-service-'));const store=new MailStore(dir);const service=new MailService({store,...options});t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,service};}
test('self-test renders business template variables with synthetic data and the configured self recipient',async t=>{ test('self-test renders business template variables with synthetic data and the fixed isolated QQ recipient',async t=>{
let sent;const {store,service}=await fixture(t,{smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sent=message;return {accepted:[config.email]};},close(){}})}); let sent;const {store,service}=await fixture(t,{smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sent=message;return {accepted:['2639266652@qq.com']};},close(){}})});
const c=store.saveChannel({...config,signature:{enabled:true,format:'html',body:'<p>Best Regards! 隔离账户签名</p>'}}),p=require('../../src/modules/mail/parser.cjs'),body='{{类别名称}}\n{{订单明细}}\n存放地址:{{存放地址}}',mail=Buffer.from(raw.toString().replace('Hello {{订单号}}',body)); const c=store.saveChannel({...config,signature:{enabled:true,format:'html',body:'<p>Best Regards! 隔离账户签名</p>'}}),p=require('../../src/modules/mail/parser.cjs'),body='{{类别名称}}\n{{订单明细}}\n存放地址:{{存放地址}}',mail=Buffer.from(raw.toString().replace('Hello {{订单号}}',body));
const draft=store.ingest(c.id,'1',1,await p.parseTemplate(mail,config),mail,c.version);store.confirm(draft.id,{version:1,subject:'测试摘要',scope:'',text:body,useText:true},'admin'); const draft=store.ingest(c.id,'1',1,await p.parseTemplate(mail,config),mail,c.version);store.confirm(draft.id,{version:1,subject:'测试摘要',scope:'',text:body,useText:true},'admin');
await service.sendTest(c.id,draft.id);assert.equal(sent.to.address,config.email);assert.match(sent.text,/订单号:TEST/);assert.match(sent.text,/示例归档目录/);assert.match(sent.text,/隔离账户签名/);assert.match(sent.html,/<p>Best Regards!/);assert.doesNotMatch(sent.text,/{{/);assert.equal(store.sends()[0].status,'sent'); await service.sendTest(c.id,draft.id);assert.deepEqual(sent.to,['2639266652@qq.com']);assert.deepEqual(sent.cc,[]);assert.deepEqual(sent.attachments,[]);assert.match(sent.text,/订单号:TEST/);assert.match(sent.text,/示例归档目录/);assert.match(sent.text,/隔离账户签名/);assert.match(sent.html,/<p>Best Regards!/);assert.doesNotMatch(sent.text,/{{/);assert.equal(store.sends()[0].status,'sent');
}); });
test('read-only poll uses UID epoch, ignores ordinary messages, does not double ingest, and records source denials',async t=>{ test('read-only poll uses UID epoch, ignores ordinary messages, does not double ingest, and records source denials',async t=>{
let downloads=0,locks=0;const client={mailbox:{uidValidity:10n},on(){},async connect(){},async getMailboxLock(box,options){assert.equal(box,'INBOX');assert.equal(options.readOnly,true);locks++;return {release(){locks--;}};},async search(query,options){assert.equal(options.uid,true);return [1,2,3];},async fetchOne(uid,query,options){assert.equal(options.uid,true);if(query.source){downloads++;return {source:uid===3?Buffer.from(raw.toString().replace('author@','unknown@')):raw};}return {size:raw.length,envelope:{subject:uid===1?'Ordinary':'[模板]Notice'}};},async logout(){},close(){}}; let downloads=0,locks=0;const client={mailbox:{uidValidity:10n},on(){},async connect(){},async getMailboxLock(box,options){assert.equal(box,'INBOX');assert.equal(options.readOnly,true);locks++;return {release(){locks--;}};},async search(query,options){assert.equal(options.uid,true);return [1,2,3];},async fetchOne(uid,query,options){assert.equal(options.uid,true);if(query.source){downloads++;return {source:uid===3?Buffer.from(raw.toString().replace('author@','unknown@')):raw};}return {size:raw.length,envelope:{subject:uid===1?'Ordinary':'[模板]Notice'}};},async logout(){},close(){}};
@@ -22,5 +22,5 @@ test('initial empty seven-day scan retains date boundary on future polls',async
test('SMTP verification never sends; explicit self-test uses confirmed template and durable send record',async t=>{ test('SMTP verification never sends; explicit self-test uses confirmed template and durable send record',async t=>{
let messages=[];const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',c=>chunks.push(c));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}});await new Promise(r=>smtp.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>smtp.close(r))); let messages=[];const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',c=>chunks.push(c));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}});await new Promise(r=>smtp.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>smtp.close(r)));
const nodemailer=require('nodemailer');const {store,service}=await fixture(t,{smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true}),imapFactory:()=>({on(){},async connect(){},async getMailboxLock(){return {release(){}};},async logout(){},close(){}})}); const nodemailer=require('nodemailer');const {store,service}=await fixture(t,{smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true}),imapFactory:()=>({on(){},async connect(){},async getMailboxLock(){return {release(){}};},async logout(){},close(){}})});
const c=store.saveChannel(config);await service.verify(c.id);assert.equal(messages.length,0);const p=require('../../src/modules/mail/parser.cjs');const draft=store.ingest(c.id,'1',1,await p.parseTemplate(raw,config),raw,c.version);assert.equal(store.active(c.id,''),null);await assert.rejects(service.sendTest(c.id,draft.id),e=>e.status===409);store.confirm(draft.id,{version:1,subject:'Notice {{订单号}}',scope:'',text:'Hello {{订单号}}',useText:false},'admin');await service.sendTest(c.id,draft.id);assert.equal(messages.length,1);const sent=await simpleParser(messages[0]);assert.equal(sent.to.value[0].address,config.email);assert.match(sent.text,/Hello TEST/);assert.equal(store.sends()[0].status,'sent'); const c=store.saveChannel(config);await service.verify(c.id);assert.equal(messages.length,0);const p=require('../../src/modules/mail/parser.cjs');const draft=store.ingest(c.id,'1',1,await p.parseTemplate(raw,config),raw,c.version);assert.equal(store.active(c.id,''),null);await assert.rejects(service.sendTest(c.id,draft.id),e=>e.status===409);store.confirm(draft.id,{version:1,subject:'Notice {{订单号}}',scope:'',text:'Hello {{订单号}}',useText:false},'admin');await service.sendTest(c.id,draft.id);assert.equal(messages.length,1);const sent=await simpleParser(messages[0]);assert.equal(sent.to.value[0].address,'2639266652@qq.com');assert.match(sent.text,/Hello TEST/);assert.equal(store.sends()[0].status,'sent');
}); });
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {MailService}=require('../../src/modules/mail/service.cjs');
function fixture({verify=()=>{},beforeSend=()=>{},unknown=false}={}){
const rows=[],messages=[],template={id:'template',version:1,status:'active',channelId:'channel',subject:'Template',text:'Hello {{订单号}}',html:'',attachments:[{filename:'private.pdf',content:'cGRm',contentType:'application/pdf'}]};
const store={channelSecret:()=>({id:'channel',version:1,email:'sender@company.test',name:'Sender',smtp:{}}),guard(){},template:()=>({...template}),sends:()=>rows,findSampleSend:(id,key)=>rows.find(r=>r.channel_id===id&&r.template_id===key),beginSend:(id,key)=>{rows.push({id:'send-'+rows.length,channel_id:id,template_id:key,status:'sending'});return rows.at(-1).id;},finishSend:(id,status)=>{rows.find(r=>r.id===id).status=status;}};
const service=new MailService({store,beforeSend,smtpFactory:()=>({verify:async()=>verify(template),sendMail:async message=>{messages.push(message);if(unknown)throw Error('connection lost');return {accepted:['2639266652@qq.com'],rejected:[]};},close(){}})});
return {service,rows,messages,template};
}
test('legacy template test enforces fixed QQ envelope without source attachments',async()=>{
const f=fixture(),result=await f.service.sendTest('channel','template');assert.equal(result.to,'2639266652@qq.com');assert.deepEqual(f.messages[0].to,['2639266652@qq.com']);assert.deepEqual(f.messages[0].cc,[]);assert.deepEqual(f.messages[0].attachments,[]);
});
for(const action of ['sendTest','sendSample'])for(const phase of ['before','after'])test(action+' enforces active period '+phase+' SMTP verification',async()=>{
let verified=false;const f=fixture({verify:()=>{verified=true;},beforeSend:()=>{if(phase==='before'||verified)throw Object.assign(Error('expired'),{status:409});}});
await assert.rejects(()=>action==='sendTest'?f.service.sendTest('channel','template'):f.service.sendSample('channel',{idempotencyKey:'one',subject:'Sample',text:'Hello'}),e=>e.status===409);assert.equal(f.messages.length,0);assert.equal(f.rows.length,0);assert.equal(verified,phase==='after');
});
test('template changed during SMTP verification is not submitted',async()=>{
const f=fixture({verify:t=>{t.version++;}});await assert.rejects(()=>f.service.sendTest('channel','template'),e=>e.status===409);assert.equal(f.messages.length,0);
});
test('uncertain template test cannot be repeated',async()=>{
const f=fixture({unknown:true});await assert.rejects(()=>f.service.sendTest('channel','template'));assert.equal(f.rows[0].status,'unknown');await assert.rejects(()=>f.service.sendTest('channel','template'),e=>e.status===409);assert.equal(f.messages.length,1);
});
@@ -0,0 +1,14 @@
'use strict';
// Keep the real server entrypoint and OS lifecycle, replacing business startup
// so this crash test cannot access company systems or production state.
const fs=require('node:fs'),http=require('node:http'),path=require('node:path');
const {respondToPing}=require('../../../src/platform/service/ping.cjs');
const application=require.resolve('../../../src/app/application.cjs');
require.cache[application]={id:application,filename:application,loaded:true,exports:{async main(){
const dir=process.env.ORDER_CRASH_TEST_DIR,port=Number(process.env.ORDER_CRASH_TEST_PORT);let ticks=0;
const server=http.createServer((req,res)=>respondToPing(req,res,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt:new Date().toISOString()}));
await new Promise(resolve=>server.listen(port,'127.0.0.1',resolve));
fs.writeFileSync(path.join(dir,'child.pid'),String(process.pid));
const timer=setInterval(()=>fs.writeFileSync(path.join(dir,'ticks'),String(++ticks)),40);
return {async stop(){clearInterval(timer);await new Promise(resolve=>server.close(resolve));}};
}}};
@@ -0,0 +1,4 @@
'use strict';
const path=require('node:path');
const {ServiceSupervisor}=require('../../../src/platform/service/supervisor.cjs');
new ServiceSupervisor({stateDir:process.env.ORDER_CRASH_TEST_DIR,ports:[Number(process.env.ORDER_CRASH_TEST_PORT)],env:{NODE_OPTIONS:'--require "'+path.join(__dirname,'crash-service-preload.cjs').replaceAll('\\','/')+'"'},timing:{intervalMs:50,pingTimeoutMs:100,startupGraceMs:3000}}).start().catch(error=>{console.error(error);process.exit(1);});
+20
View File
@@ -0,0 +1,20 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),net=require('node:net'),{spawn}=require('node:child_process');
const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
const crash=guard=>process.platform==='win32'?require('node:child_process').execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command','Stop-Process -Id '+guard.pid+' -Force'],{windowsHide:true}):guard.kill('SIGKILL');
const alive=pid=>{try{process.kill(pid,0);return true;}catch{return false;}};
async function until(predicate,timeout=5000){const end=Date.now()+timeout;while(Date.now()<end){if(await predicate())return true;await pause(40);}return false;}
async function freePort(){const socket=net.createServer();await new Promise(resolve=>socket.listen(0,'127.0.0.1',resolve));const port=socket.address().port;await new Promise(resolve=>socket.close(resolve));return port;}
async function fixture(t){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-crash-')),port=await freePort();let childPid;
const guard=spawn(process.execPath,[path.resolve('tests/service/fixtures/crash-supervisor.cjs')],{cwd:process.cwd(),windowsHide:true,detached:true,stdio:'ignore',env:{...process.env,ORDER_CRASH_TEST_DIR:dir,ORDER_CRASH_TEST_PORT:String(port)}});
t.after(async()=>{if(alive(guard.pid))guard.kill('SIGKILL');if(childPid&&alive(childPid))process.kill(childPid,'SIGKILL');await until(()=>!alive(guard.pid)&&(!childPid||!alive(childPid)));await fs.rm(dir,{recursive:true,force:true});});
assert.equal(await until(async()=>{try{childPid=Number(await fs.readFile(path.join(dir,'child.pid'),'utf8'));return Number(await fs.readFile(path.join(dir,'ticks'),'utf8'))>1;}catch{return false;}}),true,'isolated child must start');
return {dir,port,guard,childPid};
}
test('Windows abrupt supervisor death stops its business child and releases its listening port',{timeout:15000,skip:process.platform!=='win32'},async t=>{
const {dir,port,guard,childPid}=await fixture(t);crash(guard);
assert.equal(await until(()=>!alive(childPid)),true,'orphan business child must exit after supervisor death');
const ticks=await fs.readFile(path.join(dir,'ticks'),'utf8');await pause(150);assert.equal(await fs.readFile(path.join(dir,'ticks'),'utf8'),ticks,'scheduled work must cease');
const socket=net.createServer();await new Promise((resolve,reject)=>{socket.once('error',reject);socket.listen(port,'127.0.0.1',resolve);});await new Promise(resolve=>socket.close(resolve));
});
+2 -2
View File
@@ -29,10 +29,10 @@ window.MailViews=(()=>{
const data=await api('/mail');if(!isActive())return;const admin=user.role==='admin';let filter=preferredFilter||(data.templates.some(t=>t.status==='active')?'active':'pending'),detailRevision=0,editor;window.PageLifecycle.onDispose(()=>{detailRevision++;editor?.dispose();}); const data=await api('/mail');if(!isActive())return;const admin=user.role==='admin';let filter=preferredFilter||(data.templates.some(t=>t.status==='active')?'active':'pending'),detailRevision=0,editor;window.PageLifecycle.onDispose(()=>{detailRevision++;editor?.dispose();});
container.innerHTML=`<div class="card mb-3"><div class="card-header flex-wrap gap-3"><h2 class="card-title">发信模板</h2><div class="ms-auto">${admin?'<button class="btn btn-primary btn-sm me-2" id="template-new" type="button">新建模板</button>':''}<a class="btn btn-sm" href="#mail">邮箱管理</a></div></div><div class="card-body"><p class="mb-2">可直接新建或编辑模板,支持纯文本与HTML。也可向托管邮箱发送 <code>[模板][产品线]发信标题</code>,新版本将在这里等待确认。未填写产品线时作为默认模板。</p><div class="small text-secondary">可用变量:<code>{{产品线}}</code>、<code>{{订单号}}</code>、<code>{{日期}}</code>、<code>{{订单列表}}</code>、<code>{{订单明细}}</code>、<code>{{存放地址}}</code>、<code>{{类别名称}}</code></div><div class="small text-secondary mt-2">订单明细只含摘要,存放地址取本批实际目录;订单列表保留原逐文件格式。</div></div><div class="card-footer"><label class="form-label" for="template-filter">模板状态</label><select class="form-select" id="template-filter">${Object.entries(labels).map(([v,label])=>`<option value="${v}">${label}(${data.templates.filter(t=>t.status===v).length})</option>`).join('')}</select></div><div id="mail-template-list"></div></div><div id="mail-template-detail"></div>`; container.innerHTML=`<div class="card mb-3"><div class="card-header flex-wrap gap-3"><h2 class="card-title">发信模板</h2><div class="ms-auto">${admin?'<button class="btn btn-primary btn-sm me-2" id="template-new" type="button">新建模板</button>':''}<a class="btn btn-sm" href="#mail">邮箱管理</a></div></div><div class="card-body"><p class="mb-2">可直接新建或编辑模板,支持纯文本与HTML。也可向托管邮箱发送 <code>[模板][产品线]发信标题</code>,新版本将在这里等待确认。未填写产品线时作为默认模板。</p><div class="small text-secondary">可用变量:<code>{{产品线}}</code>、<code>{{订单号}}</code>、<code>{{日期}}</code>、<code>{{订单列表}}</code>、<code>{{订单明细}}</code>、<code>{{存放地址}}</code>、<code>{{类别名称}}</code></div><div class="small text-secondary mt-2">订单明细只含摘要,存放地址取本批实际目录;订单列表保留原逐文件格式。</div></div><div class="card-footer"><label class="form-label" for="template-filter">模板状态</label><select class="form-select" id="template-filter">${Object.entries(labels).map(([v,label])=>`<option value="${v}">${label}(${data.templates.filter(t=>t.status===v).length})</option>`).join('')}</select></div><div id="mail-template-list"></div></div><div id="mail-template-detail"></div>`;
const draw=()=>{const items=data.templates.filter(t=>t.status===filter);container.querySelector('#mail-template-list').innerHTML=items.length?`<div class="table-responsive"><table class="table card-table"><thead><tr><th>标题 / 范围</th><th>来源</th><th></th></tr></thead><tbody>${items.map(t=>`<tr><td><div class="fw-medium">${esc(t.subject)}</div><div class="small text-secondary mt-1">${esc(t.scope||'默认模板')} · ${modeBadge(t)} · ${stateBadge(t)} · ${t.attachmentCount} 个附件</div></td><td class="small">${esc(data.channels.find(c=>c.id===t.channelId)?.name||'旧模板草稿')}<div class="text-secondary">${esc(t.sender)}<br>${formatDate(t.createdAt)}</div></td><td><button class="btn btn-sm" data-template="${t.id}">${t.status==='pending'?'预览并确认':'查看版本'}</button></td></tr>`).join('')}</tbody></table></div>`:'<div class="card-body text-center text-secondary py-4">暂无'+labels[filter]+'模板</div>';container.querySelectorAll('[data-template]').forEach(b=>b.onclick=()=>window.PageLifecycle.guard(()=>action(b,()=>detail(b.dataset.template))));};draw();container.querySelector('#template-filter').value=filter;container.querySelector('#template-filter').onchange=event=>{filter=event.target.value;draw();}; const draw=()=>{const items=data.templates.filter(t=>t.status===filter);container.querySelector('#mail-template-list').innerHTML=items.length?`<div class="table-responsive"><table class="table card-table"><thead><tr><th>标题 / 范围</th><th>来源</th><th></th></tr></thead><tbody>${items.map(t=>`<tr><td><div class="fw-medium">${esc(t.subject)}</div><div class="small text-secondary mt-1">${esc(t.scope||'默认模板')} · ${modeBadge(t)} · ${stateBadge(t)} · ${t.attachmentCount} 个附件</div></td><td class="small">${esc(data.channels.find(c=>c.id===t.channelId)?.name||'旧模板草稿')}<div class="text-secondary">${esc(t.sender)}<br>${formatDate(t.createdAt)}</div></td><td><button class="btn btn-sm" data-template="${t.id}">${t.status==='pending'?'预览并确认':'查看版本'}</button></td></tr>`).join('')}</tbody></table></div>`:'<div class="card-body text-center text-secondary py-4">暂无'+labels[filter]+'模板</div>';container.querySelectorAll('[data-template]').forEach(b=>b.onclick=()=>window.PageLifecycle.guard(()=>action(b,()=>detail(b.dataset.template))));};draw();container.querySelector('#template-filter').value=filter;container.querySelector('#template-filter').onchange=event=>{filter=event.target.value;draw();};
async function detail(id){editor?.dispose();const revision=++detailRevision,host=container.querySelector('#mail-template-detail');host.innerHTML='<div class="card mb-3"><div class="card-body text-secondary" role="status">正在读取模板…</div></div>';let t;try{t=await api('/mail/templates/'+id);}catch(error){if(!isActive()||revision!==detailRevision)return;host.innerHTML='<div class="alert alert-danger">'+esc(error.message)+';请重新选择模板重试。</div>';throw error;}if(!isActive()||revision!==detailRevision)return;const pending=t.status==='pending';host.innerHTML=`<form class="card mb-3" id="template-review"><div class="card-header gap-2"><h3 class="card-title">模板预览</h3>${stateBadge(t)}${modeBadge(t)}<button type="button" class="btn btn-sm ms-auto" id="template-close">关闭</button></div><div class="card-body"><div class="small text-secondary mb-3">来源:${esc(t.sender)} · ${formatDate(t.date||t.createdAt)}<br>原主题:${esc(t.sourceSubject||t.subject)}</div>${t.notes?.length?`<div class="alert alert-info">${t.notes.map(esc).join('<br>')}</div>`:''}${t.channelId==='legacy'?`<div class="mb-3"><label class="form-label" for="legacy-channel">使用邮箱</label><select class="form-select" id="legacy-channel" required><option value="">请选择托管邮箱</option>${data.channels.filter(c=>!c.readOnly).map(c=>`<option value="${c.id}">${esc(c.name)}</option>`).join('')}</select></div>`:''}<div class="mb-3"><label class="form-label" for="template-mode">通知模式</label><select class="form-select" id="template-mode" ${pending&&admin?'':'disabled'}><option value="normal" ${t.notificationMode!=='huizhou'?'selected':''}>普通通知</option><option value="huizhou" ${t.notificationMode==='huizhou'?'selected':''}>惠州通知</option></select><div class="form-hint">两个模式分别确认,规则只能选择相应模式的模板。</div></div><div class="row g-3 mb-3"><div class="col-md-8"><label class="form-label" for="template-subject">发信标题</label><input class="form-control" id="template-subject" value="${esc(t.subject)}" required maxlength="300" ${pending&&admin?'':'disabled'}></div><div class="col-md-4"><label class="form-label" for="template-scope">适用产品线</label><input class="form-control" id="template-scope" value="${esc(t.scope)}" maxlength="80" placeholder="留空为默认模板" ${pending&&admin?'':'disabled'}></div></div><iframe class="mail-preview" title="邮件正文预览" sandbox src="/api/mail/templates/${id}/preview"></iframe>${pending&&admin?`<div class="mt-3"><label class="form-check"><input class="form-check-input" id="template-use-text" type="checkbox"><span class="form-check-label">改用纯文本正文</span></label><div id="template-text-editor" hidden><label class="form-label mt-2" for="template-text">纯文本正文</label><textarea class="form-control" id="template-text" rows="7" maxlength="20000">${esc(t.text)}</textarea><div class="form-hint">确认后使用这里的正文,附件继续保留。</div></div></div>`:''}<div class="mt-3"><h4 class="mb-2">附件(${t.attachments.length})</h4><ul class="list-unstyled mb-0">${t.attachments.map((a,i)=>`<li class="mb-1">${admin?`<a href="/api/mail/templates/${id}/attachments/${i}" download>${esc(a.filename)}</a>`:esc(a.filename)} <span class="text-secondary small">${Math.ceil(a.size/1024)} KB${a.inline?' · 内嵌图片':''}</span></li>`).join('')||'<li class="text-secondary small">无附件</li>'}</ul></div><div class="text-danger mt-3" id="template-error" role="alert"></div></div><div class="card-footer btn-list">${admin&&t.hasSource&&t.channelId!=='legacy'?`<a class="btn btn-sm" href="/api/mail/templates/${id}/source" download>下载原邮件</a>`:''}${pending&&admin?'<button type="button" class="btn btn-outline-secondary ms-auto" id="template-reject">忽略此模板</button><button type="submit" class="btn btn-primary">确认生效</button>':''}${admin?'<button type="button" class="btn btn-primary" id="template-edit">'+(['active','pending'].includes(t.status)?'编辑模板':'复制编辑')+'</button>':''}${t.status==='active'&&admin?'<button type="button" class="btn btn-primary ms-auto" id="template-test">发送测试到本邮箱</button>':''}</div></form>`;host.scrollIntoView({block:'start',behavior:'smooth'});host.querySelector('#template-close').onclick=()=>{detailRevision++;host.replaceChildren();}; async function detail(id){editor?.dispose();const revision=++detailRevision,host=container.querySelector('#mail-template-detail');host.innerHTML='<div class="card mb-3"><div class="card-body text-secondary" role="status">正在读取模板…</div></div>';let t;try{t=await api('/mail/templates/'+id);}catch(error){if(!isActive()||revision!==detailRevision)return;host.innerHTML='<div class="alert alert-danger">'+esc(error.message)+';请重新选择模板重试。</div>';throw error;}if(!isActive()||revision!==detailRevision)return;const pending=t.status==='pending';host.innerHTML=`<form class="card mb-3" id="template-review"><div class="card-header gap-2"><h3 class="card-title">模板预览</h3>${stateBadge(t)}${modeBadge(t)}<button type="button" class="btn btn-sm ms-auto" id="template-close">关闭</button></div><div class="card-body"><div class="small text-secondary mb-3">来源:${esc(t.sender)} · ${formatDate(t.date||t.createdAt)}<br>原主题:${esc(t.sourceSubject||t.subject)}</div>${t.notes?.length?`<div class="alert alert-info">${t.notes.map(esc).join('<br>')}</div>`:''}${t.channelId==='legacy'?`<div class="mb-3"><label class="form-label" for="legacy-channel">使用邮箱</label><select class="form-select" id="legacy-channel" required><option value="">请选择托管邮箱</option>${data.channels.filter(c=>!c.readOnly).map(c=>`<option value="${c.id}">${esc(c.name)}</option>`).join('')}</select></div>`:''}<div class="mb-3"><label class="form-label" for="template-mode">通知模式</label><select class="form-select" id="template-mode" ${pending&&admin?'':'disabled'}><option value="normal" ${t.notificationMode!=='huizhou'?'selected':''}>普通通知</option><option value="huizhou" ${t.notificationMode==='huizhou'?'selected':''}>惠州通知</option></select><div class="form-hint">两个模式分别确认,规则只能选择相应模式的模板。</div></div><div class="row g-3 mb-3"><div class="col-md-8"><label class="form-label" for="template-subject">发信标题</label><input class="form-control" id="template-subject" value="${esc(t.subject)}" required maxlength="300" ${pending&&admin?'':'disabled'}></div><div class="col-md-4"><label class="form-label" for="template-scope">适用产品线</label><input class="form-control" id="template-scope" value="${esc(t.scope)}" maxlength="80" placeholder="留空为默认模板" ${pending&&admin?'':'disabled'}></div></div><iframe class="mail-preview" title="邮件正文预览" sandbox src="/api/mail/templates/${id}/preview"></iframe>${pending&&admin?`<div class="mt-3"><label class="form-check"><input class="form-check-input" id="template-use-text" type="checkbox"><span class="form-check-label">改用纯文本正文</span></label><div id="template-text-editor" hidden><label class="form-label mt-2" for="template-text">纯文本正文</label><textarea class="form-control" id="template-text" rows="7" maxlength="20000">${esc(t.text)}</textarea><div class="form-hint">确认后使用这里的正文,附件继续保留。</div></div></div>`:''}<div class="mt-3"><h4 class="mb-2">附件(${t.attachments.length})</h4><ul class="list-unstyled mb-0">${t.attachments.map((a,i)=>`<li class="mb-1">${admin?`<a href="/api/mail/templates/${id}/attachments/${i}" download>${esc(a.filename)}</a>`:esc(a.filename)} <span class="text-secondary small">${Math.ceil(a.size/1024)} KB${a.inline?' · 内嵌图片':''}</span></li>`).join('')||'<li class="text-secondary small">无附件</li>'}</ul></div><div class="text-danger mt-3" id="template-error" role="alert"></div></div><div class="card-footer btn-list">${admin&&t.hasSource&&t.channelId!=='legacy'?`<a class="btn btn-sm" href="/api/mail/templates/${id}/source" download>下载原邮件</a>`:''}${pending&&admin?'<button type="button" class="btn btn-outline-secondary ms-auto" id="template-reject">忽略此模板</button><button type="submit" class="btn btn-primary">确认生效</button>':''}${admin?'<button type="button" class="btn btn-primary" id="template-edit">'+(['active','pending'].includes(t.status)?'编辑模板':'复制编辑')+'</button>':''}${t.status==='active'&&admin?'<button type="button" class="btn btn-primary ms-auto" id="template-test">发送测试到隔离邮箱</button>':''}</div></form>`;host.scrollIntoView({block:'start',behavior:'smooth'});host.querySelector('#template-close').onclick=()=>{detailRevision++;host.replaceChildren();};
if(admin)host.querySelector('#template-edit').onclick=()=>window.PageLifecycle.guard(()=>{detailRevision++;editor?.dispose();editor=window.MailTemplateEditor.open(host,{template:t,copy:!['active','pending'].includes(t.status),channels:data.channels,api,esc,isActive,feedback:notify,onSaved:saved=>{editor?.dispose();return templates(container,isActive,saved.status==='active'?'active':'pending');}});}); if(admin)host.querySelector('#template-edit').onclick=()=>window.PageLifecycle.guard(()=>{detailRevision++;editor?.dispose();editor=window.MailTemplateEditor.open(host,{template:t,copy:!['active','pending'].includes(t.status),channels:data.channels,api,esc,isActive,feedback:notify,onSaved:saved=>{editor?.dispose();return templates(container,isActive,saved.status==='active'?'active':'pending');}});});
if(pending&&admin){host.querySelector('#template-mode').onchange=e=>{const badge=host.querySelector('[data-template-mode]');badge.textContent=modeLabel({notificationMode:e.target.value});badge.className='badge bg-'+(e.target.value==='huizhou'?'cyan':'blue')+'-lt';};host.querySelector('#template-use-text').onchange=e=>host.querySelector('#template-text-editor').hidden=!e.target.checked;host.querySelector('#template-review').onsubmit=async e=>{e.preventDefault();const button=e.submitter;button.disabled=true;try{const useText=host.querySelector('#template-use-text').checked;await api(`/mail/templates/${id}/confirm`,{version:t.version,notificationMode:host.querySelector('#template-mode').value,subject:host.querySelector('#template-subject').value,scope:host.querySelector('#template-scope').value,useText,...(useText?{text:host.querySelector('#template-text').value}:{}),...(t.channelId==='legacy'?{channelId:host.querySelector('#legacy-channel').value}:{})});if(isActive()){host.innerHTML='<div class="alert alert-success">模板已确认生效。</div>';await window.PageLifecycle.afterSave(()=>templates(container,isActive),'模板已确认生效。',notify,isActive);}}catch(error){if(isActive())host.querySelector('#template-error').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}};host.querySelector('#template-reject').onclick=e=>action(e.target,async()=>{await api(`/mail/templates/${id}/reject`,{version:t.version});if(isActive()){host.innerHTML='<div class="alert alert-info">模板已忽略。</div>';await window.PageLifecycle.afterSave(()=>templates(container,isActive),'模板已忽略。',notify,isActive);}});} if(pending&&admin){host.querySelector('#template-mode').onchange=e=>{const badge=host.querySelector('[data-template-mode]');badge.textContent=modeLabel({notificationMode:e.target.value});badge.className='badge bg-'+(e.target.value==='huizhou'?'cyan':'blue')+'-lt';};host.querySelector('#template-use-text').onchange=e=>host.querySelector('#template-text-editor').hidden=!e.target.checked;host.querySelector('#template-review').onsubmit=async e=>{e.preventDefault();const button=e.submitter;button.disabled=true;try{const useText=host.querySelector('#template-use-text').checked;await api(`/mail/templates/${id}/confirm`,{version:t.version,notificationMode:host.querySelector('#template-mode').value,subject:host.querySelector('#template-subject').value,scope:host.querySelector('#template-scope').value,useText,...(useText?{text:host.querySelector('#template-text').value}:{}),...(t.channelId==='legacy'?{channelId:host.querySelector('#legacy-channel').value}:{})});if(isActive()){host.innerHTML='<div class="alert alert-success">模板已确认生效。</div>';await window.PageLifecycle.afterSave(()=>templates(container,isActive),'模板已确认生效。',notify,isActive);}}catch(error){if(isActive())host.querySelector('#template-error').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}};host.querySelector('#template-reject').onclick=e=>action(e.target,async()=>{await api(`/mail/templates/${id}/reject`,{version:t.version});if(isActive()){host.innerHTML='<div class="alert alert-info">模板已忽略。</div>';await window.PageLifecycle.afterSave(()=>templates(container,isActive),'模板已忽略。',notify,isActive);}});}
host.querySelector('#template-test')?.addEventListener('click',e=>{const c=data.channels.find(c=>c.id===t.channelId);if(!confirm(`使用此模板发送一封测试邮件到 ${c.email}?`))return;action(e.target,async()=>{await api(`/mail/channels/${t.channelId}/test`,{templateId:id});notify('测试邮件已提交至邮件服务器。');});}); host.querySelector('#template-test')?.addEventListener('click',e=>{const c=data.channels.find(c=>c.id===t.channelId);if(!confirm(`使用此模板发送一封测试邮件到隔离邮箱 2639266652@qq.com(无抄送、无附件)?`))return;action(e.target,async()=>{await api(`/mail/channels/${t.channelId}/test`,{templateId:id});notify('测试邮件已提交至邮件服务器。');});});
} }
if(admin)container.querySelector('#template-new').onclick=()=>window.PageLifecycle.guard(()=>{detailRevision++;editor?.dispose();editor=window.MailTemplateEditor.open(container.querySelector('#mail-template-detail'),{channels:data.channels,api,esc,isActive,feedback:notify,onSaved:saved=>{editor?.dispose();return templates(container,isActive,saved.status==='active'?'active':'pending');}});}); if(admin)container.querySelector('#template-new').onclick=()=>window.PageLifecycle.guard(()=>{detailRevision++;editor?.dispose();editor=window.MailTemplateEditor.open(container.querySelector('#mail-template-detail'),{channels:data.channels,api,esc,isActive,feedback:notify,onSaved:saved=>{editor?.dispose();return templates(container,isActive,saved.status==='active'?'active':'pending');}});});
return data; return data;