diff --git a/README.md b/README.md index d891698..3d7490c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 面向团队的 BPM 订单工作台,提供业务日历、异常待办与转交、连接管理和运行监管配置;保留 Chrome 已登录订单页导出本地 PDF 的能力。 -**订单通知流程**:以 Excel 的15类为准,从真实 BPM 待办按流程、版本和节点识别订单,导出并校验归档文件,按北京时间每天两个有效时段同类别汇总一封。收件人由分类规则维护,BPM 节点人工办理,惠州额外通知条件待确认。自动发信保持暂停,类别字段、目录、邮箱与预览须现场核验后才可启用。旧通用通知写入和调度已退役,历史记录保留查询。当前要求见[设计要求](docs/design-requirements.md)。 +**订单通知流程**:以 Excel 的15类为准,从真实 BPM 待办按流程和节点精确匹配订单,再按表单版本适配字段,导出并校验归档文件,按北京时间每天两个有效时段同类别汇总一封。收件人由分类规则维护,BPM 节点人工办理,惠州额外通知条件待确认。自动发信保持暂停,类别字段、目录、邮箱与预览须现场核验后才可启用。旧通用通知写入和调度已退役,历史记录保留查询。当前要求见[设计要求](docs/design-requirements.md)。 ## 设计与部署入口 @@ -18,7 +18,7 @@ ## Web 看板 -侧栏七项:工作总览、订单通知管理、订单与导出记录、异常待办、ZCode 助手、业务设置、系统设置。订单通知管理集中通知总览、订单执行、通知订单、待发批次、发送记录,以及发送计划/日历/模板/发送设置。业务设置维护分类通知规则与字段映射,系统设置维护服务连接、健康、账号及审计。顶部直接接入 Tabler 1.6.1 圆角分段横栏,支持手机滚动和旧地址;团队账号仅管理员可见,个人改密保留右上角。 +侧栏七项:业务首页、订单中心、邮件批次、工具、异常待办、业务设置、系统设置。工具中包含流程到达记录、PDF 导出记录和 DSH 助手;系统设置维护服务连接、邮箱、助手权限、健康和审计。首页展示实际发送窗口、批次与异常,支持窄屏与减少动态效果。 1. 启动工具后,在部署机打开 http://127.0.0.1:18766 ,自行创建管理员账号(至少 12 位密码)。没有默认账号或默认密码。 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 访问,不发送邮件。确认正常后在管理邮箱中开启 **模板收信**,服务每分钟检查;也可点击 **立即收信**。 3. 从名单内的邮箱新建邮件发送到托管邮箱,主题为 `[模板][海外运营]订单通知 {{日期}}`;正文和附件作为对应产品线模板。`[模板]订单通知` 表示默认模板。回复/转发主题、范围标记不完整、未授权发件人和超出 10 MB 的邮件不导入。首次及邮箱 UID 变化只处理近 7 天邮件,保留该日期边界和 UID 游标;只读访问,不标记已读、不移动或删除邮件。 4. 打开 **模板与收件群组 → 预览并确认**,核对来源、发信标题、产品线、表格、图片和附件后点击 **确认生效**。可调整标题和产品线,或切换为纯文本编辑正文。旧版本留作历史;多人确认发生冲突时不覆盖新版本。名单控制导入,管理员确认后才生效。 5. 支持明确变量 `{{产品线}}`、`{{订单号}}`、`{{日期}}`、`{{订单列表}}`,不执行模板表达式。HTML 预览隔离,阻断脚本及外链图片;保留原 EML,管理员可下载原邮件与附件。邮件中的 To/Cc 不会修改业务收件群组。 -6. 已生效模板可点击 **发送测试到本邮箱** 并确认目标。使用真实 SMTP 发送到托管邮箱自身,先记录发送任务,不自动重试不确定结果。此操作不会发给产品线群组。业务通知另在“业务通知”中配置来源映射,正文直接使用来源简要说明,不使用模板附件。 +6. 已生效模板可点击 **发送测试到隔离邮箱**,固定发送至 `2639266652@qq.com`,空 Cc、无附件。发送前和 SMTP 验证后复查测试期限与模板版本;结果不明禁止重复发送。分类业务通知使用规则绑定模板,PDF 仅归档,不作为附件。 旧模板草稿首次启动迁为待确认版本,确认时选择实际托管邮箱。邮箱维护须从部署机回环地址或已配置的 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,版本已锁定。公司邮箱真实连接需管理员录入参数后检查。 ## 存储服务器与业务通知 @@ -82,19 +82,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)。 -## 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 文件摘要并自动识别。 -2. 管理员在 **ZCode 接入设置** 填写供应商的 OpenAI 兼容 API 根地址(例如含 `/v1` 的地址)、模型名和密钥,再启用并保存。仅本机或可信 HTTPS 可维护。密钥加密保存、不回传;留空保留,更换地址或模型须重新填写。**检查运行包** 仅验证本地入口,真实模型认证在发送对话时验证。 -3. 默认只诊断。可单独开放固定操作卡片:检查启用的存储连接(管理员)、扫描授权 BPM 连接、重试失败归档。模型不能直接执行,必须由用户点击,服务器再次校验权限与目标,记录单次执行结果。暂停助手后旧卡片同样不可执行。 +1. 运行 `node scripts/install-dsh-runtime.cjs` 安装固定官方 DeepSeek Harness 运行包;`--check` 仅检查。运行包独立安装在 LocalAppData,项目依赖不变。 +2. 使用 Messages 兼容 API 根地址(官方默认 `https://api.deepseek.com/anthropic`)、实际模型名称和密钥。密钥加密保存、不回传;未配置密钥时助手停用。检查运行包不代表真实模型认证成功。 +3. 固定操作卡片按工作台权限执行,用户点击后重新核验目标。管理员可另行开放代码修复:明确选择已跟踪文件,先审查建议,再在独立 Git 工作区运行固定测试。通过后待人工审查,失败恢复基线并保留提交;结果不明停止并待核验,不自动合并或部署。 +4. AI 操作记录只追加保存步骤、提交、测试与恢复结果,支持按账号查询历史。原生文件、Shell、网络、MCP 工具不注册;代码验证以本机服务身份运行,Git 工作区不等同操作系统沙箱。 -助手仅发送允许范围内的运行状态与异常摘要,不读取凭据、完整 BPM 表单、邮件正文或服务器文件内容。固定 CLI 的原生工具全部禁用,插件、MCP、技能、子代理、记忆和 hooks 关闭;每轮使用独立临时配置及过滤环境。模型输出只接受规定 JSON,不能执行任意命令、URL、路径,不审批、不发邮件、不改配置。限制属于已核对版本的应用控制,不是操作系统沙箱。 - -消息与模型配置加密保存在本机 `assistant/assistant.sqlite`。个人会话互相隔离,每会话最多 100 轮、每用户最多 50 个会话;全服务最多 2 个同时回复,支持 15–180 秒超时和每日轮次上限。上限统计对话轮次,运行包自身可能在一轮内重试模型请求。重启会标记未完成任务为中断,不自动重复执行。 - -当前已用**官方 CLI + 本机测试模型接口** 验证对话协议、模型参数和禁用工具;尚未配置或验证真实供应商模型认证。没有后台自主监管循环。来源、版本与限制见 [接入记录](docs/zcode-integration-2026-10-18.md)。 +已用官方 DSH + 本地假模型验证协议与空工具列表,真实模型密钥尚未配置。来源、设计与边界见 [受控助手设计](docs/superpowers/specs/2026-10-27-mail-dsh-controlled-optimization-design.md)。 ## BPM 登录 @@ -150,7 +147,7 @@ Chrome 加载扩展只需做一次。修改扩展源码、重新配对或变更 - 本地程序使用隔离的无界面 Chrome 排版,禁用页面脚本和网络;保存后关闭该排版进程,不影响你正在使用的 Chrome。 - 不导出密码、隐藏控件、ViewState、讨论输入和操作按钮,不提交或修改 BPM 订单。 - **输出是页面导出样稿,不是服务器原版 PDF,也不保证与 XForm 原生打印完全一致。** 不支持的图片、资源读取失败会在扩展中提示。网页内的附件只显示名称,不会自动合并附件。 -- 本版包含 PDF 导出、团队协作、BPM 托管、SMTP / IMAP 邮箱与模板审核及明确操作的测试发信。支持 SMB 服务器配置、PDF 归档、通用通知队列与受控 ZCode 对话;BPM 业务匹配与简要说明自动入队、后台自主监管仍待接入;不会自动处理知会或修改 BPM 审批。 +- 本版包含按规则匹配、只读采集、PDF/SMB归档、分类模板与计划批次、确认未发送订单顺延、受控DSH助手和业务台账。历史表单及隔离回放通过不等于十五类真实通知与实收全部验收完成;正式服务机部署另行安排。 ## 故障处理 diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 90ceb07..75380b9 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,5 +1,12 @@ # 开发交接(2026-10-23) +## 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-27 业务首页轻量看板 - 用户确认蓝白卡片、流程小场景和少量动效。新增首页独立模块及样式,突出下一计划发送时点、到达截止、时间进度、收集中批次及顺延数量;运行条件和异常独立展示,保留现有业务操作边界。 @@ -289,3 +296,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)。早期阶段文档的“尚未实现”以最新基准及代码为准。 - 最终验证:当前业务回归173项、provider/采集恢复/版本兼容/期限保护专项60项通过;独立复核46项通过。新增缺字段/空明细/复制/汇总行回归均先复现失败再修复。 + +- 最终候选版本验证:301项业务测试全部通过,0失败/0跳过;修复专项25项通过,生产依赖审计0条已知漏洞。审查结论:两项确认问题已修复,可合并代码;正式投产验收边界不变。 diff --git a/docs/deployment.md b/docs/deployment.md index b12ae36..ee7e1df 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -3,7 +3,7 @@ ## 安装启动 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。 4. 执行 `npm start` 或双击 `启动工具.cmd`。浏览器访问 `http://127.0.0.1:18766/`,首次自行创建管理员,无默认密码。 5. 管理员创建团队账号,配置 BPM 连接及邮箱。账号密码在 Web 中录入,不写源码、命令行或文档。 diff --git a/docs/pr-1-review-2026-10-27.md b/docs/pr-1-review-2026-10-27.md new file mode 100644 index 0000000..79dc93d --- /dev/null +++ b/docs/pr-1-review-2026-10-27.md @@ -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条已知漏洞。审查结论:两项确认问题已修复,可合并代码;正式投产验收边界不变。 diff --git a/package.json b/package.json index 20892e4..adacc69 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "service:stop": "node scripts/service.cjs stop", "service:restart": "node scripts/service.cjs restart", "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", + "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", "test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"" }, "engines": { diff --git a/src/app/application.cjs b/src/app/application.cjs index d1ab998..a9905f1 100644 --- a/src/app/application.cjs +++ b/src/app/application.cjs @@ -88,7 +88,7 @@ async function main(options = {}) { 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()}); 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); 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}); diff --git a/src/modules/assistant/repair-validator.cjs b/src/modules/assistant/repair-validator.cjs index cf3ec26..71589c8 100644 --- a/src/modules/assistant/repair-validator.cjs +++ b/src/modules/assistant/repair-validator.cjs @@ -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']; 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 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)); -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; +// The runner supplies this isolated checkout. Trust only its canonical path for +// 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; diff --git a/src/modules/mail/service.cjs b/src/modules/mail/service.cjs index 90a2991..df05bc1 100644 --- a/src/modules/mail/service.cjs +++ b/src/modules/mail/service.cjs @@ -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 safeError=(error,kind)=>error?.code==='EAUTH'||error?.authenticationFailed?`${kind} 登录失败,请检查账号和授权密码。`:/CERT|TLS|SSL|SELF_SIGNED/.test(error?.code||'')?`${kind} 加密连接失败,请检查服务器地址和证书。`:`${kind} 连接失败,请检查服务器、端口和网络后重试。`; 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);} 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()=>{ 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); 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; 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:'
Best Regards! 隔离账户签名
'}}),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'); - 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,/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,/
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=>{
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=>{
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 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');
});
diff --git a/tests/mail/template-test-policy.test.cjs b/tests/mail/template-test-policy.test.cjs
new file mode 100644
index 0000000..53f5a5a
--- /dev/null
+++ b/tests/mail/template-test-policy.test.cjs
@@ -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);
+});
diff --git a/tests/service/fixtures/crash-service-preload.cjs b/tests/service/fixtures/crash-service-preload.cjs
new file mode 100644
index 0000000..891c2e3
--- /dev/null
+++ b/tests/service/fixtures/crash-service-preload.cjs
@@ -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));}};
+}}};
diff --git a/tests/service/fixtures/crash-supervisor.cjs b/tests/service/fixtures/crash-supervisor.cjs
new file mode 100644
index 0000000..18f2e9a
--- /dev/null
+++ b/tests/service/fixtures/crash-supervisor.cjs
@@ -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);});
diff --git a/tests/service/supervisor-crash.test.cjs b/tests/service/supervisor-crash.test.cjs
new file mode 100644
index 0000000..7d41006
--- /dev/null
+++ b/tests/service/supervisor-crash.test.cjs
@@ -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() 可直接新建或编辑模板,支持纯文本与HTML。也可向托管邮箱发送 发信模板
[模板][产品线]发信标题,新版本将在这里等待确认。未填写产品线时作为默认模板。{{产品线}}、{{订单号}}、{{日期}}、{{订单列表}}、{{订单明细}}、{{存放地址}}、{{类别名称}} ${items.map(t=>`标题 / 范围 来源 `).join('')}${esc(data.channels.find(c=>c.id===t.channelId)?.name||'旧模板草稿')}
${formatDate(t.createdAt)}